Search completed in 1.21 seconds.
Index - Web APIs
ence, id, track The kind property contains a string indicating the category of audio contained in the AudioTrack. 190 AudioTrack.label API, Audio, Audio Track, AudioTrack, HTML DOM, Media, Property, Read-only, Reference, label, metadata, track The read-only AudioTrack property label returns a string specifying the audio track's human-readable label, if one is available;
otherwise, it returns an empty string. 191 AudioTrack.language API, Audio, AudioTrack, HTML DOM, Language, Localization, Media, Property, Read-only, Reference, Translated, Translation, track The read-only AudioTrack property language returns a string identifying the language used in the audio track. 192 AudioTrack.sourceBuffer API, Audio, AudioTrack, HTML DOM, MSE, Media...
...properties of this characteristic. 326 BluetoothRemoteGATTCharacteristic.readValue() API, Bluetooth, BluetoothRemoteGATTCharacteristic, Experimental, Property, Reference, Web Bluetooth API, readValue The BluetoothRemoteGATTCharacteristic.readValue() method returns a Promise that resolves to a DataView holding a duplicate of the value property if it is available and supported.
Otherwise it throws an error. 327 BluetoothRemoteGATTCharacteristic.service API, Bluetooth, BluetoothRemoteGATTCharacteristic, Experimental, Property, Reference, Service, Web Bluetooth API The BluetoothRemoteGATTCharacteristic.service read-only property returns the BluetoothGATTService this characteristic belongs to. 328 BluetoothRemoteGATTCharacteristic.startNotifications()...
...GATTCharacteristic this descriptor belongs to. 335 readValue() API, Bluetooth, BluetoothGattDescriptor, BluetoothRemoteGATTDescriptor, Experimental, Method, Reference, Web Bluetooth API, readValue() The BluetoothRemoteGATTDescriptor.readValue() method returns a Promise that resolves to an ArrayBuffer holding a duplicate of the value property if it is available and supported.
Otherwise it throws an error. 336 uuid API, Bluetooth, BluetoothRemoteGATTDescriptor, Experimental, Property, Reference, Web Bluetooth API, uuid The BluetoothRemoteGATTDescriptor.uuid read-only property returns the UUID of the characteristic descriptor, for example '00002902-0000-1000-8000-00805f9b34fb' for theClient Characteristic Configuration descriptor. 337 value API...
...And 38 more matches
Index
19 DOUBLE_TO_JSVAL JSAPI Reference, Obsolete, SpiderMonkey DOUBLE_TO_JSVAL is the inverse of JS::ToNumber. 20 INT_FITS_IN_JSVAL JSAPI Reference, Obsolete, SpiderMonkey Determines if a specified C integer value, i, lies within the range allowed for integer jsvals. If so, INT_FITS_IN_JSVAL returns TRUE, and i can be cast to jsval by calling INT_TO_JSVAL(i).
Otherwise, INT_FITS_IN_JSVAL returns FALSE. In this case, the application can still convert i to a jsval using JS_NewNumberValue. 21 INT_TO_JSVAL JSAPI Reference, Obsolete, SpiderMonkey INT_TO_JSVAL converts a C integer, i, to a jsval. 22 JS::Add*Root JSAPI Reference, NeedsContent, Obsolete, Reference, Reference(2), SpiderMonkey These functions are obsoleted, use J...
...among a number of objects, and which contains the JSObjectOps *ops pointer used to dispatch object operations from API calls. 112 JSHasInstanceOp JSAPI Reference, Reference, Reference(2), SpiderMonkey JSHasInstanceOp is called to check whether v is an instance of obj. Return false on error or exception, true on success with true in *bp if v is an instance of obj, false in *bp
otherwise. 113 JSID_EMPTY JSAPI Reference, Reference, Reference(2), SpiderMonkey JSID_EMPTY is an internal jsid value which is used in type inference code. 114 JSID_IS_EMPTY JSAPI Reference, Reference, Reference(2), SpiderMonkey JSID_IS_EMPTY tests whether a specified JS ID, id, is JSID_EMPTY. 115 JSID_IS_GCTHING JSAPI Reference, Reference, Reference...
... of (a concrete subclass of) JSObjectMap (see jsobj.h), with the nrefs and ops members initialized from the same-named parameters, and with the nslots and freeslot members initialized according to ops and clasp. Return null on error, non-null on success. 140 JSObjectOps.setProto JSAPI Reference, Obsolete, SpiderMonkey These hooks must check for cycles without deadlocking, and
otherwise take special steps. See js_SetPrototype or js_SetParent in js/src/jsobj.cpp for an example. 141 JSObjectPrincipalsFinder JSAPI Reference, Obsolete, SpiderMonkey The JavaScript engine calls this callback to obtain principals for a JSPrincipals.subsume check. 142 JSPRINCIPALS_HOLD JSAPI Reference, Obsolete, SpiderMonkey JSPRINCIPALS_HOLD and JSPRINCIPALS_DR...
...And 27 more matches
CustomizableUI.jsm
will happen when they're added to the DOM and are not hidden). If you don't, and your toolbar has a defaultset attribute, CustomizableUI will register it automatically. If your toolbar does not have a defaultset attribute, the node will be saved for processing when you call registerArea. Note that CustomizableUI won't restore state in the area, allow the user to customize it in customize mode, or
otherwise deal with it, until the area has been registered. registerMenuPanel() Register the menu panel node. This method should not be called by anyone apart from the built-in PanelUI. Parameters aPanel the panel DOM node being registered. unregisterArea() Unregister a customizable area. The inverse of registerArea. Unregistering an area will remove all the (removable) widgets in the area, whic...
...tomizableUI, this will throw. If the area to which you try to add has not yet been restored from its legacy state (currentset attribute), this will postpone the addition. If the area to which you try to add is the same as the area in which the widget is currently placed, this will do the same as moveWidgetWithinArea. If the widget cannot be removed from its original location, this will no-op.
Otherwise, this will fire an onWidgetAdded notification, and an onWidgetBeforeDOMChange and onWidgetAfterDOMChange notification for each window CustomizableUI knows about. Parameters aWidgetId the ID of the widget to add aAreaId the ID of the area to add the widget to [optional] aPosition the position at which to add the widget. If you do not pass a position, the widget will be added to the end of...
...bout. Parameters aWidgetId the ID of the widget to add aAreaId the ID of the area to add the widget to [optional] aPosition the position at which to add the widget. If you do not pass a position, the widget will be added to the end of the area. removeWidgetFromArea() Remove a widget from its area. If the widget cannot be removed from its area, or is not in any area, this will no-op. ...
...And 10 more matches
Bytecode Descriptions
Evaluation. Format: JOF_IC Instanceof Stack: value, target => (value instanceof target) The instanceof operator. This throws a TypeError if target is not an object. It calls target[Symbol.hasInstance](value) if the method exists. On success, the result is always a boolean value. Format: JOF_IC In Stack: id, obj => (id in obj) The in operator. Push true if obj has a property with the key id.
Otherwise push false. This throws a TypeError if obj is not an object. This can fire proxy hooks and can throw. On success, the result is always a boolean value. Format: JOF_IC Lsh, Rsh, Ursh Stack: lval, rval => (lval OP rval) Bitwise shift operators (<<, >>, >>>). Pop two values, convert them to integers, perform a bitwise shift, and push the result. Conversion can call .toString()/.valueOf() methods ...
...he branch around the iterator loop are emitted only when arr is itself a rest parameter, as in (...arr) => f(...arr), a strong hint that it's a packed Array whose prototype is Array.prototype. See js::OptimizeSpreadCall. Eval Operands: (uint16_t argc) Stack: callee, this, args[0], ..., args[argc-1] => rval Perform a direct eval in the current environment if callee is the builtin eval function,
otherwise follow same behaviour as JSOp::Call. All direct evals use one of the JSOp::*Eval instructions here and these opcodes are only used when the syntactic conditions for a direct eval are met. If the builtin eval function is called though other means, it becomes an indirect eval. Direct eval causes all bindings in enclosing non-global scopes to be marked "aliased". The optimization that puts bindings ...
... # resultPromise GetAliasedVar ".generator" # resultPromise gen Await # resolved gen resumeKind AfterYield AsyncAwait arranges for this frame to be resumed later and pushes its result promise. Await then suspends the frame and removes it from the stack, returning the result promise to the caller. (If this async call hasn't awaited before, the caller may be user code.
Otherwise, the caller is self-hosted code using resumeGenerator.) In async generators: ... # valueToAwait GetAliasedVar ".generator" # valueToAwait gen Await # resolved gen resumeKind AfterYield AsyncAwait is not used, so (1) the value returned to the caller by Await is valueToAwait, not resultPromise; and (2) the caller is responsible for doing the asyn...
...And 10 more matches
Index - Archive of obsolete content
oject presentations Presentations This article provides links to presentations covering various aspects of the Mozilla project. 565 Mozprocess mozprocess provides python process management via an operating system and platform transparent interface to Mozilla platforms of interest. Mozprocess aims to provide the ability to robustly terminate a process (by timeout or
otherwise), along with any child processes, on Windows, OS X, and Linux. Mozprocess utilizes and extends subprocess.Popen to these ends. 566 Mozprofile Junk Mozprofile is a python tool for creating and managing profiles for Mozilla's applications (Firefox, Thunderbird, etc.). In addition to creating profiles, mozprofile can install addons and set preferences. Mozprofile can be utilize...
... 1676 Template Builder Interface XUL, XUL_Template_Guide When inserting an element into a XUL document, the element is checked to see if it has a datasources attribute. If so, a template builder will be created for the element and attached to the element. If the element is a <tree> element and has the flags attribute set to "dont-build-content", a tree builder will be created.
Otherwise, a content builder will be created. Both types of builder share much of the same code except for how they generate output to be displayed. Both types of builders implement the nsIXULTemplateBuilder interface, while the tree builder also implements the nsIXULTreeBuilder interface. 1677 Template Logging Debugging problems with a template can be difficult as many problems are l...
... vbox XUL Elements, XUL Reference A container element which can contain any number of child elements. This is equivalent to the box element, except it defaults to vertical orientation. 1946 where XUL Elements, XUL Reference Indicate a condition that must match for a template result to be used. If the condition is true, the corresponding action body is generated;
otherwise the result is ignored and no content is generated. 1947 window XUL Elements, XUL Reference Describes the structure of a top-level window. It is the root node of a XUL document. It is by default a horizontally oriented box. As it is a box, all box attributes can be used. By default, the window will have a platform-specific frame around it. 1948 wizard XUL Elemen...
...And 9 more matches
WebIDL bindings
bject& aGlobal, uint32_t aSomeNumber, ErrorResult& rv); }; C++ reflections of WebIDL types The exact C++ representation for WebIDL types can depend on the precise way that they're being used (e.g., return values, arguments, and sequence or dictionary members might all have different representations). Unless stated
otherwise, a type only has one representation. Also, unless stated
otherwise, nullable types are represented by wrapping Nullable<> around the base type. In all cases, optional arguments which do not have a default value are represented by wrapping const Optional<>& around the representation of the argument type. If the argument type is a C++ reference, it will also become a NonNull<> around the actual ty...
...rm is preferred because it results in faster code, but it should only be used if the return value was not addrefed (and so it can only be used if the return value is kept alive by the callee until at least the binding method has returned). WebIDL callback interfaces in sequences, dictionaries, owning unions, and variadic arguments are represented by RefPtr<Foo> if nullable and OwningNonNull<Foo>
otherwise. If the interface is a single-operation interface, the object exposes two methods that both invoke the same underlying JS callable. The first of these methods allows the caller to pass in a this object, while the second defaults to undefined as the this value. In either case, the this value is only used if the callback interface is implemented by a JS callable. If it's implemented by an object ...
... (rv.Failed()) { // The error has already been reported to the JS console; you can handle // things however you want here. return; } // For some reason we want to catch and rethrow exceptions from SetSomeNumber, say. aCallback.SetSomeNumber(2*number, rv, eRethrowExceptions); if (rv.Failed()) { // The exception is now stored on rv. This code MUST report // it usefully;
otherwise it will assert. } } External interfaces External interfaces are represented in C++ as objects that XPConnect knows how to unwrap to. This can mean XPCOM interfaces (whether declared in XPIDL or not) or it can mean some type that there's a castable native unwrapping function for. The C++ type to be used should be the nativeType listed for the external interface in the Bindings.conf file. The ...
...And 9 more matches
sslfnc.html
the SSL version number 3.1, appearing to be a "minor" revision of SSL 3.0. NSS 2.8 supports TLS in addition to SSL2 and SSL3. You can think of it as "SSL_ENABLE_SSL3.1". See the description below for more information about this option. SSL_V2_COMPATIBLE_HELLO tells the SSL library whether or not to send SSL3 client hello messages in SSL2-compatible format. If set to PR_TRUE, it will;
otherwise, it will not. Factory setting is on (PR_TRUE). See the description below for more information on this option. SSL_NO_CACHE disallows use of the session cache. Factory setting is off. If you turn this option on, this socket will be unable to resume a session begun by another socket. When this socket's session is finished, no other socket will be able to resume the session begun by thi...
... cipher One of the following values for SSL2 (factory settings for all are enabled): SSL_EN_RC4_128_WITH_MD5 SSL_EN_RC4_128_EXPORT40_WITH_MD5 SSL_EN_RC2_128_CBC_WITH_MD5 SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5 SSL_EN_DES_64_CBC_WITH_MD5 SSL_EN_DES_192_EDE3_CBC_WITH_MD5 Or one of the following values for SSL3/TLS (unless indicated
otherwise, factory settings for all are enabled): TLS_DHE_RSA_WITH_AES_256_CBC_SHA (not enabled by default; client side only) TLS_DHE_DSS_WITH_AES_256_CBC_SHA (not enabled by default; client side only) TLS_RSA_WITH_AES_256_CBC_SHA (not enabled by default) SSL_FORTEZZA_DMS_WITH_RC4_128_SHA TLS_DHE_DSS_WITH_RC4_128_SHA (not enabled by default; client side only) TLS_DHE_RSA_WITH...
...pherPrefGetDefault returns the factory setting. SSL_ClearSessionCache Empties the SSL client session ID cache. Syntax #include "ssl.h" void SSL_ClearSessionCache(void); Description You must call SSL_ClearSessionCache after you use one of the SSL Export Policy Functions to change cipher suite policy settings or use SSL_CipherPrefSetDefault to enable or disable any cipher suite.
Otherwise, the old settings remain in the session cache and will be used instead of the new settings. This function clears only the client cache. The client cache is not configurable. It is located in RAM (not on disk), and has the following characteristics: maximum number of entries: unlimited SSL 2.0 timeout value: 100 seconds SSL 3.0 timeout value: 24 hours NOTE: If an SSL client applicati...
...And 7 more matches
source-editor.jsm
e index into the text at which str was found, or -1 if the string wasn't found. lastFound Number The index of the previous location at which str was found, for multiple find operations (such as find() followed by findNext()). This can be -1 if the string was never found. ignoreCase Boolean true if the search was case sensitive;
otherwise false. readOnly Boolean Set this value to true to make the editor read only, thereby preventing the user from making changes. Set it to false to allow editing. Constants Preference name constants These constants define the names of preferences used by the source editor. Constant Value Description SourceEditor.PREFS.COMPONENT ...
...ing aEventType, Function aCallback ); Parameters aEventType The name of the event type to listen for; see Event name constants for possible values. aCallback The function to call when the specified event occurs. canRedo() Determines whether or not there are changes that can be redone. Boolean canRedo(); Parameters None. Return value true if there are changes that can be redone,
otherwise false. canUndo() Determines whether or not there are changes that can be undone. Boolean canUndo(); Parameters None. Return value true if there are changes that can be undone,
otherwise false. destroy() Destroys the editor, releasing resource it's allocated and removing event handlers it's installed. You should call this method when you're done using the editor object. void destroy(); ...
...st character of the found string is located, or -1 if the string wasn't found. Find options The aOptions object can customize the search operation. It may have the following properties: Property Type Description backwards Boolean If true, the search begins at start (or the end of the text, if start is not specified) and progresses toward the beginning of the text.
Otherwise the search progresses forward. The default is false. ignoreCase Boolean If true, the search is performed in a case-insensitive manner;
otherwise case is considered. The default is false. start Number An integer value indicating the offset into the text at which to begin the find operation. The default is 0 if backwards is false, or text.length if backwards is true. ...
...And 5 more matches
Shell global objects
ring memory barrier. setSharedArrayBuffer() Install the SharedArrayBuffer object in the cross-worker mailbox. setSharedArrayBuffer performs an ordering memory barrier. shapeOf(obj) Get the shape of obj (an implementation detail). groupOf(obj) Get the group of obj (an implementation detail). unwrappedObjectsHaveSameShape(obj1, obj2) Returns true iff obj1 and obj2 have the same shape, false
otherwise. Both objects are unwrapped first, so this can be used on objects from different globals. sleep(dt) Sleep for dt seconds. compile(code) Compiles a string to bytecode, potentially throwing. parseModule(code) Parses source text as a module and returns a Module object. setModuleResolveHook(function(module, specifier) {}) Set the HostResolveImportedModule hook to function. This hook is used t...
...ent o. If the property is omitted or v is null, don't attribute the source to any DOM element. elementAttributeName if present and not undefined, the name of property of element that holds this code. This is what Debugger.Source.prototype.elementAttributeName returns. runOffThreadScript() Wait for off-thread compilation to complete. ...
...A negative value (default) means that the execution time is unlimited. If a second argument is provided, it will be invoked when the timer elapses. ...
...And 5 more matches
nsIDOMWindowUtils
count can't be provided. focusedInputType string The type of the currently-focused HTML <input> element, if one is focused. imageAnimationMode unsigned short Returns the image animation mode of the window. The attribute's value must be one of the animationMode values from imgIContainer. IMEIsOpen boolean Returns the IME open state. True if it's open,
otherwise false. This attribute only works when IMEStatus is IME_STATUS_ENABLED. Read only. IMEStatus unsigned long Returns the current IME status. Values correspond to the IME_STATUS_* constants defined below. Read only. isMozAfterPaintPending boolean Returns true if a MozAfterPaint event has been queued but not yet fired. Read only. layerManagerType AString ...
... layer manager the widget associated with this window is using. "Basic" is unaccelerated; other types are accelerated. Throws an error if there is no widget associated with this window. Read only. outerWindowID unsigned long long The ID of the window's outer window. Read only. paintingSuppressed boolean true if painting is currently suppressed for this window;
otherwise false. Read only. This is used on mobile, for example, to prevent attempts to render content until enough of the page has been loaded to avoid content bouncing around excessively as more content is loaded. screenPixelsPerCSSPixel float Returns the number of screen pixels per CSS pixel. Read only. audioMuted boolean With this it's possible to mute all the M...
... QUERY_SELECTED_TEXT 3200 QUERY_SELECTED_TEXT queries the first selection range's information. QUERY_TEXT_CONTENT 3201 QUERY_TEXT_CONTENT queries the text at the specified range. QUERY_CARET_RECT 3203 QUERY_CARET_RECT queries the (collapsed) caret rect of the offset. If the actual caret is there at the specified offset, this returns the actual caret rect.
Otherwise, this guesses the caret rect from the metrics of the text. QUERY_TEXT_RECT 3204 QUERY_TEXT_RECT queries the specified text's rect. QUERY_EDITOR_RECT 3205 QUERY_TEXT_RECT queries the focused editor's rect. QUERY_CHARACTER_AT_POINT 3208 QUERY_CHARACTER_AT_POINT queries the character information at the specified point. The point is offset in the w...
...And 5 more matches
nsITreeView
ex, in long orientation, in nsIDOMDataTransfer dataTransfer ); Parameters index The index of the row. orientation The position around the given row. Defined in constants. dataTransfer This parameter, added in Gecko 1.9.2, provides the data being dragged, so that it can be examined to determine if a drop is possible. Return value true if a drop is allowed at the current location;
otherwise false. canDropBeforeAfter() Obsolete since Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method used by the drag feedback code to determine if a drag is allowable at the current location. To get the behavior where drops are only allowed on items, such as the mailNews folder pane, always return false from canDropBeforeAfter(). boolean canDropBeforeAfter( ...
... allowable at the current location. To get the behavior where drops are only allowed on items, such as the mailNews folder pane, always return false from canDropBeforeAfter(). boolean canDropBeforeAfter( in long index, in boolean before ); Parameters index The index of the item. before true to test drop before. false to test drop after. Return value true if a drop event can occur.
Otherwise false. canDropOn() Obsolete since Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method used by the drag feedback code to determine if a drag is allowable at the current location. To get the behavior where drops are only allowed on items, such as the mailNews folder pane, always return false from canDropBeforeAfter(). boolean canDropOn( in long index ); ...
... / SeaMonkey 1.0) Method used by the drag feedback code to determine if a drag is allowable at the current location. To get the behavior where drops are only allowed on items, such as the mailNews folder pane, always return false from canDropBeforeAfter(). boolean canDropOn( in long index ); Parameters index The index of the item. Return value true if a drop event can occur.
Otherwise false. cycleCell() Called on the view when a cell in a non-selectable cycling column (for example, unread/flag/and so on.) is clicked. void cycleCell( in long row, in nsITreeColumn col ); Parameters row The row of the cell. col The column of the cell. cycleHeader() Called on the view when a header is clicked. void cycleHeader( in nsITreeColumn col ); Parameters col The ...
...And 5 more matches
Debugger - Firefox Developer Tools
Object A Debugger instance inherits the following accessor properties from its prototype: enabled A boolean value indicating whether this Debugger instance's handlers, breakpoints, and the like are currently enabled. It is an accessor property with a getter and setter: assigning to it enables or disables this Debugger instance; reading it produces true if the instance is enabled, or false
otherwise. This property is initially true in a freshly created Debugger instance. This property gives debugger code a single point of control for disentangling itself from the debuggee, regardless of what sort of events or handlers or "points" we add to the interface. allowUnobservedAsmJS A boolean value indicating whether asm.js code running inside this Debugger instance's debuggee globals is inv...
...on each Debugger instance that is observing the debuggee. The handler functions receive the Debugger instance as their this value. Most handler functions can return a resumption value indicating how the debuggee's execution should proceed. On a new Debugger instance, each of these properties is initially undefined. Any value assigned to a debugging handler must be either a function or undefined;
otherwise a TypeError is thrown. Handler functions run in the same thread in which the event occurred. They run in the compartment to which they belong, not in a debuggee compartment. onNewScript(script,global) New code, represented by the Debugger.Script instancescript, has been loaded in the scope of the debuggees. This method's return value is ignored. onNewPromise(promise) A new Promise ...
...xceptionvalue has been thrown, and has propagated toframe;frame is the youngest remaining stack frame, and is a debuggee frame. This method should return a resumption value specifying how the debuggee's execution should proceed. If it returns undefined, the exception continues to propagate as normal: if control in frame is in a try block, control jumps to the corresponding catch or finally block;
otherwise,frame is popped, and the exception propagates toframe's caller. When an exception's propagation causes control to enter a finally block, the exception is temporarily set aside. If the finally block finishes normally, the exception resumes propagation, and the debugger's onExceptionUnwind handler is called again, in the same frame. (The other possibility is for the finally block to exit due to a...
...And 5 more matches
lang/type - Archive of obsolete content
Functions for working with type detection. Globals Functions isUndefined(value) Returns true if value is undefined, false
otherwise. let { isUndefined } = require('sdk/lang/type'); var foo; isUndefined(foo); // true isUndefined(0); // false Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is undefined. isNull(value) Returns true if value is null, false
otherwise. let { isNull } = require('sdk/lang/type'); isNull(null); // true isNull(false); // false Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is null. isString(value) Returns true if value is a String, false
otherwise. Uses typeof operator to check type, and will only properly detect string primitives: for example, a string creat...
...y detect string primitives: for example, a string created with new String() will always return false. let { isString } = require('sdk/lang/type'); isString('my string'); // true isString(100); // false isString('100'); // true Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is a String. isNumber(value) Returns true if value is a Number, false
otherwise. Uses typeof operator to check type, and will only properly detect number primitives: for example, a number created with new Number() will always return false. let { isNumber } = require('sdk/lang/type'); isNumber(3.1415); // true isNumber(100); // true isNumber('100'); // false Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is a Number. isRe...
...operly detect number primitives: for example, a number created with new Number() will always return false. let { isNumber } = require('sdk/lang/type'); isNumber(3.1415); // true isNumber(100); // true isNumber('100'); // false Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is a Number. isRegExp(value) Returns true if value is a RegExp, false
otherwise. let { isRegExp } = require('sdk/lang/type'); isRegExp(/[^\.]*\.js$/); // true isRegExp(new RegExp('substring')); // true isRegExp(1000); // false Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is a RegExp. isDate(value) Returns true if value is a Date, false
otherwise. let { isDate } = require('sdk/lang/type'); isDate(new Date()); // true...
...And 4 more matches
Parsing microformats in JavaScript - Archive of obsolete content
rmats. Methods dateTimeGetter() Specifically retrieves a date from a microformat node. After getting the text, it is normalized into an ISO 8601 date. normalizedDate = Microformats.parser.dateTimeGetter(propnode, parentnode); Parameters propnode The DOM node to check. parentnode The property's parent node. If it is a subproperty, this is the parent property node.
Otherwise this is the microformat node. Return value A string containing the normalized date. defaultGetter() Uses the microformat patterns to decide what the correct text for a given microformat property is. This includes looking at thing such as abbr, img and alt, area and alt, and value excerpting. propertyValue = Microformats.parser.defaultGetter(propnode, parentnode, datatype); Parameters ...
... correct text for a given microformat property is. This includes looking at thing such as abbr, img and alt, area and alt, and value excerpting. propertyValue = Microformats.parser.defaultGetter(propnode, parentnode, datatype); Parameters propnode The DOM node to check. parentnode The property's parent node. If it is a subproperty, this is the parent property node.
Otherwise this is the microformat node. datatype "HTML" if the search should be done using innerHTML(), or "text" to use innerText(). The default is "text". Return value A string containing the property's value. emailGetter() Specifically retrieves an email address from a microformat node. This removes the subject if one is specified, as well as the mailto: prefix. email = Microformats.parse...
...y's value. emailGetter() Specifically retrieves an email address from a microformat node. This removes the subject if one is specified, as well as the mailto: prefix. email = Microformats.parser.emailGetter(propnode, parentnode); Parameters propnode The DOM node to check. parentnode The property's parent node. If it is a subproperty, this is the parent property node. ...
...And 4 more matches
nsIFile
or not two nsIFile instances correspond to the same file or directory. boolean equals( in nsIFile inFile ); Parameters inFile The nsIFile to compare this nsIFile against. Return value true if "inFile" is equivalent to this nsIFile. exists() This method tests whether or not this nsIFile exists. boolean exists() Parameters None. Return value true if the file or directory exists.
Otherwise it returns false. isDirectory() This method tests whether or not this nsIFile corresponds to a directory. boolean isDirectory(); Parameters None. Return value true if this nsIFile corresponds to a directory.
Otherwise it returns false. isExecutable() This method tests whether or not this nsIFile corresponds to a file that may be executed. Note: This method does not work on all platfor...
... This method will throw NS_ERROR_FILE_NOT_FOUND if the path is invalid. To avoid this, check with nsIFile.exists() first. ...
... This method will throw NS_ERROR_FILE_NOT_FOUND if the path is invalid. To avoid this, check with nsIFile.exists() first. ...
...And 4 more matches
nsITextInputProcessor
InputTransaction(in nsIDOMWindow aWindow, in nsITextInputProcessorCallback aCallback); Parameters aWindow The DOM window which has focused editor. This must not be null. aCallback The callback object. This must not be null. See the document of nsITextInputProcessorCallback for the details. Return value Returns true if the instance could create composition.
Otherwise, false. beginInputTransactionForTests() This must be called before starting composition for automated tests every time. This tries to get the rights to create composition on the window. If no other instance is composing on the window, this associates the instance with the window and registers the callback to the instance if it's specified. boolean beginInputTransactionForTests(in nsIDOMWindow ...
... in nsITextInputProcessorCallback aCallback Optional); Parameters aWindow The DOM window which has focused editor. This must not be null. aCallback The callback object. If this is not specified, requests to IMEs are handled automatically. See the document of nsITextInputProcessorCallback for the details. Return value Returns true if the instance could create composition.
Otherwise, false. cancelComposition() Cancels the composition which was created by the instance. If you call this when there is no composition, this throws an exception. void cancelComposition(in nsIDOMKeyEvent aDOMKeyEvent Optional, in unsigned long aKeyFlags Optional); Parameters aDOMKeyEvent Optional When the canceling composition is caused by a key operation, this should ...
...d when Gecko thinks that they should be. See also How to create KeyboardEvent instance for nsITextInputProcessor. aKeyFlags Optional See KEY_* constants. If this is not specified, the value is assumed as 0. Return value When there is no composition which was created by the instance and if compositionstart is consumed by web contents, i.e., failed to start new composition, this returns false.
Otherwise, it returns true. getModifierState() Getting modifier state. This is similar to KeyboardEvent.getModifierState() [en-US]. The result is the modifier state of managed by the instance. boolean getModifierState(in DOMString aModifierKeyName); Parameters aModifierKeyName A modifier key name which is defined by DOM Level 3 KeyboardEvents key Values. Return value true if the modifier state i...
...And 4 more matches
Index
hmmssZ Field "next update" is optional. Time should be in GeneralizedTime format (YYYYMMDDhhmmssZ). For example: 20050204153000Z * Add an extension to a CRL or a crl certificate entry: addext extension-name critical/non-critical [arg1[arg2 ...]] Where: extension-name: string value of a name of known extensions. critical/non-critical: is 1 when extension is critical and 0
otherwise. arg1, arg2: specific to extension type extension parameters addext uses the range that was set earlier by addcert and will install an extension to every cert entries within the range. * Add certificate entries(s) to CRL: addcert range date range: two integer values separated by dash: range of certificates that will be added by this command. dash is used as a delimiter. O...
...#3280 * Add The Authority Key Identifier extension: The authority key identifier extension provides a means of identifying the public key corresponding to the private key used to sign a CRL. authKeyId critical [key-id | dn cert-serial] Where: authKeyIdent: identifies the name of an extension critical: value of 1 of 0. Should be set to 1 if this extension is critical or 0
otherwise. key-id: key identifier represented in octet string. dn:: is a CA distinguished name cert-serial: authority certificate serial number. * Add Issuer Alternative Name extension: The issuer alternative names extension allows additional identities to be associated with the issuer of the CRL. Defined options include an rfc822 name (electronic mail address), a DNS name, an IP addres...
... invalidityDate non-critical date Where: crlNumber: identifies the name of an extension non-critical: should be set to 0 since this is non-critical extension date: invalidity date of a cert. Date should be represented in GeneralizedTime format (YYYYMMDDhhmmssZ). Usage The Certificate Revocation List Management Tool's capabilities are grouped as follows, us...
...And 3 more matches
Debugger.Object - Firefox Developer Tools
proto The referent's prototype (as a new Debugger.Object instance), or null if it has no prototype. This accessor may throw if the referent is a scripted proxy or some other sort of exotic object (an opaque wrapper, for example). class A string naming the ECMAScript [[Class]] of the referent. callable true if the referent is a callable object (such as a function or a function proxy); false
otherwise. name The name of the referent, if it is a named function. If the referent is an anonymous function, or not a function at all, this is undefined. This accessor returns whatever name appeared after the function keyword in the source code, regardless of whether the function is the result of instantiating a function declaration (which binds the function to its name in the enclosing scope) or e...
...f the referent is a function that is debuggee code, a Debugger.Environment instance representing the lexical environment enclosing the function when it was created. If the referent is a function proxy or not debuggee code, this is undefined. errorMessageName If the referent is an error created with an engine internal message template this is a string which is the name of the template; undefined
otherwise. errorLineNumber If the referent is an Error object, this is the line number at which the referent was created; undefined
otherwise. errorColumnNumber If the referent is an Error object, this is the column number at which the referent was created; undefined
otherwise. isBoundFunction If the referent is a debuggee function, returns true if the referent is a bound function; false
otherwise. I...
...If the referent is not a debuggee function, or not a function at all, returns undefined instead. isGeneratorFunction If the referent is a debuggee function, returns true if the referent was created with a function* expression or statement, or false if it is some other sort of function. ...
...And 3 more matches
Midas
for the given command. Supported Commands Command Value Description backcolor A color code. This command will set the background color of the document. bold If there is no selection, the insertion point will set bold for subsequently typed characters. If there is a selection and all of the characters are already bold, the bold will be removed.
Otherwise, all selected characters will become bold. contentReadOnly This command will make the editor readonly(true)or editable(false). Anticipated usage is for temporarily disabling input while something else is occurring elsewhere in the web page. copy If there is a selection, this command will copy the selection to the clipboard. If there isn't a selection, nothing w...
...at block becomes the first LI and UL. If the caret is inside a numbered item, the numbered item becomes a bulleted item. insertparagraph Inserts a new paragraph. italic If there is no selection, the insertion point will set italic for subsequently typed characters. If there is a selection and all of the characters are already italic, the italic will be removed.
Otherwise, all selected characters will become italic. justifycenter Center-aligns the current block. justifyfull Fully-justifies the current block. justifyleft Left-aligns the current block. justifyright Right aligns the current block. outdent Outdent the block where the caret is located. If the block is not indented prior...
...ommand will select all of the contents within the editable area. note: the shortcut key will automatically trigger this command (typically accel-A) strikethrough If there is no selection, the insertion point will set strikethrough for subsequently typed characters. If there is a selection and all of the characters are already striked, the strikethrough will be removed.
Otherwise, all selected characters will have a line drawn through them. styleWithCSS This command is used for toggling the format of generated content. By default (at least today), this is true. An example of the differences is that the "bold" command will generate <b> if the styleWithCSS command is false and generate css style attribute if the styleWithCSS command is true. sub...
...And 2 more matches
IAccessibleTable
sed, [out] value is 0. S_OK. columnDescription() Returns the description text of the specified column in the table. [propget] HRESULT columnDescription( [in] long column, [out] BSTR description ); Parameters column The 0 based index of the column for which to retrieve the description. description Returns the description text of the specified column in the table if such a description exists.
Otherwise a null pointer is returned. Return value E_INVALIDARG if bad [in] passed, [out] value is null. S_FALSE if there is nothing to return, [out] value is null. S_OK. columnExtentAt() Returns the number of columns occupied by the accessible object at the specified row and column in the table. The result is greater than 1 if the specified cell spans multiple columns. [propget] HRESULT columnExtentAt( ...
...assed, [out] value is 0. S_OK. isColumnSelected() Returns a boolean value indicating whether the specified column is completely selected. [propget] HRESULT isColumnSelected( [in] long column, [out] boolean isSelected ); Parameters column 0 based index of the column for which to determine whether it is selected. isSelected Returns true if the specified column is selected completely and false
otherwise. Return value E_INVALIDARG if bad [in] passed, [out] value is false. S_OK. isRowSelected() Returns a boolean value indicating whether the specified row is completely selected. [propget] HRESULT isRowSelected( [in] long row, [out] boolean isSelected ); Parameters row 0 based index of the row for which to determine whether it is selected. isSelected Returns true if the specified row is selec...
...ARG if bad [in] passed, [out] value is false. S_OK. isRowSelected() Returns a boolean value indicating whether the specified row is completely selected. [propget] HRESULT isRowSelected( [in] long row, [out] boolean isSelected ); Parameters row 0 based index of the row for which to determine whether it is selected. isSelected Returns true if the specified row is selected completely and false
otherwise. Return value E_INVALIDARG if bad [in] passed, [out] value is false. S_OK. isSelected() Returns a boolean value indicating whether the specified cell is selected. [propget] HRESULT isSelected( [in] long row, [in] long column, [out] boolean isSelected ); Parameters row 0 based index of the row for the cell to determine whether it is selected. column 0 based index of the column for the cel...
...And 2 more matches
nsIAnnotationService
aValue The annotation value. aFlags Should be "0" for now, some flags will be defined in the future. aExpiration One of the EXPIRE_* constant value defined above. Note: ALL PAGE ANNOTATIONS WILL GET DELETED WHEN THE PAGE IS REMOVED FROM HISTORY IF THE PAGE IS NOT BOOKMARKED. This means that if you create an annotation on an unvisited URI, it will get deleted when the browser shuts down.
Otherwise, URIs can exist in history as annotations but the user has no way of knowing it, potentially violating their privacy expectations about actions such as Clear history. If there is an important annotation that the user or extension wants to keep, you should add a bookmark for the page and use an EXPIRE_NEVER annotation. This will ensure the annotation exists until the item is removed by the user. ...
... aValue The annotation value. aFlags Should be "0" for now, some flags will be defined in the future. aExpiration One of the EXPIRE_* constant value defined above. Note: ALL PAGE ANNOTATIONS WILL GET DELETED WHEN THE PAGE IS REMOVED FROM HISTORY IF THE PAGE IS NOT BOOKMARKED. This means that if you create an annotation on an unvisited URI, it will get deleted when the browser shuts down.
Otherwise, URIs can exist in history as annotations but the user has no way of knowing it, potentially violating their privacy expectations about actions such as Clear history. If there is an important annotation that the user or extension wants to keep, you should add a bookmark for the page and use an EXPIRE_NEVER annotation. This will ensure the annotation exists until the item is removed by the user. ...
...al Count of annotations name available. result Returns the name of all annotations. pageHasAnnotation() This method tests for annotation existance for given URI. boolean pageHasAnnotation( in nsIURI aURI, in AUTF8String aName ); Parameters aURI The URI on which the annotation is set. aName The annotation name. Return value Returns true, if an annotation exists for given URI,
otherwise returns false. itemHasAnnotation() This method tests for annotation existance for given item. boolean itemHasAnnotation( in long long aItemId, in AUTF8String aName ); Parameters aItemId The item on which the annotation is set. aName The annotation name. Return value Returns true, if an annotation exists for given item,
otherwise returns false. removePageAnnotation() This metho...
...And 2 more matches
SubtleCrypto.verify() - Web APIs
ontaining the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. signature is a ArrayBuffer containing the signature to verify. data is a ArrayBuffer containing the data whose signature is to be verified. Return value result is a Promise that fulfills with a Boolean: true if the signature is valid, false
otherwise. Exceptions The promise is rejected when the following exception is encountered: InvalidAccessError Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. Supported algorithms The verify() method supports the same algorithms as the sign() method. Examples Not...
...d encode it in a form we can use for sign operation. */ function getMessageEncoding() { const messageBox = document.querySelector(".rsassa-pkcs1 #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } /* Fetch the encoded message-to-sign and verify it against the stored signature. * If it checks out, set the "valid" class on the signature. *
Otherwise set the "invalid" class. */ async function verifyMessage(publicKey) { const signatureValue = document.querySelector(".rsassa-pkcs1 .signature-value"); signatureValue.classList.remove("valid", "invalid"); let encoded = getMessageEncoding(); let result = await window.crypto.subtle.verify( "RSASSA-PKCS1-v1_5", publicKey, signature, encoded ); signatureValue.classList.ad...
...x, and encode it in a form we can use for sign operation. */ function getMessageEncoding() { const messageBox = document.querySelector(".rsa-pss #message"); let message = messageBox.value; let enc = new TextEncoder(); return enc.encode(message); } /* Fetch the encoded message-to-sign and verify it against the stored signature. * If it checks out, set the "valid" class on the signature. *
Otherwise set the "invalid" class. */ async function verifyMessage(publicKey) { const signatureValue = document.querySelector(".rsa-pss .signature-value"); signatureValue.classList.remove("valid", "invalid"); let encoded = getMessageEncoding(); let result = await window.crypto.subtle.verify( { name: "RSA-PSS", saltLength: 32, }, publicKey, signature, encoded ); ...
...And 2 more matches
Background audio processing using AudioWorklet - Web APIs
n AudioWorkletNode before playing the resulting sound out. Slider controls are available to allow controlling the gain of both the oscillator and the audio worklet's output. Glitch Project Page See the Code Try it Live Creating an audio worklet processor Fundamentally, an audio worklet processor (which we'll refer to usually as either an "audio processor" or simply as a "processor" because
otherwise this article will be about twice as long) is implemented using a JavaScript module that defines and installs the custom audio processor class. Structure of an audio worklet processor An audio worklet processor is a JavaScript module which consists of the following: A JavaScript class which defines the audio processor. This class extends the AudioWorkletProcessor class. The audio processor c...
...ecifying a value of true as the result from your process() function in essence tells the Web Audio API that your processor needs to keep being called even if the API doesn't think there's anything left for you to do. In other words, true overrides the API's logic and gives you control over your processor's lifetime policy, keeping the processor's owning AudioWorkletNode running even when it would
otherwise decide to shut down the node. Returning false from the process() method tells the API that it should follow its normal logic and shut down your processor node if it deems it appropriate to do so. If the API determines that your node is no longer needed, process() will not be called again. Note: At this time, unfortunately, Chrome does not implement this algorithm in a manner that matches the c...
...our audio processor. It also handles creating the audio context if it hasn't already been done. In order to ensure the context is usable, this starts by creating the context if it's not already available, then adds the module containing the processor to the worklet. Once that's done, it instantiates and returns a new AudioWorkletNode. Once you have that in hand, you connect it to other nodes and
otherwise use it just like any other node. You can then create a new audio processor node by simply doing this: let newProcessorNode = createMyAudioProcessor(); If the returned value, newProcessorNode, is non-null, we have a valid audio context with its hiss processor node in place and ready to use. Supporting audio parameters Just like any other Web Audio node, AudioWorkletNode supports parameters, w...
...And 2 more matches
util/array - Archive of obsolete content
Helper functions for working with arrays. Globals Functions has(array, element) Returns true if the given Array contains the element or false
otherwise. A simplified version of array.indexOf(element) >= 0. let { has } = require('sdk/util/array'); let a = ['rock', 'roll', 100]; has(a, 'rock'); // true has(a, 'rush'); // false has(a, 100); // true Parameters array : array The array to search. element : * The element to search for in the array. Returns boolean : A boolean indicating whether or not the element was found in the array. hasAny(array, elements) Returns true if the given Array contains any of the elements in the elements array, or false
otherwise. let { hasAny } = require('sdk/util/array'); let a = ['rock', 'roll', 100]; hasAny(a, ['rock', 'bright', 'light']); // true ha...
...'coil', 'jet']); // false Parameters array : array The array to search for elements. elements : array An array of elements to search for in array. Returns boolean : A boolean indicating whether or not any of the elements were found in the array. add(array, element) If the given array does not already contain the given element, this function adds the element to the array and returns true.
Otherwise, this function does not add the element and returns false. let { add } = require('sdk/util/array'); let a = ['alice', 'bob', 'carol']; add(a, 'dave'); // true add(a, 'dave'); // false add(a, 'alice'); // false console.log(a); // ['alice', 'bob', 'carol', 'dave'] Parameters array : array The array to add the element to. element : * The element to add Returns boolean : A boolean indicatin...
..., 'alice'); // false console.log(a); // ['alice', 'bob', 'carol', 'dave'] Parameters array : array The array to add the element to. element : * The element to add Returns boolean : A boolean indicating whether or not the element was added to the array. remove(array, element) If the given array contains the given element, this function removes the element from the array and returns true.
Otherwise, this function does not alter the array and returns false. let { remove } = require('sdk/util/array'); let a = ['alice', 'bob', 'carol']; remove(a, 'dave'); // false remove(a, 'bob'); // true remove(a, 'bob'); // false console.log(a); // ['alice', 'carol'] Parameters array : array The array to remove the element from. element : * The element to remove from the array if it contains it. R...
... i.add('unagi'); i.add('keon'); fromIterator(i) // ['otoro', 'unagi', 'keon'] Parameters iterator : iterator The Iterator object over which to iterate and place results into an array. Returns array : The iterator's results in an array. find(iterator) Iterates over given array and applies given predicate function until predicate(element) is true. If such element is found it's retured back
otherwise third optional fallback argument is returned back. If fallback is not provided returns undefined. let { find } = require('sdk/util/array'); let isOdd = (x) => x % 2; find([2, 4, 5, 7, 8, 9], isOdd); // => 5 find([2, 4, 6, 8], isOdd); // => undefiend find([2, 4, 6, 8], isOdd, null); // => null fromIterator(i) // ['otoro', 'unagi', 'keon'] Parameters iterator : iterator The Iterat...
Appendix D: Loading Scripts - Archive of obsolete content
a means to specify the character set and JavaScript version of the scripts to be loaded, which many other methods do not. Debuggable: development tools support debugging JavaScript loaded by script tags Disadvantages Scoping: Scripts loaded via script tags share the global scope with all other scripts loaded into the same window. These tags provide no means to load scripts into a private or
otherwise specific scope. Speed: Even if these scripts are loaded from a cache, only read and compile time are reduced. The scripts still need to execute all of their initialization code and allocate and initialize all of their data structures each time the script is loaded. Loading: Script loaded via script tags run in partially loaded documents. Problems can ensue if the script immediately attempts to ...
...y with which it can be specified makes this method useful for extracting JavaScript from a number of file formats other than raw JavaScript scripts. Additionally, as Sandbox objects can be created with an arbitrary prototype object, the evaluated code can be given access to the global properties of any existing scope. Security: Sandbox objects are initialized with a security principal object, or
otherwise a window or URL from which to derive one. This means that evalInSandbox can be used to execute code with a specified privilege level rather than full chrome privileges. Beyond this, the scope of the Sandbox can be augmented or rarified to add or remove privileges as necessary. Under ordinary circumstances, native objects passed out of Sandboxes are wrapped in XrayWrapper objects, which means that...
... scope. Namespace contamination and the resulting compatibility issues are only an issue when they are imported into shared global namespaces. Data sharing: As modules are loaded only once globally, every import has access to the same data and global variables no matter what context or window it was imported from. JavaScript modules can therefor be used for communication and data sharing between
otherwise isolated contexts. Debugging: Chromebug (at least) can list Component.utils modules and single step through them. Disadvantages Namespacing: As modules always execute with their own namespace, they have no direct access to the DOM or window properties of windows or documents, and therefore must often pass around references to these objects and any document-specific state data that they requ...
...wn global contexts which run in their own threads. In order to ensure thread safety, these contexts are extremely limited, can't be passed JavaScript objects, and have no access to the DOM. All communication between these contexts and outer contexts is marshalled through JSON encoding and decoding. ChromeWorkers also have access to ctypes and a limited number of thread safe XPCOM classes, but are
otherwise limited to simple computation based on data passed via messages and XMLHttpRequests. Advantages Asynchronous: Workers execute asynchronously in their own threads, which means that they have limited risk of interfering with the main thread. They may safely perform synchronous XMLHttpRequests or other intensive computation which would normally need to be broken up into multiple callbacks. Safe...
NPClass - Archive of obsolete content
construct; }; Warning: Don't call these routines directly. You should instead use the appropriate API functions. Fields structVersion The version number of the structure. This is set to NP_CLASS_STRUCT_VERSION, which is 1 in Mozilla 1.8.*, 2 since Mozilla 1.9a1, and 3 since Firefox 3.0b1. allocate Returns a pointer to a newly allocated NPObject. Called by NPN_CreateObject() if non-NULL,
otherwise the browser calls malloc(). This function is expected to allocate and return enough storage to hold the NPObject that is being created. deallocate Called by NPN_ReleaseObject() when an object's reference count reaches zero. If this field is NULL, free() is called isntead. invalidate Called on live objects that belong to a plugin instance that is being destroyed. This call is always followed b...
...ad. invalidate Called on live objects that belong to a plugin instance that is being destroyed. This call is always followed by a call to the deallocate function, or free(). Any attempt to use an invalidated object will result in undefined behavior. hasMethod Called by NPN_HasMethod() to determine whether or not a specified method exists on a given NPObject. Returns true if the method exists,
otherwise returns false. invoke Called by NPN_Invoke() to invoke a specific method on a given NPObject. Returns true if invocation succeeded or false if an error occurred. invokeDefault Called by NPN_InvokeDefault() to invoke the default method (if available) on a given NPObject. Returns true if invocation succeeded or false if an error occurred. hasProperty Called by NPN_HasProperty() to check wheth...
.... Returns true if invocation succeeded or false if an error occurred. invokeDefault Called by NPN_InvokeDefault() to invoke the default method (if available) on a given NPObject. Returns true if invocation succeeded or false if an error occurred. hasProperty Called by NPN_HasProperty() to check whether a given property exists on a given NPObject. Returns true if the specified property exists,
otherwise returns false. getProperty Called by NPN_GetProperty() to get the value of the specified property on a given NPObject. Returns true if the value was successfully retrieved,
otherwise returns false. setProperty Called by NPN_SetProperty() to set the value of the specified property on a given NPObject. Returns true if the value was successfully set,
otherwise returns false. removeProperty Cal...
... enumerate Called by NPN_Enumerate. This field is available only if structVersion is NP_CLASS_STRUCT_VERSION_ENUM (2) or greater. construct Called by NPN_Construct. This field is available only if structVersion is NP_CLASS_STRUCT_VERSION_CTOR (3) or greater. ...
Introduction to SSL - Archive of obsolete content
ollowing cipher suites for SSL 3.0: RC4 with 128-bit encryption and MD5 message authentication RC4 with 40-bit encryption and MD5 message authentication RC2 with 40-bit encryption and MD5 message authentication No encryption, MD5 message authentication only Cipher Suites With RSA Key Exchange Table 1 lists the cipher suites supported by SSL that use the RSA key-exchange algorithm. Unless
otherwise indicated, all ciphers listed in the table are supported by both SSL 2.0 and SSL 3.0. Cipher suites are listed from strongest to weakest. Table 1. Cipher Suites Supported by the SSL Protocol That Use the RSA Key-Exchange Algorithm Strength Category and Recommended Use Cipher Suites Strongest Cipher Suite Permitted for deployments within the United States o...
...ith one key of a public-private key pair and decrypting it with the other key: In the case of server authentication, the client encrypts the premaster secret with the server's public key. Only the corresponding private key can correctly decrypt the secret, so the client has some assurance that the identity associated with the public key is in fact the server with which the client is connected.
Otherwise, the server cannot decrypt the premaster secret and cannot generate the symmetric keys required for the session, and the session will be terminated. In the case of client authentication, the client encrypts some random data with the client's private key-that is, it creates a digital signature. The public key in the client's certificate can correctly validate the digital signature only if the cor...
...remaster secret and cannot generate the symmetric keys required for the session, and the session will be terminated. In the case of client authentication, the client encrypts some random data with the client's private key-that is, it creates a digital signature. The public key in the client's certificate can correctly validate the digital signature only if the corresponding private key was used.
Otherwise, the server cannot validate the digital signature and the session is terminated. The sections that follow provide more details on server authentication and client authentication. Server Authentication Red Hat's SSL-enabled client software always requires server authentication, or cryptographic validation by a client of the server's identity. As explained in Step 2 of "The SSL Handshake", the ...
...e user will be warned of the problem and informed that an encrypted and authenticated connection cannot be established. If the server requires client authentication, the server performs the steps described in "Client Authentication." After the steps described here, the server must successfully use its private key to decrypt the premaster secret the client sends in Step 4 of "The SSL Handshake."
Otherwise, the SSL session will be terminated. This provides additional assurance that the identity associated with the public key in the server's certificate is in fact the server with which the client is connected. Man-in-the-Middle Attack As suggested in Step 4 above, the client application must check the server domain name specified in the server certificate against the actual domain name of the serv...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
tical rendering path which is a series of steps that must happen to properly render a website. 57 CSS pixel CSS, CSS Pixel, Glossary, height, length, pixel, size, unit, width The CSS pixel--denoted in CSS with the suffix px--is a unit of length which roughly corresponds to the width or height of a single dot that can be comfortably seen by the human eye without strain, but is
otherwise as small as possible. By definition, this is the physical size of a single pixel at a pixel density of 96 DPI, located an arm's length away from the viewer's eyes. 58 CSS preprocessor CSS, Glossary A CSS preprocessor is a program that lets you generate CSS from the preprocessor's own unique syntax. 59 Cache Glossary, HTTP A cache (web cache or HTTP cache)...
...s simultaneously, resulting in a faster page load time and improved user experience. 121 Dominator CodingScripting, Glossary In graph theory, node A dominates node B if every path from the root node to B passes through A. 122 Dynamic programming language CodingScripting, Glossary A dynamic programming language is a programming language in which operations
otherwise done at compile-time can be done at run-time. For example, in JavaScript it is possible to change the type of a variable or add new properties or methods to an object while the program is running. 123 Dynamic typing CodingScripting, Glossary, ProgrammingLanguage Dynamically-typed languages are those (like JavaScript) where the interpreter assigns variables a type at runtime b...
...ine CodingScripting, Glossary, NeedsContent The JavaScript engine is an interpreter that parses and executes a JavaScript program. 133 Entity CodingScripting, Composing, Glossary, HTML An HTML entity is a piece of text ("string") that begins with an ampersand (&) and ends with a semicolon (;) . Entities are frequently used to display reserved characters (which would
otherwise be interpreted as HTML code), and invisible characters (like non-breaking spaces). You can also use them in place of other characters that are difficult to type with a standard keyboard. 134 Entity header Glossary, WebMechanics An entity header is an HTTP header that can be used in an HTTP request or response, and describes the content of the body of themessage. Headers lik...
...unction as input, and the function can optionally return a value. A function in JavaScript is also an object. 162 Fuzz testing Firefox, Fuzzing, Mozilla, QA, Security, Testing Fuzzing is a technique for testing software using automated tools to provide invalid or unexpected input to a program or function in a program, then checking the results to see if the program crashes or
otherwise acts inappropriately. This is an important way to ensure that software is stable, reliable, and secure, and we use fuzzing a lot at Mozilla. 163 GIF Composing, Glossary GIF (Graphics Interchange Format) is an image format that uses lossless compression and can be used for animations. A GIF uses up to 8 bits per pixel and a maximum of 256 colors from the 24-bit color space. ...
HTTP Cache
Elements in this global hashtable are hashtables of cache entries. The cache entries are mapped by concantation of Enhance ID and URI passed to nsICacheStorage.asyncOpenURI. So that when an entry is beeing ...
...state to NOTLOADED consumer reference ++ call to CacheEntry::AsyncOpen consumer reference -- CacheEntry::AsyncOpen (entry atomic): the opener is added to FIFO, consumer reference ++ (dropped back after an opener is removed from the FIFO) state == NOTLOADED: state = LOADING when OPEN_TRUNCATE flag was used: CacheFile is created as 'new', state = EMPTY
otherwise: CacheFile is created and load on it started CacheEntry::OnFileReady notification is now expected state == LOADING: just do nothing and exit call to CacheEntry::InvokeCallbacks CacheEntry::InvokeCallbacks (entry atomic): called on: a new opener has been added to the FIFO via an AsyncOpen call asynchronous result of CacheFile open the writer throws t...
... a new opener has been added to the FIFO via an AsyncOpen call asynchronous result of CacheFile open the writer throws the entry away the output stream of the entry has been opened or closed metaDataReady or setValid on the entry has been called the entry has been doomed state == EMPTY: on OPER_READONLY flag use: onCacheEntryAvailable with null for the cache entry
otherwise: state = WRITING opener is removed from the FIFO and remembered as the current 'writer' onCacheEntryAvailable with aNew = true and this entry is invoked (on the caller thread) for the writer state == READY: onCacheEntryCheck with the entry is invoked on the first opener in FIFO - on the caller thread if demanded result == RECHECK_AFTER_WRITE_FINISHED: ...
...opener with null for the entry opener is removed from the FIFO state == WRITING or REVALIDATING: do nothing and exit any other value of state is unexpected here (assertion failure) loop this process while there are openers in the FIFO CacheEntry::OnFileReady (entry atomic): load result == failure or the file has not been found on disk (is new): state = EMPTY
otherwise: state = READY since the cache file has been found and is usable containing meta data and data of the entry call to CacheEntry::InvokeCallbacks CacheEntry::OnHandleClosed (entry atomic): Called when any consumer throws the cache entry away If the handle is not the handle given to the current writer, then exit state == WRITING: the writer failed to call metaDataReady on the entry - state =...
Places utilities for JavaScript
he livemark service. boolean nodeIsLivemarkItem(aNode) Determines whether a result node is a live-bookmark item Parameters aNode The node to check. Return type Returns a boolean. isReadonlyFolder() Determines whether or not a node is a readonly folder. boolean isReadonlyFolder(aNode) Parameters aNode The node to check. Return type Return true if the node is a folder, false
otherwise. getIndexOfNode() Gets the index of a node within its parent container int getIndexOfNode(aNode) Parameters aNode The node to look up Return type Returns the index of the node within its parent container, or -1 if the node was not found or the node specified has no parent. wrapNode() String-wraps a result node according to the rules of the specified content type. string wrapNode(...
... within the places organizer. If we don't call this, we'll treat those visits as TRANSITION_LINK. markPageAsFollowedBookmark(string aURL) checkURLSecurity() Allows opening of javascript/data URI only if the given node is bookmarked (see bug 224521). checkURLSecurity(aURINode) Parameters aURINode a URI node Return type Return true if it's safe to open the node in the browser, false
otherwise. getQueryStringForFolder() Helper for getting a serialized Places query for a particular folder. getQueryStringForFolder(int aFolderId) Parameters aFolderId The folder id to get a query for. Return type Return string serialized place URI getDescriptionFromDocument() Get the description associated with a document, as specified in a <META> element. getDescriptionFromDocument(doc) ...
...for. Return type Return string serialized place URI getDescriptionFromDocument() Get the description associated with a document, as specified in a <META> element. getDescriptionFromDocument(doc) Parameters doc A DOM Document to get a description for Return type Returns a description string if a META element was discovered with a "description" or "httpequiv" attribute, empty string
otherwise. setPostDataForBookmark() Set the POST data associated with a bookmark, if any. Used by POST keywords. setPostDataForBookmark(int aBookmarkId, string aPostData) aBookmarkId Return type Returns string of POST data getPostDataForBookmark() Get the POST data associated with a bookmark, if any. getPostDataForBookmark(int aBookmarkId) Parameters aBookmark...
...any. Used by POST keywords. setPostDataForBookmark(int aBookmarkId, string aPostData) aBookmarkId Return type Returns string of POST data getPostDataForBookmark() Get the POST data associated with a bookmark, if any. getPostDataForBookmark(int aBookmarkId) Parameters aBookmarkId Return type Returns string of POST data if set for aBookmarkId. null
otherwise. getURLAndPostDataForKeyword() Get the URI (and any associated POST data) for a given keyword. getURLAndPostDataForKeyword(aKeyword) Parameters aKeyword keyword Return type Returns an array containing a string URL and a string of POST data getItemDescription() Retrieve the description of an item getItemDescription(aItemId) Parameters aItemId item identifier Return type R...
Observer Notifications
Application startup These are the topics that you can observe on startup, in order of appearance. If your component requires access to the user profile, or any services which require access to the profile (preferences, bookmarks, and so on) then a common pattern is to register with the nsICategoryManager for the app-startup topic which can be done in the component's registration code, and then in that notification register with the observer service for the profile-after-change notification. ...
... Data Description bookmarks-restore-begin json Sent just before bookmarks are restored from JSON. bookmarks-restore-begin html Sent just before bookmarks are restored from HTML. If bookmarks will be restored into a specific folder, observers will be passed an nsISupportsPRInt64 through their subject parameters indicating the ID of the folder. The subject is null
otherwise. bookmarks-restore-begin html-initial Sent just before bookmarks are restored from HTML on initial import. If bookmarks are restored into a specific folder, observers will be passed an nsISupportsPRInt64 through their subject parameters indicating the ID of the folder. The subject is null
otherwise. bookmarks-restore-success json Sent just after bookmarks are restore...
...ject is null
otherwise. bookmarks-restore-success json Sent just after bookmarks are restored from JSON. bookmarks-restore-success html Sent just after bookmarks are restored from HTML. If bookmarks were restored into a specific folder, observers will be passed an nsISupportsPRInt64 through their subject parameters indicating the ID of the folder. The subject is null
otherwise. bookmarks-restore-success html-initial Sent just after bookmarks are restored from HTML on initial import. If bookmarks were restored into a specific folder, observers will be passed an nsISupportsPRInt64 through their subject parameters indicating the ID of the folder. The subject is null
otherwise. bookmarks-restore-failed json Sent when bookmarks could not be suc...
...-restore-failed json Sent when bookmarks could not be sucessfully restored from JSON. bookmarks-restore-failed html Sent when bookmarks could not be successfully restored from HTML. If bookmarks were to have been restored into a specific folder, observers will be passed an nsISupportsPRInt64 through their subject parameters indicating the ID of the folder. The subject is null
otherwise. bookmarks-restore-failed html-initial Sent when bookmarks could not be successfully restored from HTML on intial import. If bookmarks were to have been restored into a specific folder, observers will be passed an nsISupportsPRInt64 through their subject parameters indicating the ID of the folder. The subject is null
otherwise. Themes These topics indicate when actions rela...
IAccessibleTable2
, [out] value is null. S_OK. columnDescription() Returns the description text of the specified column in the table. [propget] HRESULT columnDescription( [in] long column, [out] BSTR description ); Parameters column The 0 based index of the column for which to retrieve the description. description Returns the description text of the specified column in the table if such a description exists.
Otherwise a null pointer is returned. Return value E_INVALIDARG if bad [in] passed, [out] value is null. S_FALSE if there is nothing to return, [out] value is null. S_OK. isColumnSelected() Returns a boolean value indicating whether the specified column is completely selected. [propget] HRESULT isColumnSelected( [in] long column, [out] boolean isSelected ); Parameters column 0 based index of the col...
...rn, [out] value is null. S_OK. isColumnSelected() Returns a boolean value indicating whether the specified column is completely selected. [propget] HRESULT isColumnSelected( [in] long column, [out] boolean isSelected ); Parameters column 0 based index of the column for which to determine whether it is selected. isSelected Returns true if the specified column is selected completely and false
otherwise. Return value E_INVALIDARG if bad [in] passed, [out] value is false. S_OK. isRowSelected() Returns a boolean value indicating whether the specified row is completely selected. [propget] HRESULT isRowSelected( [in] long row, [out] boolean isSelected ); Parameters row 0 based index of the row for which to determine whether it is selected. isSelected Returns true if the specified row is selec...
...ARG if bad [in] passed, [out] value is false. S_OK. isRowSelected() Returns a boolean value indicating whether the specified row is completely selected. [propget] HRESULT isRowSelected( [in] long row, [out] boolean isSelected ); Parameters row 0 based index of the row for which to determine whether it is selected. isSelected Returns true if the specified row is selected completely and false
otherwise. Return value E_INVALIDARG if bad [in] passed, [out] value is false. S_OK. modelChange() Returns the type and extents describing how a table changed. Provided for use by the IA2_EVENT_TABLE_MODEL_CHANGED event handler. This data is only guaranteed to be valid while the thread notifying the event continues. Once the handler has returned, the validity of the data depends on how the server manages ...
...r of rows currently selected. Return value S_OK. rowDescription() Returns the description text of the specified row in the table. [propget] HRESULT rowDescription( [in] long row, [out] BSTR description ); Parameters row The 0 based index of the row for which to retrieve the description. description Returns the description text of the specified row in the table if such a description exists.
Otherwise a null pointer is returned. Return value E_INVALIDARG if bad [in] passed, [out] value is null. S_FALSE if there is nothing to return, [out] value is null. S_OK. selectColumn() Selects a column and unselects all previously selected columns. The behavior should mimic that of the application, but for those applications which do not have a means in the GUI to select a full column of cells the behavi...
nsIClipboardCommands
ction(); boolean canPaste(); void copyImageContents(); void copyImageLocation(); void copyLinkLocation(); void copySelection(); void cutSelection(); void paste(); void selectAll(); void selectNone(); Methods canCopyImageContents() Returns whether we can copy an image's contents. boolean canCopyImageContents(); Parameters None. Return value true if an image is selected, false
otherwise. canCopyImageLocation() Returns whether we can copy an image location. boolean canCopyImageLocation(); Parameters None. Return value true if an image is selected, false
otherwise. canCopyLinkLocation() Returns whether we can copy a link location. boolean canCopyLinkLocation(); Parameters None. Return value true if a link is selected, false
otherwise. canCopySelection() Returns whether there is ...
...canPaste() Returns whether the current contents of the clipboard can be pasted and if the current selection is not read-only. ...
...copyImageContents() Copy the contents of the selected image. ...
...copyImageContents() Copy the contents of the selected image. void copyImageContents(); Parameters None. copyImageLocation() Copy the location of the selected image. void copyImageLocation(); Parameters None. ...
nsIPromptService
If set to null the parent window will be nsIWindowWatcher.activeWindow. aDialogTitle Text to appear in the title of the dialog. aText Text to appear in the body of the dialog. aValue Contains the default value for the dialog field when this method is called (null value is ok). Upon return, if the user pressed OK, then this parameter contains a newly allocated string value.
Otherwise, the parameter's value is unmodified. If you call this method from JavaScript you need to wrap this argument in an object with its 'value' property set to a string (or use an empty object). aCheckMsg Text to appear with the checkbox. If null, checkbox will not be shown. aCheckState Contains the initial checked state of the checkbox when this method is called and the final checked ...
...t to null the parent window will be nsIWindowWatcher.activeWindow. aDialogTitle Text to appear in the title of the dialog. aText Text to appear in the body of the dialog. aUsername Contains the default value for the username field when this method is called (null value is ok). Upon return, if the user pressed OK, then this parameter contains a newly allocated string value.
Otherwise, the parameter's value is unmodified. If you call this method from JavaScript you need to wrap this argument in an object with its 'value' property set to a string (or use an empty object). aPassword Contains the default value for the password field when this method is called (null value is ok). Upon return, if the user pressed OK, then this parameter contains a newly allocated string val...
...e parameter's value is unmodified. If you call this method from JavaScript you need to wrap this argument in an object with its 'value' property set to a string (or use an empty object). aPassword Contains the default value for the password field when this method is called (null value is ok). Upon return, if the user pressed OK, then this parameter contains a newly allocated string value.
Otherwise, the parameter's value is unmodified. If you call this method from JavaScript you need to wrap this argument in an object with its 'value' property set to a string (or use an empty object). aCheckMsg Text to appear with the checkbox. If null, checkbox will not be shown. aCheckState Contains the initial checked state of the checkbox when this method is called and the final checked ...
...t to null the parent window will be nsIWindowWatcher.activeWindow. aDialogTitle Text to appear in the title of the dialog. aText Text to appear in the body of the dialog. aPassword Contains the default value for the password field when this method is called (null value is ok). Upon return, if the user pressed OK, then this parameter contains a newly allocated string value.
Otherwise, the parameter's value is unmodified. If you call this method from JavaScript you need to wrap this argument in an object with its 'value' property set to a string (or use an empty object). aCheckMsg Text to appear with the checkbox. If null, checkbox will not be shown. aCheckState Contains the initial checked state of the checkbox when this method is called and the final checked ...
nsIURI
If hostPort is not applicable to the URI scheme (e.g. about:blank) Note: Characters are not escaped. originCharset ACString The charset of the document from which this URI originated. An empty value implies UTF-8. If this value is something other than UTF-8 then the URI components (for example spec, prePath, username, and so on) are all fully URL-escaped.
Otherwise, the URI components may contain unescaped multibyte UTF-8 characters. Read only. password AUTF8String The optional password, assuming the preHost consists of "username:password". Exceptions thrown NS_ERROR_FAILURE If password is not applicable to the URI scheme (e.g. about:blank) Note: Some characters may be escaped. path AUTF8Str...
...uals() Compares the current URI with another URI. Note: This is more than a string comparison, as two different URI strings can represent the same location. For example, comparing "http://foo.com:80/" and "http://foo.com/" will return true. boolean equals( in nsIURI other ); Parameters other Another nsIURI to compare to. Return value true if the two URIs represent the same location;
otherwise false. equalsExceptRef() Compares the current URI with another URI, ignoring the value of the .ref member. Note: This is more than a string comparison, as two different URI strings can represent the same location. For example, comparing "http://foo.com/#" and "http://foo.com/" or "http://foo.com/#aaa" and "http://foo.com/#bbb" will return true. boolean equalsExceptRef( in nsIURI other ); ...
...This is more than a string comparison, as two different URI strings can represent the same location. For example, comparing "http://foo.com/#" and "http://foo.com/" or "http://foo.com/#aaa" and "http://foo.com/#bbb" will return true. boolean equalsExceptRef( in nsIURI other ); Parameters other Another nsIURI to compare to. Return value true if the two URIs represent the same location;
otherwise false. resolve() Resolves a relative URI string, using this URI as the base. Note: Some implementations may have no concept of a relative URI. AUTF8String resolve( in AUTF8String relativePath ); Parameters relativePath The relative path to resolve. Return value The resolved absolute URI string. schemeIs() Quickly reports whether the nsIURI represents a URI with the specified sche...
...pecified scheme. This comparison is case-insensitive. Note: This is an optimization, allowing you to check the scheme of the URI without having to get the scheme and do the comparison yourself; this saves memory allocations. boolean schemeIs( in string scheme ); Parameters scheme A string representing the scheme to compare to. Return value true if the URI is for the specified scheme;
otherwise false. See also Code snippets:URI parsing ...
Debugger.Memory - Firefox Developer Tools
type: trackingAllocationSites A boolean value indicating whether this Debugger.Memory instance is capturing the JavaScript execution stack when each Object is allocated. This accessor property has both a getter and setter: assigning to it enables or disables the allocation site tracking. Reading the accessor produces true if the Debugger is capturing stacks for Object allocations, and false
otherwise. Allocation site tracking is initially disabled in a new Debugger. Assignment is fallible: if the Debugger cannot track allocation sites, it throws an Error instance. You can retrieve the allocation site for a given object with the Debugger.Object.prototype.allocationSite accessor property. allocationSamplingProbability A number between 0 and 1 that indicates the probability with which ...
...The maximum number of allocation sites to accumulate in the allocations log at a time. This accessor can be both fetched and stored to. Its default value is 5000. allocationsLogOverflowed Returns true if there have been more than [maxAllocationsLogLength][#max-alloc-log] allocations since the last time [drainAllocationsLog][#drain-alloc-log] was called and some data has been lost. Returns false
otherwise. Debugger.Memory Handler Functions Similar to Debugger's handler functions, Debugger.Memory inherits accessor properties that store handler functions for SpiderMonkey to call when given events occur in debuggee code. Unlike Debugger's hooks, Debugger.Memory's handlers' return values are not significant, and are ignored. The handler functions receive the Debugger.Memory's owning Debugger insta...
...ignificant, and are ignored. The handler functions receive the Debugger.Memory's owning Debugger instance as their this value. The owning Debugger's uncaughtExceptionHandler is still fired for errors thrown in Debugger.Memory hooks. On a new Debugger.Memory instance, each of these properties is initially undefined. Any value assigned to a debugging handler must be either a function or undefined;
otherwise a TypeError is thrown. Handler functions run in the same thread in which the event occurred. They run in the compartment to which they belong, not in a debuggee compartment. onGarbageCollection(statistics) A garbage collection cycle spanning one or more debuggees has just been completed. The statistics parameter is an object containing information about the GC cycle. It has the following...
...T" "SET_DOC_SHELL" "DOM_UTILS" "DOM_IPC" "DOM_WORKER" "INTER_SLICE_GC" "REFRESH_FRAME" "FULL_GC_TIMER" "SHUTDOWN_CC" "USER_INACTIVE" nonincrementalReason If SpiderMonkey's collector determined it could not incrementally collect garbage, and had to do a full GC all at once, this is a short string describing the reason it determined the full GC was necessary.
Otherwise, null is returned. Known values include the following: "GC mode" "malloc bytes trigger" "allocation trigger" "requested" gcCycleNumber The GC cycle's "number". Does not correspond to the number of GC cycles that have run, but is guaranteed to be monotonically increasing. Function Properties of the Debugger.Memory.prototype Object Memory Use Analysis Exposes Impl...
Debugger.Source - Firefox Developer Tools
ed new WebAssembly.Module with the string "> wasm" appended. sourceMapURL If the instance refers to JavaScript source, if this source was produced by a minimizer or translated from some other language, and we know the URL of a source map document relating the source positions in this source to the corresponding source positions in the original source, then this property's value is that URL.
Otherwise, this is null. (On the web, the translator may provide the source map URL in a specially formatted comment in the JavaScript source code, or via a header in the HTTP reply that carried the generated JavaScript.) This property is writable, so you can change the source map URL by setting it. All Debugger.Source objects referencing the same source will see the change. Setting an empty string has...
...ferencing the same source will see the change. Setting an empty string has no effect and will not change existing value. If the instance refers to WebAssembly code, null. Attempts to write to this property throw a TypeError. displayURL If the script had a special //# sourceURL comment, as described in the source maps specification, then this property's value holds the string that was given.
Otherwise, this is null. element The Debugger.Object instance referring to the DOM element to which this source code belongs, if any, or undefined if it belongs to no DOM element. Source belongs to a DOM element in the following cases: Source belongs to a <script> element if it is the element's text content (that is, it is written out as the body of the <script> element in the markup text), or...
...If the sources attached to a DOM element change, the Debugger.Source instances representing superceded code still refer to the DOM element; this accessor only reflects origins, not current relationships.) elementAttributeName If this source belongs to a DOM element because it is an event handler content attribute or an event handler IDL attribute, this is the name of that attribute, a string.
Otherwise, this is undefined. introductionType If the instance refers to JavaScript source, a string indicating how this source code was introduced into the system. This accessor returns one of the following values: "eval", for code passed to eval. "Function", for code passed to the Function constructor. "Function.prototype", for Function.prototype internally generated code. ...
... If the instance refers to WebAssembly code, "wasm". introductionScript, introductionOffset If the instance refers to JavaScript source, and if this source was introduced by calling a function from debuggee code, then introductionScript is the Debugger.Script instance referring to the script containing that call, and introductionOffset is the call's bytecode offset within that script.
Otherwise, these are both undefined. Taken together, these properties indicate the location of the introducing call. For the purposes of these accessors, assignments to accessor properties are treated as function calls. Thus, setting a DOM element's event handler IDL attribute by assigning to the corresponding JavaScript property creates a source whose introductionScript and introductionOffset refer to t...
DevTools API - Firefox Developer Tools
Array of ToolDefinition objects for the built-in tools. getAdditionalTools() Returns an Array of ToolDefinition objects for tools added by addons. getToolDefinition(toolId) Fetch the ToolDefinition object for a tool if it exists and is enabled. Parameters: toolId {String} - The ID of the tool. Return value: A ToolDefinition if a tool with the given ID exists and is enabled, null
otherwise. getToolDefinitionMap() Returns a toolId -> ToolDefinition map for tools that are enabled. getToolDefinitionArray() Returns an Array of ToolDefinition objects for enabled tools sorted by the order they appear in the toolbox. getThemeDefinition(themeId) Fetch the ThemeDefinition object for the theme with the given id. Parameters: themeId {String} - The ID of the theme. Retur...
...tion map for tools that are enabled. getToolDefinitionArray() Returns an Array of ToolDefinition objects for enabled tools sorted by the order they appear in the toolbox. getThemeDefinition(themeId) Fetch the ThemeDefinition object for the theme with the given id. Parameters: themeId {String} - The ID of the theme. Return value: A ThemeDefinition object if the theme exists, null
otherwise. getThemeDefinitionMap() Returns a toolId -> ThemeDefinition map for available themes. getThemeDefinitionArray() Returns an Array of ThemeDefinition objects for avialble themes. Events Following events are emitted by the gDevTools object via the EventEmitter interface. tool-registered(toolId) A new tool has been registered. tool-unregistered(tool) A tool has been unre...
...tType.CUSTOM Host type for a custom frame host. Methods getCurrentPanel() Get the currently active ToolPanel. Return value: The ToolPanel object that was returned from ToolPanel.build(). getPanel(toolId) Get the ToolPanel for given tool. Parameters: toolId {String} - The tool identifier. Return value: The ToolPanel object if the tool with the given toolId is active,
otherwise undefined. getPanelWhenReady(toolId) Similar to getPanel() but waits for the tool to load first. If the tool is not already loaded or currently loading the returned Promise won't be fulfilled until something triggers the tool to load. Parameters: toolId {String} - The tool identifier. Return value: A Promise that is fulfilled with the ToolPanel object once the tool has finished load...
...hat is resolved with the ToolPanel object once it's ready to be used. destroy() A method that is called when the toolbox is closed or the tool is unregistered. If the tool needs to perform asynchronous operations during destruction the method should return a Promise that is resolved once the process is complete. Return value: A Promise if the function performs asynchronous operations,
otherwise undefined. Example Here's a basic template for a ToolPanel implementation. // In the ToolDefintion object, do // build: (window, target) => new MyPanel(window, target), function MyPanel(window, target) { // The window object that has loaded the URL defined in the ToolDefinition this.window = window; // The Target this toolbox is debugging. this.target = target; // Do synchrono...
Using IndexedDB - Web APIs
an upgraded version number, an onupgradeneeded event is triggered straight away, allowing you to provide an updated schema in its handler. More on this later in Updating the version of the database below, and the IDBFactory.open reference page. Important: The version number is an unsigned long long number, which means that it can be a very big integer. It also means that you can't use a float,
otherwise it will be converted to the closest lower integer and the transaction may not start, nor the upgradeneeded event trigger. So for example, don't use 2.4 as a version number: var request = indexedDB.open("MyTestDatabase", 2.4); // don't do this, as the version will be rounded to 2 Generating handlers The first thing you'll want to do with almost all of the requests you generate is to add succes...
...! }; request.onsuccess = function(event) { // Do something with request.result! }; Which of the two functions, onsuccess() or onerror(), gets called? If everything succeeds, a success event (that is, a DOM event whose type property is set to "success") is fired with request as its target. Once it is fired, the onsuccess() function on request is triggered with the success event as its argument.
Otherwise, if there was any problem, an error event (that is, a DOM event whose type property is set to "error") is fired at request. This triggers the onerror() function with the error event as its argument. The IndexedDB API is designed to minimize the need for error handling, so you're not likely to see many error events (at least, not once you're used to the API!). In the case of opening a database, h...
... then doing something else, the entire transaction is rolled back. This design forces you to think about and handle errors, but you can always add a catchall error handler to the database if fine-grained error handling is too cumbersome. If you don't handle an error event or if you call abort() on the transaction, then the transaction is rolled back and an abort event is fired on the transaction.
Otherwise, after all pending requests have completed, you'll get a complete event. If you're doing lots of database operations, then tracking the transaction rather than individual requests can certainly aid your sanity. Now that you have a transaction, you'll need to get the object store from it. Transactions only let you have an object store that you specified when creating the transaction. Then you can...
... you want to specify locale-aware sorting, you can use a specialized IDBLocaleAwareKeyRange. IDBIndex has also had new properties added to it to specify if it has a locale specified, and what it is: locale (returns the locale if any, or null if none is specified) and isAutoLocale (returns true if the index was created with an auto locale, meaning that the platform's default locale is used, false
otherwise.) Note: This feature is currently hidden behind a flag -- to enable it and experiment, go to about:config and enable dom.indexedDB.experimental. Full IndexedDB example HTML Content <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <h1>IndexedDB Demo: storing blobs, e-publication example</h1> <div class="note"> <p> ...
Inputs and input sources - Web APIs
ring directional controls (either a motion-sensing pointer or a joystick or trackpad, for example) to aim in a direction, possibly at a target, though targeting is left to you to implement yourself. See Facing and targeting for further information. Selecting Using the main "select" button or other input on the controller to choose the targeted direction (or the object at which it points), or to
otherwise engage an action. For details on the primary action, see Primary action. Squeezing Squeezing the controller or a mechanism on the controller to engage a secondary action. The section Primary squeeze action describes this in more detail. Any additional capabilities a WebXR controller may have are accessed through the input source's gamepad object. This object provides access to all of the butt...
...ard from between the eyes in a direction perpendicular to the viewer's face. More flexible is the tracked-pointer mode, in which the ray's origin is at a handheld controller or hand tracking system's origin and extends outward in the direction in which the controller is pointing. The ray extends outward in a direction defined by whatever platform and controller are being used, if that's defined;
otherwise, the ray extends in the same direction the user is pointing in with their index finger, if it were currently outstretched. The third and final target ray mode is most commonly found on mobile devices like smartphones and tablets. The screen mode indicates that the target ray is determined based on the user interacting with the WebXR context by engaging with the screen in some way--most likely by...
...the user has performed the activity that begins the primary action. This may be a gesture, depressing a button, or the like. If the primary action ends successfully (for example, due to the user releasing the button or trigger), rather than because of an error, the select event is sent. After the select event is sent or if the controller on which the action is being performed is disconnected or
otherwise becomes unavailable, the selectend event is sent. Generally speaking, the selectstart and selectend events tell you when you might want to display something to the user indicating that the primary action is going on. This might be drawing a controller with the activated button in a new color, or showing the targeted object being grabbed and moved around, starting when selectstart arrives and st...
...r, then recomputing its reference space. Action The avatar performs an action, such as using an object or weapon, jumping, or any other activity not related to basic movement and rotation. Some inputs are instead used to control the application rather than the avatar. For example, a button might open an options menu used to configure the application. While that menu is open, inputs that would
otherwise control the avatar might be instead applied to controlling the menu's interface. Using keyboard and mouse events Capturing input from the keyboard and mouse is done just like it is in any web application. Set up handlers for the events that you need to handle in order to obtain the inputs you want. It's what you do with those inputs that's interesting. Imagine an avatar object which we'll use ...
Using XMLHttpRequest - Web APIs
ttp://www.example.org/example.txt"); oReq.send(); Types of requests A request made via XMLHttpRequest can fetch the data in one of two ways, asynchronously or synchronously. The type of request is dictated by the optional async argument (the third argument) that is set on the XMLHttpRequest.open() method. If this argument is true or not specified, the XMLHttpRequest is processed asynchronously,
otherwise the process is handled synchronously. A detailed discussion and demonstrations of these two types of requests can be found on the synchronous and asynchronous requests page. Do not use synchronous requests outside Web Workers. Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects...
...function transferFailed(evt) { console.log("An error occurred while transferring the file."); } function transferCanceled(evt) { console.log("The transfer has been canceled by the user."); } Lines 3-6 add event listeners for the various events that are sent while performing a data transfer using XMLHttpRequest. Note: You need to add the event listeners before calling open() on the request.
Otherwise the progress events will not fire. The progress event handler, specified by the updateProgress() function in this example, receives the total number of bytes to transfer as well as the number of bytes transferred so far in the event's total and loaded fields. However, if the lengthComputable field is false, the total length is not known and will be zero. Progress events exist for both download ...
...Failing to sanitize can lead to cross-site scripting vulnerabilities. */ echo ":: data received via GET ::\n\n"; print_r($_GET); echo "\n\n:: Data received via POST ::\n\n"; print_r($_POST); echo "\n\n:: Data received as \"raw\" (text/plain encoding) ::\n\n"; if (isset($HTTP_RAW_POST_DATA)) { echo $HTTP_RAW_POST_DATA; } echo "\n\n:: Fi...
...nModif)).toLocaleString() + "!"); }); If you want to know if the current page has changed, please read the article about document.lastModified. Cross-site XMLHttpRequest Modern browsers support cross-site requests by implementing the Cross-Origin Resource Sharing (CORS) standard. As long as the server is configured to allow requests from your web application's origin, XMLHttpRequest will work.
Otherwise, an INVALID_ACCESS_ERR exception is thrown. Bypassing the cache A cross-browser compatible approach to bypassing the cache is appending a timestamp to the URL, being sure to include a "?" or "&" as appropriate. For example: http://foo.com/bar.html -> http://foo.com/bar.html?12345 http://foo.com/bar.html?foobar=baz -> http://foo.com/bar.html?foobar=baz&12345 As the local cache is indexed by U...
HTML attribute: rel - HTML: Hypertext Markup Language
browsing context if the hyperlink would create either of those to begin with (i.e., has an appropriate target attribute value). Not allowed Annotation Annotation noreferrer No Referer header will be included. Additionally, has the same effect as noopener. Not allowed Annotation Annotation opener Creates an auxiliary browsing context if the hyperlink would
otherwise create a top-level browsing context that is not anauxiliary browsing context (i.e., has "_blank" as target attribute value). Not allowed Annotation Annotation pingback Gives the address of the pingback server that handles pingbacks to the current document. External Resource Not allowed Not allowed preconnect Specifies that the user agent should preemptive...
...k rel=alternate href="/fr/pdf" hreflang=fr type=application/pdf title="French PDF"> author Indicates the author of the current document or article. Relevant for <link>, <a>, and <area> elements, the author keyword creates a hyperlink. ...
... canonical Valid for <link>, it defines the preferred URL for the current document, which is useful for search engines. dns-prefetch Relevant for the <link> element both in the <body> and <head>, it tells the browser to preemptively perform DNS resolution for the target resource's origin. ...
...the link behave as if window.opener were null and target="_parent" were set. This is the opposite of opener. noreferrer Relevant to <form>, <a>, and <area>, including this value makes the referrer unknown (no Referer header will be included), and opens the creates a top-level browsing context, as if noopener were also set. opener Creates an auxiliary browsing context if the hyperlink would
otherwise create a top-level browsing context that is not anauxiliary browsing context (i.e., has "_blank" as target attribute value). Effectively, the opposite of noopener. pingback Gives the address of the pingback server that handles pingbacks to the current document. preconnect Specifies that the user agent should preemptively connect to the target resource's origin. prefetch Specifies that the u...
HTML documentation index - HTML: Hypertext Markup Language
Attribute, Input, Reference, minlength, textarea The minlength attribute defines the minimum number of characters (as UTF-16 code units) the user can enter into an <input> or <textarea>. This must be an integer value 0 or higher. If no minlength is specified, or an invalid value is specified, the input has no minimum length. This value must be less than or equal to the value of maxlength,
otherwise the value will never be valid, as it is impossible to meet both criteria. 44 HTML attribute: multiple Attribute, Attributes, Constraint validation The Boolean multiple attribute, if set, means the form control accepts one or more values. Valid for the email and file input types and the <select>, the manner by which the user opts for multiple values depends on the form control...
...uitable one. It can also be the destination for streamed media, using a MediaStream. 64 <b>: The Bring Attention To element Attention, Element, HTML, HTML text-level semantics, HTML:Flow content, HTML:Palpable Content, HTML:Phrasing content, Reference, Web The HTML Bring Attention To element (<b>) is used to draw the reader's attention to the element's contents, which are not
otherwise granted special importance. 65 <base>: The Document Base URL element Element, HTML, HTML document metadata, HTML:Metadata content, Reference The HTML <base> element specifies the base URL to use for all relative URLs in a document. 66 <basefont> Element, Fonts, HTML, Layout, Obsolete, Reference, Style, Web, basefont The obsolete HTML Base Font element (<b...
...ck into the document. You can use <video> for audio content as well, but the <audio> element may provide a more appropriate user experience. 219 <wbr> Element, HTML, HTML text-level semantics, Reference, Web The HTML <wbr> element represents a word break opportunity--a position within text where the browser may optionally break a line, though its line-breaking rules would not
otherwise create a break at that location. 220 <xmp> Element, HTML, Obsolete, Reference, Web The HTML Example Element (<xmp>) renders text between the start and end tags without interpreting the HTML in between and using a monospaced font. The HTML2 specification recommended that it should be rendered wide enough to allow 80 characters per line. 221 HTML reference HTML, ...
...ng context access to the document that opened it -- by not setting the Window.opener property on the opened window (it returns null). 228 Link types: noreferrer Attribute, HTML, Link types, Reference The noreferrer keyword for the rel attribute of the <a>, <area>, and <form> elements instructs the browser, when navigating to the target resource, to omit the Referer header and
otherwise leak no referrer information -- and additionally to behave as if the noopener keyword were also specified. 229 Link types: preconnect Attribute, HTML, Link, Link types, Reference The preconnect keyword for the rel attribute of the <link> element is a hint to browsers that the user is likely to need resources from the target resource's origin, and therefore the browser can lik...
SyntaxError: unterminated string literal - JavaScript
and closing quotes (single or double) for your string literal, you have escaped your string literal correctly, your string literal isn't split across multiple lines. ...
...s 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. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent;
otherwise it will not work. That form looks like this: var longString = 'This is a very long string which needs \ to wrap acros...
... Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent;
otherwise it will not work. ...
.... ...
Codecs used by WebRTC - Web media technologies
and audio synchronized, so that the movements and any ancillary information (such as slides or a projection) are presented at the same time as the audio that corresponds. General codec requirements Before looking at codec-specific capabilities and requirements, there are a few overall requirements that must be met by any codec configuration used with WebRTC. Unless the SDP specifically signals
otherwise, the web browser receiving a WebRTC video stream must be able to handle video at at least 20 FPS at a minimum resolution of 320 pixels wide by 240 pixels tall. It's encouraged that video be encoded at a frame rate and size no lower than that, since that's essentially the lower bound of what WebRTC generally is expected to handle. SDP supports a codec-independent way to specify preferred video re...
...e listed in the following table. Other video codecs Codec name Profile(s) Browser compatibility VP9 -- Chrome (48+), Firefox VP8 VP8, which we describe in general in the main guide to video codecs used on the web, has some specific requirements that must be followed when using it to encode or decode a video track on a WebRTC connection. Unless signaled
otherwise, VP8 will use square pixels (that is, pixels with an aspect ratio of 1:1). Other notes The network payload format for sharing VP8 using RTP (such as when using WebRTC) is described in RFC 7741: RTP Payload Format for VP8 Video. AVC / H.264 Support for AVC's Constrained Baseline (CB) profile is required in all fully-compliant WebRTC implementations. CB is a subset of the main profile, and is s...
... Other requirements For the purposes of supporting switching between portrait and landscape orientations, there are two methods that can be used. The first is the video orientation (CVO) header extension to the RTP protocol. However, if this isn't signaled as supported in the SDP, then it's encouraged that browsers support Display Orientation SEI messages, though not required. Unless signaled
otherwise, the pixel aspect ratio is 1:1, indicating that pixels are square. Other notes The payload format used for AVC in WebRTC is described in RFC 6184: RTP Payload Format for H.264 Video. AVC implementations for WebRTC are required to support the special "filler payload" and "full frame freeze" SEI messages; these are used to support switching among multiple input streams seamlessly. Supported audi...
...ng the codec list into two arrays: one containing codecs whose MIME type matches the one specified by the mimeType parameter, and the other with all the other codecs. Once the list has been split up, they're concatenated back together with the entries matching the given mimeType first, followed by all of the other codecs. The rearranged list is then returned to the caller. Default codecs Unless
otherwise specified, the default--or, more accurately, preferred--codecs requested by each browser's implementation of WebRTC are shown in the table below. Preferred codecs for WebRTC in major web browsers Audio Video Chrome Edge Firefox VP9 (Firefox 46 and later) VP8 Opera Safari Choosing t...
Preferences - Archive of obsolete content
onents.interfaces.nsIPrefService); var branch = prefs.getBranch("extensions.myext."); var value = branch.getComplexValue("welcomemessage", Components.interfaces.nsIPrefLocalizedString).data; The code in step 3 will read the default value from chrome://myext/locale/defaults.properties when no user value is set, and will behave exactly the same as if nsISupportsString was passed as aType
otherwise. Setting nsIPrefLocalizedString preferences is similar to setting nsISupportsString: var pls = Components.classes["@mozilla.org/pref-localizedstring;1"] .createInstance(Components.interfaces.nsIPrefLocalizedString); pls.data = val; prefs.setComplexValue("preference.with.non.ascii.value", Components.interfaces.nsIPrefLocalizedString, pls); nsILocalFi...
...cked, an NS_ERROR_UNEXPECTED exception is thrown. If the preference is locked or if there is no value for that preference in the current tree, the get method checks the default tree. If there's a value of the expected type in the default tree, it is returned (with the only exception being that calling getComplexValue() with aType parameter specified as nsIPrefLocalizedString, described above).
Otherwise an NS_ERROR_UNEXPECTED exception is thrown. If the branch is from the default tree, the get method doesn't check the tree with current values at all. (This is not exactly how it's coded in libpref, but it's equivalent) Where the default values are read from All Mozilla-based applications read (application directory)/defaults/preferences/*.js In addition to that, recent versions of Toolkit...
...classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService) .getBranch("myextension.prefs.") .QueryInterface(Components.interfaces.nsIPrefBranch2) .addObserver("", this, false); Using prefHasUserValue() nsIPrefBranch.prefHasUserValue(preference) checks whether the preference has been changed from the default value. If so, it will return true,
otherwise false. In particular, when no default value exists for a preference, prefHasUserValue() indicates whether a preference exists. Attempting to read a nonexistent preference using one of the get*Pref methods will throw an exception. Using prefHasUserValue() lets you check if the preference exists before attempting to read it. For example: if (prefs.prefHasUserValue("mypref")) { alert(prefs.getCh...
Inline options - Archive of obsolete content
Some discussion on the subject at StackOverflow: How to use addEventListener on inputChanged of inline options Display notifications If you want to use the settings UI for anything more than storing preferences, then you will probably need to initialize them when they first appear. You can't do this until your options XUL has been loaded into the Add-on Ma...
... for restartless extensions or in an XPCOM component or a JavaScript code module (not an overlay!) for traditional extensions. Note: Starting in Gecko 13.0, you can also listen for the addon-options-hidden notification, which has the same subject and data as above, to find out when the UI is about to be removed. Use this notification to remove event listeners, or any other references that might
otherwise be leaked. Locating the options file There are two ways to let the Add-on Manager find your options file: Method 1 Name the file options.xul and put it in the extension's root folder (alongside install.rdf). This method does not require you to create a chrome.manifest and set it's path. This method does not require you to specify optionsType in install.rdf. Method 2 Use install.rdf to iden...
....rdf. Method 2 Use install.rdf to identify the XUL file used for displaying the options. This requires that you register a content path in the chrome.manifest. ...
MMgc - Archive of obsolete content
call directly, such as Alloc and Free. GC::Alloc, GC::Free The Alloc and Free methods are garbage-collected analogs for malloc and free. Memory allocated with Alloc doesn't need to be explicitly freed, although it can be freed with Free if it is known that there are no other references to it. Alloc is often used to allocate arrays and other objects of variable size that contain GC pointers or are
otherwise desirable to have in managed memory. These flags may be passed to Alloc to control the allocation type. /** * flags to be passed as second argument to alloc */ enum AllocFlags { kZero=1, kContainsPointers=2, kFinalize=4, kRCObject=8 }; kZero zeros out the memory.
Otherwise, the memory contains undefined values. kContainsPointers indicates to the GC that the memory will contain pointers t...
...s from a zero reference count. If you crash with a dangling pointer to a RC object, check for DWB macros that need to be DRCWB. Unmarked unmanaged memory If you have pointers to GC objects in your unmanaged memory objects, the unmanaged objects need to be GCRoots. GCRoots are known to the GC and will be marked during a collection. Pointers must be marked for the GC to consider the objects "live";
otherwise, the objects will be considered unreachable and will be destroyed. And you'll be left with dangling pointers to these destroyed objects. If you get a crash dereferencing a pointer to a GC object, and the pointer was a member variable in an unmanaged (non-GC) object, check whether the unmanaged object is a GCRoot. If it isn't, maybe it needs to be. Finding missing write barriers There are some aut...
...t need a pointer to its block (just zero the lower 12 bits of any GC-allocated thing to get the GCBlock pointer). The GCBlock contains bitmaps for marking and indicating if an item has a destructor that needs to be called (a GCFinalizedObject base class exists defining a virtual destructor for GC items that need it). Deleted items are stored in a per-block free list which is used if there are any
otherwise we get the next free item at the end. If we don't have anything free and we reach the end, we get another block from the GCHeap. GCHeap's reserve/commit strategy GCHeap reserves 16MB of address space per heap region. The goal of reserving so much address space is so that subsequent expansions of the heap are able to obtain contiguous memory blocks. If we can keep the heap contiguous, that reduces...
Style System Overview - Archive of obsolete content
to just get the struct from the parent. Style data computation All the style struct computation described in the previous few slides happens lazily. First, nsStyleContext::GetStyleData checks for a cached struct on the style context, and returns it if present. Then, nsRuleNode::GetStyleData checks for a cached struct or a dependent bit on the rule node, and returns the struct if present.
Otherwise, we need to compute the struct, so nsRuleNode::GetStyleData calls nsRuleNode::Get*Data, which initializes the correct one of the data structs on the stack (the structs used by nsCSSDeclaration) Style data computation Get*Data calls nsRuleNode::WalkRuleTree, which walks from the style context's rule node towards the root rule node. To fill in the data, we call nsIStyleRule::MapRuleInfoInto o...
...ode::Compute*Data to turn the specified values into the mostly-computed style data in the style struct. Compute*Data use either a default or a start struct as the basis for the computation. A start struct is a cached struct in the rule tree that we can just copy and add to. If the computation in Compute*Data used any data from the parent style context, we cache the struct on the style context.
Otherwise, we cache the struct in the rule tree, on the first rule node that contributed any data, and mark dependent bits on the path up to that rule node. Managing style contexts Style contexts must (in most cases) be created before frames are constructed, to determine what frame to create. Parent style context determines inheritance; it should always be the content parent. [design flaw in frame/SC...
...to a frame-change, instead. Bugs due to failure to call nsIFrame::DidSetStyleContext. Style sheet addition and removal Handled in pres shell. PresShell::ReconstructStyleData calls FrameManager::ComputeStyleChangeFor (ReResolve) and then processes the frame-change list. Rebuilds rule tree if stylesheet was removed to avoid dangling pointers (and perhaps aliasing that would cause problems).
Otherwise we'd have to walk rule tree and compare each rule node to every rule in the sheet (O(rules * rule-nodes)). When rebuilding rule tree, we have to clear cached style contexts from XUL menus and trees. Style rule changes Handling of style rule changes is done in frame constructor (called from style set, called from pres shell, which is a document observer) and in the pres shell. Code should be...
Using microformats - Archive of obsolete content
otElement Required. The DOM element at which to begin the search. If you want to search the entire document, specify content.document. options Optional. If provided, this is a JavaScript object that contains zero or more of the following flags: recurseExternalFrames If true, child frames are included in the search. The default is true. showHidden If true, hidden microformats are added;
otherwise they're left out. The default is false. debug Specify true if debug mode is in use;
otherwise, specify false. The default is false. Return value An integer value indicating the number of microformats that match the specified criteria. debug() Returns a string that describes a microformat object. Note: You can simply call debug() on a microformat object: microformatObject.debug() instead ...
...ment at which to begin the search. If you want to search the entire document, specify content.document. options Optional. If provided, this is a JavaScript object that contains zero or more of the following flags: recurseExternalFrames If true, child frames that reference external content are included in the search. The default is true. showHidden If true, hidden microformats are added;
otherwise they're left out. The default is false. debug Specify true if debug mode is in use;
otherwise, specify false. The default is false. targetArray Optional. If provided, this is an array of microformat objects to which the search results are added. Return value A new array of microformat objects matching the search criteria, or the array specified by microformats with the newly found micr...
...eve. Return value The parent of the specified node. Returns nothing if the specified node isn't a microformat or the child of a microformat. isMicroformat() Determines whether or not the specified DOM node is a microformat. var flag = Microformats.isMicroformat(node); Parameters node The DOM node to check to see if it's a microformat. Return value true if the node is a microformat,
otherwise false. Note: This method doesnot return true if the node is a child of a microformat. See also Microformats.org ...
Menu - Archive of obsolete content
perties. Parameters properties An object defining any of the properties below. The items property may be used to define an array of menuitems. Properties Property Type Description beforeHide function A function invoked just before the menu is hidden. If the menu is a context menu, it is called as beforeHide(menu, context) and
otherwise as beforeHide(menu). menu is the Menu object to which beforeHide is attached. context is an object describing the context in which the menu was shown. beforeShow function A function invoked just before the menu is shown. If the menu is a context menu, it is called as beforeShow(menu, context) and
otherwise as beforeShow(menu). menu is the Menu object to which beforeSh...
...Read-only. items array An array of menuitems in the menu. Read-only. ...
...ng undefined, null, and the empty string. null is recommended because it stands out.) function A menuitem that will update itself when its menu is shown. The function is invoked just before the item's menu is shown and when the items array of the item's menu is retrieved. It must return a non-function menuitem. If the item belongs to a context menu, the function is called as function(context) and
otherwise function(). context is an object describing the context in which the menu was shown. string A simple menuitem with the given string label. object A menuitem with specific properties. The object may define any of the properties listed below. Properties Property Type Description command function A function that will be called when the...
Space Manager Detailed Design - Archive of obsolete content
h band data entry, see if the top of the band is greater than the (adjusted) y offset requested if it is, then band is below the offset requested, so the area between the band and the y offset is available - create a trapezoid with that region and return it. if the (adjusted) y offset is between the band top and bottom, then get the available space for the band by calling GetBandAvailableSpace
otherwise, move to the next band GetBandAvailableSpace: This method is called from GetBandData only. It walks all of the bands in the space manager and determines which bands intersect with the band passed in, and if within those bands there are regions that are available or occupied. First, walk all of the bands until a band that is to the right of the desired offset is located Starting at that ban...
...in the band collection that has a region corresponding to the reference band rect, marked as occupied by either a single or multiple frames. move to the next band after walking all of the band data, se if we have reached the rightedge of the band. If not, then check for space in the band collection if there is no room left, then set the count to the current count plus 1 and return an error.
otherwise, create another entry in the band collection, marked as available, and with a rect corresponding to the area remain in in the band(e.g. from the right edge of the last band rect to the right edge of the band). Algorithm 2: AddRectRegion Clients call into this method to notify the Space Manager that a new frame is occupying some space. First, try to get frame info for the frame. If it is fo...
...moveRegion,passing in the frame that is being removed. Get the FrameInfo for the frame passed in. If not found, an error is returned. If the rect for the frame is not empty, then visit each band in the bandList: for each rect in the band: if the bandRect is occupied by the frame, either remove the frame from the bandRect (if there are other frames sharing it) and remember that it was shared
otherwise simply remove the bandRect (no other frames share it). if the bandRect was shared, then try to coalesce adjacent bandRects if the previous bandRect is directly next to the current bandRect,and they have the same frame list, then make the current bandRect cover the previous bandRect's full region (adjust the left edge to be that of the previous bandRect) and remove the previous bandRect. if t...
PopupEvents - Archive of obsolete content
t opens, or any submenus open. For example: <menu label="File"> <menupopup onpopupshowing="if (event.target == this) adjustFileMenu(this);"> <menu label="Open"> <menupopup> <menuitem label="File..."/> <menuitem label="Page"/> </menupopup> </menu> </menupopup> </menu> The target of the event is examined to ensure that the event is for the desired menupopup.
Otherwise, the adjustFileMenu function would be called whenever the outer menupopup is opened and when the inner menupopup is opened. The bubbling of events applies to all popup events. The popupshown event The popupshown event is fired once a popup is already visible. When calling either the openPopup or openPopupAtScreen methods, the popup will not actually be open before that method returns. The popupsh...
... <textbox id="search"/> <button label="Search" oncommand="doSearch();"/> </panel> You can prevent a popup from hiding by calling the event's preventDefault method. This way, the popup will not be closed. Usually, you should not do this. If you wanted to ensure that a value was entered for instance, it is much better to rework the UI such that the code can handle no value being entered instead.
Otherwise, the user will be distracted with a popup that they cannot close. You also cannot cancel the hiding of a menupopup when a user has made a selection from a menu, as it is already too late to do so. In this situation the command event has already been sent to the selected menuitem and the operation already carried out. This is one special case in which the popuphiding event is fired after the popup...
...ion the command event has already been sent to the selected menuitem and the operation already carried out. This is one special case in which the popuphiding event is fired after the popup has been removed from the screen. The reason for this is if, as is quite common, the menu item's action is to open a modal dialog. Here, the menu would need to be removed first, before the dialog can be opened.
Otherwise, the user would have a menu for a parent window that is no longer active. So instead, the popup is removed first. Note that this means that the popuphiding event doesn't fire until after the modal dialog has been closed. There are situations when the popuphiding event will not fire when a menu is closed so you should make sure not to call any necessary code there. A better way is to just reinitia...
XUL element attributes - Archive of obsolete content
ed horizontally. right The elements are aligned on their right edges. The pack attribute is related to the alignment but is used to specify the position in the opposite direction. You can also specify the value of align using the style property -moz-box-align. allowevents Type: boolean If true, events are passed to children of the element.
Otherwise, events are passed to the element only. allownegativeassertions Type: boolean Valid on any element that has a datasources attribute. When multiple datasources are used, one may override an assertion from another. This attribute, if true, which is the default, allows a datasource to negate an earlier assertion. class Type: string The style class of the element. Multiple class...
...urce is used, either the URL of an XML file or an anchor reference to another element within the same document. For instance, the reference '#data' refers to an element with the id 'data'. If you plan on adding a datasource to an element but don't want one to be added right away, set this attribute to 'rdf:null'. This will make the element so that its contents can be generated from a datasource.
Otherwise, you cannot add one later. When the XUL document is contained on a remote web site, the datasources may only be loaded from the same domain as the document. dir Type: one of the values below The direction in which the child elements of the element are placed. normal For scales, the scale's values are ordered from left to right (for horizontal scales) or from top to bottom (for ver...
... only once. wait-cursor Type: boolean Set this attribute to true to have the cursor switch to a waiting cursor while the mouse is hovering over the element. Usually, you would only use this on the window element or other top-level elements. In order to revert to the normal cursor state call the method removeAttribute("wait-cursor") when the process effectively has ended
otherwise the wait cursor might never disappear. width Type: string (representing an integer) The preferred width of the element. The value should not include a unit as all values are in pixels. The actual displayed width may be different if the element or its contents have a minimum or maximum width, or the size is adjusted by the flexibility or alignment of its parent. The CSS width property ma...
textbox - Archive of obsolete content
f rows to display in the element. If the element contains more than this number of rows, a scrollbar will appear which the user can use to scroll to the other rows. To get the actual number of rows in the element, use the getRowCount method. searchbutton Type: boolean If true, the search field will only fire a command event when the user presses the search button or presses the Enter key.
Otherwise, the command event is fired whenever the user modifies the value. This attribute only applies to textboxes with the type search. size Type: integer The number of characters that can be displayed in the textbox. spellcheck Type: boolean If true, spell checking is enabled by default for the text box; if false, spell checking is disabled by default. If not specified, this defaults ...
...f the number box will wrap around when the maximum or minimum value is exceeded. The minimum and maximum values must both not be infinity. Properties accessibleType Type: integer A value indicating the type of accessibility object for the element. clickSelectsAll Type: boolean If set to true, the contents of the textbox are selected when focused;
otherwise, the cursor is left unchanged. decimalPlaces Type: integer Gets and sets the value of the decimalplaces attribute. decimalSymbol Type: string The character used for the decimal place indicator. The default value is a period (.) defaultValue Type: string Gets and sets the the default value in a textbox. disabled ...
... increment Type: integer Gets and sets the value of the increment attribute. inputField Type: textbox element In Mozilla, the XUL textbox is implemented as a wrapper around an HTML input element. This read only property holds a reference to this inner input element. label Type: string Sets the label attribute. Gets the label attribute if it is present and not empty.
Otherwise it returns the value of the associated label element, if applicable.
Otherwise it returns the placeholder or emptyText property. The getter is mostly useful for screen readers. Note: Prior to Firefox 3, and always in Thunderbird and SeaMonkey, the label property of an autocomplete textbox returns its value, for compatibility with the menulist element. max Type: integer ...
tree - Archive of obsolete content
first column displayed in the tree. inputField Type: textbox element Read-only property that holds the textbox that is used for editing. selType Type: string Gets and sets the value of the seltype attribute. selstyle Type: string If set to the value primary, only the label of the primary column will be highlighted when an item in the tree is selected.
Otherwise, the entire row will be highlighted. To see the difference, compare the selection style in the folder list and the message list in Mozilla mail. tabIndex Type: integer Gets and sets the value of the tabindex attribute. treeBoxObject Type: nsITreeBoxObject The box object is responsible for rendering the tree on the window. This object implements the nsITreeBoxObject in...
...n in which it is located. The tree view's nsITreeView.getCellText() method is called to obtain the cell contents. stopEditing( shouldaccept ) Return type: no return value Stops editing the cell currently being edited. If the shouldAccept parameter is true, the cell's label is changed to the edited value (the tree view's nsITreeView.setCellText() method is called to change the cell contents).
Otherwise the cell label is reverted to the value it had prior to editing. Related Elements treecols, treecol, treechildren, treeitem, treerow, treecell and treeseparator.. Interfaces nsIAccessibleProvider, nsIDOMXULTreeElement, nsIDOMXULMultiSelectControlElement Script Examples To have alternating colors for each row, use the style rules like the following: treechildren::-moz-tree-row(selected...
... value="false"/> <treecell label="Alice"/> </treerow> </treeitem> <treeitem> <treerow> <treecell value="false"/> <treecell label="Bob"/> </treerow> </treeitem> </treechildren> </tree> </window> CSS: treechildren::-moz-tree-checkbox { /* unchecked checkbox treecells. This style MUST come before treechildren::-moz-tree-checkbox(checked)
otherwise it won't take effect. */ list-style-image: url("") } treechildren::-moz-tree-checkbox(checked) { /* checked checkbox treecells. cbox-check.gif isn't available in Firefox 1, 2, and 3 in Mac OS X so you should specify a URL to an image in your extension or elsewhere. */ list-style-image: url("chrome://global/skin/checkbox/cbox-check.gif"); } treechildren::-moz-tree-checkbox(disabled...
calICalendarViewController - Archive of obsolete content
aCalendar will be the defaultCalendar of the displayCalendar of the calICalendarView. The calIDateTime parameters are optional, but aEndTime cannot be included without aStartTime. If aStartTime is specified, then the calIEvent is meant to be created 'silently', that is, without a more detailed dialog appearing. The calIEvent should have its endDate set to aEndTime, if this parameter is specified.
Otherwise, it should be set to a default value, as determined by the application. The other values of the calIEvent (title, summary, alarm, etc) should likewise be set to defaults. If no aStartTime is specified, then an event-creation dialog should be displayed. modifyOccurrence void modifyOccurrence (in calIItemOccurrence aOccurrence, in calIDateTime aNewStartTime, in calIDateTime aNewE...
... (in calIItemOccurrence aOccurrence, in calIDateTime aNewStartTime, in calIDateTime aNewEndTime); The modifyOccurrence method is used to change the attributes of an already existing calIItem. The calIDateTime parameters must either both be specified, or neither. If they are both specified, aOccurrence should be modified 'silently', that is, without a more detailed dialog appearing.
Otherwise, a dialog should be display allowing the user to modify the fields. Implementations of calICalendarViewController should be careful to provide clearly defined behavior to the user regarding the modification of recurring calIItems. deleteOccurrence void deleteOccurrence (in calIItemOccurrence aOccurrence); The deleteOccurrence method is called when by the calICalendarView when calIItem shoul...
... var event = createEvent(); event.startDate = aStartTime; aCalendar.addItem(event, null); } else { createEventWithDialog(aCalendar, aStartTime, aEndTime); } }, modifyOccurrence: function (aOccurrence, aNewStartTime, aNewEndTime) { // if we can modify this thing directly (e.g. ...
XForms Select1 Element - Archive of obsolete content
o group - used when appearance = 'full' (xhtml/xul) combobox Displaying a combobox is the default representation (xhtml/xul). XHTML widget characteristics analogous widgets is <html:select/> visual grouping by choices element is supported selection="open" is supported if incremental attribute value is false, the bound node is updated when the select1 control is blurred (i.e. ...
... select1 control is blurred (i.e. loses focus),
otherwise it is updated upon item selection XUL widget characteristics analogous widgets are <html:select/> and <xul:menulist/> visual grouping by choices element isn't implemented selection="open" attribute isn't supported if incremental attribute value is false, the bound node is updated when the select control is blurred (i.e. loses focus),
otherwise it is updated upon item selection listbox The select1 is represented as listbox (xhtml/xul). Characteristics analogous widgets are <html:select size="5"/> and <xul:listbox/> visual grouping by choices element isn't implemented selection="open" attribute isn't supported if incremental attribute value is false, the bound node is updated when the select control is blurred (i.e. loses focus),...
...it is updated upon item selection listbox The select1 is represented as listbox (xhtml/xul). Characteristics analogous widgets are <html:select size="5"/> and <xul:listbox/> visual grouping by choices element isn't implemented selection="open" attribute isn't supported if incremental attribute value is false, the bound node is updated when the select control is blurred (i.e. loses focus),
otherwise it is updated upon item selection radio group The select is represented as group of radios (xhtml/xul). Characteristics appearance attribute contains the value full there are no analogue widgets in XHTML or in XUL visual grouping by choices element is supported selection="open" attribute isn't supported if incremental attribute value is false then bound node is updated when item is blurr...
Handling common JavaScript problems - Learn web development
ssic JavaScript features", and the requirement to use such code has diminished as the requirement to support older browsers has lessened (although bear in mind that they have not gone away altogether). These days, most cross-browser JavaScript problems are seen: When poor-quality browser-sniffing code, feature-detection code, and vendor prefix usage block browsers from running code they could
otherwise use just fine. When developers make use of new/nascent JavaScript features (for example ECMAScript 6 / ECMAScript Next features, modern Web APIs...) in their code, and find that such features don't work in older browsers. We'll explore all these problems and more below. Fixing general JavaScript problems As we said in the previous article on HTML/CSS, you should make sure your code is workin...
...vantages (see Arrow functions). For a quick example, see arrow-function.html (see the source code also). Arrow functions are supported across all modern browsers, except for IE and Safari. Declaring strict mode at the top of your JavaScript code causes it to be parsed with a stricter set of rules, meaning that more warnings and errors will be thrown, and some things will be disallowed that would
otherwise be acceptable. It is arguably a good idea to use strict mode, as it makes for better, more efficient code, however it has limited/patchy support across browsers (see Strict mode in browsers). Typed arrays allow JavaScript code to access and manipulate raw binary data, which is necessary as browser APIs for example start to manipulate streams of raw video and audio data. These are available in IE...
...cial effects to your websites. This was more useful back when DHTML was a popular buzzword, and implementing an effect involved a lot of complex JavaScript, but these days browsers have a lot of built in CSS3 features and APIs to implementing effects more easily. See JavaScripting.com/animation for a list of libraries. UI libraries: Provide methods for implementing complex UI features that would
otherwise be challenging to implement and get working cross browser, for example Foundation, Bootstrap, and Material-UI (the latter is a set of components for use with the React framework). These tend to be used as the basis of an entire site layout; it is often difficult to drop them in just for one UI feature. Normalization libraries: Give you a simple syntax that allows you to easily complete a task wi...
Accessibility API cross-reference
ton that drops down a menu, MSAA only BUTTONMENU n/a n/a Expressed with aria-haspopup on an element with a button role Represents the system's caret CARET n/a n/a n/a A brief portion of text describing a table or figure. ...
... CHECKBUTTON CHECK_BOX CHECK_BOX checkbox or switch <input type=checkbox> Pretty obvious what this is for CLOCK n/a n/a timer <time> Column of cells in a table - how would the user specifically point to this, as opposed to the column header or ...
...GE_TAB PAGE_TAB tab The container of the page tab controls. PAGETABLIST PAGE_TAB_LIST PAGE_TAB_LIST tablist A pane or frame in the current window PANE n/a region or group ? The most common content type in most documents. A paragraph generally encloses distinct portions of content that are not
otherwise specified with other block level structure element types such as heading, table or list elements. <p> <P> Shows percentage completion for task PROGRESSBAR PROGRESS_BAR n/a progressbar Page showing properties of something PROPERTYPAGE n/a n/a n/a Your average, run-of-the-mill button ...
Gecko info for Windows accessibility vendors
flowsto relation -- the inverse flow_from relation is automatically calculated. These relations can affect the calculation for the next next or previous item of a certain type. ...
...Indicates that the absence of STATE_CHECKED should be spoken as // "unchecked", and that EVENT_STATE_CHANGE...
... Default role of root object of application DHTML: role="wairole:application" accName() exposes the <title> of the current pane. Role Supported? Unique features ROLE_DOCUMENT Default role for root object of document DHTML: role="wairole:document" Sets STATE_READONLY indicates it is a normal document,
otherwise we're in an editor. Sets STATE_BUSY when a new document is loading in this space. Fires EVENT_STATE_CHANGE when busy flag is set or cleared due to document load starting or finishing. accValue() exposes the URL of the current pane. accName() exposes the <title> of the current pane. ROLE_PANE The first child of a <frame> or <iframe> ...
Displaying Places information using views
s as well. In lieu of setting an id on a treecol, you may specify an anonid attribute. This is useful when you need the id for another purpose or when a treecol is contained in anonymous content, as in XBL. If both an id attribute and anonid attribute are specified, the anonid is used. The built-in tree view is provided as a general-purpose convenience. If you need to display additional data or
otherwise require more control over your view, you may need to write your own. See Creating custom views below. Using the tree view So you've got a built-in tree view. How do you ask it about the data it displays? First, see nsIPlacesView. Like all Places views, the built-in tree view implements this interface, which provides broad methods such as getting the view's nsINavHistoryResult instance and exa...
...yQueryOptions object. selectItems() Selects the first node in the tree that matches each given item ID. It will open any parent nodes that it needs to in order to show the selected items. void selectItems( array aIDs, array aOpenContainers ); Parameters aIDs An array of item IDs. aOpenContainers If true or undefined, folders that are closed are also searched. They are not searched
otherwise. Optional. selectNode() Causes a particular node to be selected in the tree, resulting in all containers above the node in the hierarchy to be opened so that the node is visible. void selectNode( nsINavHistoryNode node ); Parameters node The nsINavHistoryResultNode to select. selectPlaceURI() Causes a particular node represented by the specified placeURI to be selected in the tree.
... return this._getCellText(aRowIndex, aCol); }; view._cycleHeader = view.cycleHeader; view.cycleHeader = function (aCol) { switch (aCol.id || aCol.element.getAttribute("anonid")) { case "fullURI": case "indexInParent": case "parity": // You might resort by column here. break; default: this._cycleHeader(aCol); break; } };...
Mozilla DOM Hacking Guide
t expect this to be a complete reference quite yet. If you can contribute any time or knowledge to this document, it is greatly appreciated! Target audience: People interested in learning how the DOM is implemented. Prior knowledge of C++ and XPCOM is assumed. If you don't know XPCOM yet, and would like to be able to read this document quickly, you can read the Introduction to XPCOM for the DOM.
Otherwise, for more detailed XPCOM documentation, please see the XPCOM project page. Class Info and Helper Classes Introduction to Class Info Class Info is what gives the DOM classes their correct behavior when used through XPConnect. It lies at the heart of the famous "XPCDOM landing" that happened in May. We will talk a lot about XPConnect in this document, since it is so important for the DOM. By "co...
... in the introduction to Class Info, there is the main array, sClassInfoData, filled with objects of type nsDOMClassInfoData. However when the array is created, three data members of the structure are left as null pointers: mCachedClassInfo, mProtoChainInterface, and mInterfaces. Init() uses a set of macros to fill the blanks: the DOM_CLASSINFO_MAP family. Each DOM class needs to use these macros,
otherwise bad things will happen. I will use the example of the Window class to illustrate the use of the macros. Here is the relevant piece of code. DOM_CLASSINFO_MAP_BEGIN(Window, nsIDOMWindow) DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindow) ... DOM_CLASSINFO_MAP_ENTRY(nsIDOMAbstractView) DOM_CLASSINFO_MAP_END DOM_CLASSINFO_MAP_BEGIN(_class, _interface) maps to _DOM_CLASSINFO_MAP_BEGIN(_class, &NS_GET_IID(_inte...
...ntation interface, so here we go. The C++ implementation is in nsDocument.cpp. The first step is of course to do the C++ implementation of the interface, which is described in the intro to XPCOM document. Let's assume nsDOMImplementation now implements the nsIDOMHTMLDOMImplementation interface (look in bug 33871 if you want to know how to do that). We want to expose this interface to JavaScript (
otherwise only XPCOM callers will be able to access this interface). To do that, we have to add it to the DOMClassInfo of the DOMImplementation DOM object. Benefits The HTMLDOMImplementation interface will be available from JavaScript. Methods defined on the HTMLDOMImplementation interface will be accessible on the document.implementation object (the main goal) using the automatic interface flattenin...
NSS tools : crlutil
extupdate=YYYYMMDDhhmmssZ Field "next update" is optional. Time should be in GeneralizedTime format (YYYYMMDDhhmmssZ). For example: 20050204153000Z * Add an extension to a CRL or a crl certificate entry: addext extension-name critical/non-critical [arg1[arg2 ...]] Where: extension-name: string value of a name of known extensions. critical/non-critical: is 1 when extension is critical and 0
otherwise. arg1, arg2: specific to extension type extension parameters addext uses the range that was set earlier by addcert and will install an extension to every cert entries within the range. * Add certificate entries(s) to CRL: addcert range date range: two integer values separated by dash: range of certificates that will be added by this command. dash is used as a delimiter. Only one cert will...
...nformation see RFC #3280 * Add The Authority Key Identifier extension: The authority key identifier extension provides a means of identifying the public key corresponding to the private key used to sign a CRL. authKeyId critical [key-id | dn cert-serial] Where: authKeyIdent: identifies the name of an extension critical: value of 1 of 0. Should be set to 1 if this extension is critical or 0
otherwise. key-id: key identifier represented in octet string. dn:: is a CA distinguished name cert-serial: authority certificate serial number. * Add Issuer Alternative Name extension: The issuer alternative names extension allows additional identities to be associated with the issuer of the CRL. Defined options include an rfc822 name (electronic mail address), a DNS name, an IP address, and a URI. ...
... invalidityDate non-critical date Where: crlNumber: identifies the name of an extension non-critical: should be set to 0 since this is non-critical extension date: invalidity date of a cert. Date should be represented in GeneralizedTime format (YYYYMMDDhhmmssZ). Usage The Certificate Revocation List Management Tool's capabilities are grouped as follows, using these combinat...
NSS Tools crlutil
t update" is optional. Time should be in GeneralizedTime format (YYYYMMDDhhmmssZ). For example: 20050204153000Z Add an extension to a CRL or a crl certificate entry: addext extension-name critical/non-critical [arg1[arg2 ...]] Where: extension-name: string value of a name of known extensions. critical/non-critical: is 1 when extension is critical and 0
otherwise. arg1, arg2: specific to extension type extension parameters addext uses the range that was set earlier by addcert and will install an extension to every cert entries within the range. See "Implemented extensions" for more information regarding extensions and theirs parameters. Add certificate entries(s) to CRL: addcert range date Where: ...
...uthority Key Identifier extension: The authority key identifier extension provides a means of identifying the public key corresponding to the private key used to sign a CRL. authKeyId critical [key-id | dn cert-serial] Where: authKeyIdent: identifies the name of an extension critical: value of 1 of 0. Should be set to 1 if this extension is critical or 0
otherwise. key-id: key identifier represented in octet string. dn:: is a CA distinguished name cert-serial: authority certificate serial number. Add Issuer Alternative Name extension: The issuer alternative names extension allows additional identities to be associated with the issuer of the CRL. Defined options include an rfc822 name (electronic mail address), a DNS name, an IP address, and ...
... invalidityDate non-critical date Where: crlNumber: identifies the name of an extension non-critical: should be set to 0 since this is non-critical extension date: invalidity date of a cert. Date should be represented in GeneralizedTime format (YYYYMMDDhhmmssZ). Usage The Certificate Revocation List Management Tool's capabilities ...
NSS tools : crlutil
hmmssZ Field "next update" is optional. Time should be in GeneralizedTime format (YYYYMMDDhhmmssZ). For example: 20050204153000Z * Add an extension to a CRL or a crl certificate entry: addext extension-name critical/non-critical [arg1[arg2 ...]] Where: extension-name: string value of a name of known extensions. critical/non-critical: is 1 when extension is critical and 0
otherwise. arg1, arg2: specific to extension type extension parameters addext uses the range that was set earlier by addcert and will install an extension to every cert entries within the range. * Add certificate entries(s) to CRL: addcert range date range: two integer values separated by dash: range of certificates that will be added by this command. dash is used as a delimiter. O...
...#3280 * Add The Authority Key Identifier extension: The authority key identifier extension provides a means of identifying the public key corresponding to the private key used to sign a CRL. authKeyId critical [key-id | dn cert-serial] Where: authKeyIdent: identifies the name of an extension critical: value of 1 of 0. Should be set to 1 if this extension is critical or 0
otherwise. key-id: key identifier represented in octet string. dn:: is a CA distinguished name cert-serial: authority certificate serial number. * Add Issuer Alternative Name extension: The issuer alternative names extension allows additional identities to be associated with the issuer of the CRL. Defined options include an rfc822 name (electronic mail address), a DNS name, an IP addres...
... invalidityDate non-critical date Where: crlNumber: identifies the name of an extension non-critical: should be set to 0 since this is non-critical extension date: invalidity date of a cert. Date should be represented in GeneralizedTime format (YYYYMMDDhhmmssZ). Usage The Certificate Revocation List Management Tool's capabilities are grouped as follows, us...
Tracing JIT
ram-counter (PC) value has been jumped-to. This number is called the hit count for the PC. If the hit count of a particular PC reaches a threshold value, the target is considered hot. When the monitor decides a target PC is hot, it looks in a hashtable of fragments to see if there is a fragment holding native code for that target PC. If it finds such a fragment, it transitions to executing mode.
Otherwise it transitions to recording mode. Recording When the trace monitor enters recording mode, it constructs a new trace recorder, of type TraceRecorder. It then passes control back to the SpiderMonkey interpreter. The interpreter continues interpreting bytecode, but with an important difference: each bytecode it interprets is also sent to the trace monitor and recorded in the monitor's trace record...
...d that native happens to re-enter the interpreter to interpret yet more bytecode, and furthermore if that bytecode itself contains a hot PC that has not yet been traced, the trace monitor may be asked to begin nested recording. This is the same as normal recording mode, except that the outermost recorder is placed on a deferred-abort stack. When the innermost recorder completes -- successfully or
otherwise -- every recorder on the deferred abort stack is aborted. This process is called deep aborting the suspended recorders. Executing When the monitor interprets a backward jump to a PC that it has a compiled trace of machine code for, the monitor enters executing mode. This mode is relatively simple compared to recording mode. First the monitor allocates a native stack for the trace to use, an...
...ace-exit, as an optimization. If the side exit condition indicates that the trace exited successfully -- simply running out of native code or hitting a branch condition that no native code yet exists to handle -- the monitor will inspect the hit count for the trace-exiting PC. If that PC has itself grown hot, the monitor will immediately transition to recording mode starting with the exiting PC.
Otherwise it will return to monitoring mode. If the side exit condition indicates that the trace exited unsuccessfully -- due to encountering sufficient memory pressure to trigger a garbage collection, running out of native stack space, expiring a timer or any similar abnormal condition -- the monitor returns to monitoring mode. Some other terminology may be helpful when reading the code: The term gu...
JSAPI User Guide
und will be destroyed if you don't tell the JSAPI you're still using it. Second, the application should take steps to reduce the performance impact of garbage collection. Keeping objects alive If your JSAPI application crashes, it is likely due to a GC-related error. The application must ensure that the garbage collector can reach all the objects, numbers, and strings that are still being used.
Otherwise, the GC will free the memory occupied by those values, leading to a probable crash the next time your program tries to use them. There are many ways to ensure that a value is GC-reachable. If you just need the value to remain reachable for the duration of a JSNative call, store it in *rval or an element of the argv array. The values stored in those locations are always reachable. To get extra...
...operties. The latter are called "static" below by analogy to Java. They are defined in the constructor object's scope, so that MyClass.myStaticProp works along with new MyClass(). JS_InitClass takes a lot of arguments, but you can pass nullptr for any of the last four if there are no such properties or methods. Note that you do not need to call JS_InitClass to make a new instance of that class--
otherwise there would be a chicken-and-egg problem making the global object--but you should call JS_InitClass if you require a constructor function for script authors to call via new, and/or a class prototype object (MyClass.prototype) for authors to extend with new properties at run time. In general, if you want to support multiple instances that share behavior, use JS_InitClass. protoObj = JS_InitClass(...
..., or they can serve as interfaces to your program's services. For example, a custom JS object that provides direct service might be one that handles all of an application's network access, or might serve as an intermediary broker of database services. Or a JS object that mirrors data and functions that already exist in the application may provide an object-oriented interface to C code that is not
otherwise, strictly-speaking, object-oriented itself. Such a custom object acts as an interface to the application itself, passing values from the application to the user, and receiving and processing user input before returning it to the application. Such an object might also be used to provide access control to the underlying functions of the application. There are two ways to create custom objects that...
JS_ExecuteRegExp
o rval. rval JS::MutableHandleValue Out parameter. Receives the result match result array or boolean value. Description JS_ExecuteRegExp and JS_NewRegExpObjectNoStatics execute the RegExp object, reobj, to the specified input string, chars, from *indexp index. ...
...uteRegExp and JS_NewRegExpObjectNoStatics execute the RegExp object, reobj, to the specified input string, chars, from *indexp index. If test is false, JS_ExecuteRegExp and JS_NewRegExpObjectNoStatics store the match result array to *rval if matches,
otherwise stores null to *rval. If test is true, JS_ExecuteRegExp and JS_NewRegExpObjectNoStatics store the boolean value true to *rval if matches,
otherwise stores null to *rval. JS_ExecuteRegExp updates the built-in RegExp object's properties. ...
...he match result array to *rval if matches,
otherwise stores null to *rval. If test is true, JS_ExecuteRegExp and JS_NewRegExpObjectNoStatics store the boolean value true to *rval if matches,
otherwise stores null to *rval. JS_ExecuteRegExp updates the built-in RegExp object's properties. ...
JS_NewObject
since JSAPI 39 Description JS_NewObject creates a new object based on a specified class. cx is a pointer to a context associated with the runtime in which to establish the new object. clasp is a pointer to an existing class to use for internal methods, such as finalize. The JavaScript engine selects a prototype object for you. On success, JS_NewObject returns a pointer to the new object.
Otherwise it returns NULL. Added in SpiderMonkey 1.8 JS_NewObjectWithGivenProto creates a new object with the specified prototype. If NULL is passed as proto, the new object will have a prototype with the JS value of null. To create a new object as a property of an existing object, use JS_DefineObject, a convenience function that combines JS_NewObject and JS_DefineProperty. Obsolete ? Starting with Ge...
...an create a new object in a specific compartment using the Components.utils.createObjectIn() method. Choosing a default prototype Like many JSAPI functions, JS_NewObject selects an appropriate prototype for the newly created object if you don't supply one yourself. If the new object's class (here, clasp) is a built-in class, then its associated prototype is used as the new object's prototype.
Otherwise, Object.prototype is used as the new object's prototype. Previous behaviour Obsolete since JSAPI 45 Here's how the process works in detail: First, we must identify a global object. If the parent is non-NULL, we assume it is part of a scope chain, walk to the end of that chain, and use the global object we find there. If the parent is NULL, we use the global object at the end of the scope cha...
...andard requires us in certain cases to use the original constructors' prototypes. If the global object's class's flags include JSCLASS_GLOBAL_FLAGS, then the global object always retains the original constructors for each standard class; we use these original constructors when they are available. Finally, we must find a prototype. If the constructor has a prototype property, we use its value.
Otherwise, we use Object.prototype, looking up the constructor for Object as described above. See Also MXR ID Search for JS_NewObject MXR ID Search for JS_NewObjectWithGivenProto JS_NewGlobalObject JS_NewArrayObject JS_ValueToObject bug 408871 bug 1136906, bug 1136345 -- remove parent parameter bug 1125567 -- change prototype lookup behaviour ...
JS_ReportErrorNumber
s passed to the ReportErrorNumber API. Description These functions create a JSErrorReport, populate it with an error message obtained from the given JSErrorCallback, and either report it to the current error reporter callback or create an Error object and set it as the pending exception. First errorCallback(userRef, errorNumber) is called. If errorCallback returns NULL, (??? what happens?). ...
...g exception. First errorCallback(userRef, errorNumber) is called. If errorCallback returns NULL, (??? what happens?).
Otherwise, if the JSErrorFormatString returned by the JSErrorCallback has .exnType == JSEXN_NONE, then the error reporter, if any, is called, and no Error object is created. (??? The source code seems to say we ignore the .exnType, actually, but surely I'm just missing something.)
Otherwise, if any JavaScript code is running in cx (for example, if the caller is a JSNative that was called from a script), then an Error object is created and becomes the pending exception. The error reporter is not called yet, because the script still has an opportunity to catch and handle the exception.
Otherwise, no JavaScript code is running in cx. If the JSOPTION_DONT_REPORT_UNCAUGHT option is set, ...
...ode is running in cx (for example, if the caller is a JSNative that was called from a script), then an Error object is created and becomes the pending exception. The error reporter is not called yet, because the script still has an opportunity to catch and handle the exception.
Otherwise, no JavaScript code is running in cx. If the JSOPTION_DONT_REPORT_UNCAUGHT option is set, (??? what happens?).
Otherwise, (??? what happens?). See Also MXR ID Search for JS_ReportErrorNumber MXR ID Search for JS_ReportErrorNumberUC MXR ID Search for JS_ReportErrorFlagsAndNumber MXR ID Search for JS_ReportErrorFlagsAndNumberUC MXR ID Search for JS_ReportErrorNumberUCArray bug 801487 ...
JS_SetProperty
ves like the JavaScript expression obj[name] = v. JS_SetUCProperty is the Unicode version of the function. JS_SetPropertyById is the same but takes a JS::HandleId for the property name. If obj is a Proxy, the JS_SetProperty [[Set]] internal method defined in ES2015 (rev 29 9.5.9) is performed. If obj is a native object with custom setGeneric op, the op is called with (cx, obj, id, &v, false)). ...
...ve object with custom setGeneric op, the op is called with (cx, obj, id, &v, false)).
Otherwise, [[Set]] internal method defined in ES2015 (rev 29 9.1.9) is performed. If the lookup found no property with the given name, or if it found that obj inherits such a property from a non-native object, then a new own property is added to obj, as described below. The new property is JSPROP_ENUMERATE.
Otherwise, if the lookup found a read-only property or obj non-extensible, nothing happens, but this is not an error. In strict mode, a warning is issued.
Otherwise, if obj has an own property with the given name, then the existing property's value is set as described below. Creation of new properties One of the cases above involves creating a new own property on obj. The name of the new property is gi...
...he arguments (cx, obj, id, &v). This hook may assign to v. If the hook succeeds and the property has a stored value, then the value left in v by the addProperty hook becomes the stored value of the property. Setting the value. Two of the cases above can involve setting the value of a new or existing property of obj. This is done as follows. If the property has a JavaScript setter, it is called;
otherwise, if it has a JavaScript getter, then an error is reported;
otherwise the property's setter is called, passing the arguments (cx, obj, id, &v). If the setter succeeds and the property has a stored value, then the value left in v becomes the stored value of the property. On success, JS_SetProperty returns true, and the value in v is left unchanged unless a hook or setter modified it. On error or e...
TPS Tests
// ... "fx_account": { "username": "foobar@restmail.net", "password": "hunter2" }, "preferences": { // use "https://stable.dev.lcip.org" for dev instead of stage "identity.fxaccounts.autoconfig.uri": "https://accounts.stage.mozaws.net" // possibly more preferences... }, // ... } Note that in this example, the foobar@restmail.net account must be registered on stage,
otherwise authentication will fail (and the whole test will fail as well. You can sign up for an FxA account on stage or dev by creating an FxA account after adding the identity.fxaccounts.autoconfig.uri preference (with the appropriate value) to about:config. Additionally, note that the config file must parse as valid JSON, and so you can't have comments in it (sorry, I know this is annoying). One altern...
...ch is a function reference to call, the other members of which are parameters to pass to the function. Each type of asset list has a number of built-in functions you can call, described in the section on Asset lists; there are also some additional built-in functions. Built-in functions Sync(options) Initiates a Sync operation. If no options are passed, a default sync operation is performed.
Otherwise, a special sync can be performed if one of the following are passed: SYNC_WIPE_SERVER, SYNC_WIPE_CLIENT, SYNC_RESET_CLIENT. This will cause TPS to set the firstSync pref to the relevant value before syncing, so that the described actionwill take place Logger.logInfo(msg) Logs the given message to the TPS log. Logger.AssertTrue(condition, msg) Asserts that condition is true,
otherwise an exce...
... Custom functions You can also write your own functions to be called as actions. ...
Web Replay
his tab in the same way as a recording tab, though playing forward to the end will pause the tab instead of allowing further recording. Save Recording and Replay on a Different Machine (partially implemented) Recordings can be replayed on a different machine from the one which recorded them. This requires using the same build of firefox and a reasonably similar version of the operating system;
otherwise the tab will probably crash. This feature has had little testing or polishing and there is not yet a good definition of 'reasonably similar'. Time Travel Features This section describes extensions to the developer tools that use time travel to help debug a recording/replaying tab. Step Back When paused, the reverse step button in the Debugger developer tool will step to the previous line exe...
...s are those affected by interleaving execution with other threads, and which always behave the same given the same interleaving. Intra-thread non-determinism is recorded and later replayed for each thread. These behaviors mainly originate from system calls (i/o and such). Inter-thread non-determinism is handled by first assuming the program is data race free: shared memory accesses which would
otherwise race are either protected by locks or use APIs that perform atomic operations. If we record and later replay the order in which threads acquire locks (and, by extension, release locks and use condvars) then accesses on lock-protected memory will occur in the same order. Atomic variables can be handled by treating reads and writes as if they were wrapped by a lock acquire/release during recordin...
...protected, and as faults occur a special exception handler thread unprotects the memory, copies its contents and marks it as dirty. When the next snapshot is taken, only the dirty memory is examined for any changes vs. the copy made. This mechanism requires intercepting mmap (or similar low level allocation functions) so that any newly addressable memory is known -- anonymous mappings would not
otherwise be intercepted or included in the recording, as heap allocation is non-deterministic while replaying. mprotect is intercepted and nop'ed to avoid interference with the dirty memory mechanism, and munmap is intercepted with no actual unmapping performed, so that memory does not need to be remapped when restoring a snapshot (a set of free regions is maintained to allow reusing this memory). All s...
Handling Mozilla Security Bugs
This document describes how the new security organizational structure will work, and how security-related Mozilla bug reports will be handled. Note that the focus of this new structure is restricted solely to addressing actual security vulnerabilities arising from problems in Mozilla code. This work is separate from the work of developers adding new security features (cryptographically-based or
otherwise) to Mozilla, although obviously many of the same people will be involved in both sets of activities. Background Security vulnerabilities are different from other bugs, because their consequences are potentially so severe: users' private information (including financial information) could be exposed, users' data could be destroyed, and users' systems could be used as platforms for attacks on oth...
...ponsible for posting the information received to Bugzilla, and marking the bug as "Security-Sensitive" if it is warranted, given the nature and severity of the bug and the risk of potential exploits. Other Participants Besides the permanent security bug group members described above, there are two other categories of people who may participate in security bug group activities and have access to
otherwise-confidential security bug reports: A person who reports a security bug will have continued access to all Bugzilla activities associated with that bug, even if the bug is marked "Security-Sensitive." Any other persons may be given access to a particular security bug, by someone else (who does have access) adding them to the CC list for that bug. Thus someone reporting a security bug essentia...
...o make room for new ones. Disclosure of Security Vulnerabilities The security module owner, peers, and other members of the Mozilla security bug group will not be asked to sign formal nondisclosure agreements or other legal paperwork. However, we do expect members of the group: Not to disclose security bug information to others who are not members of the Mozilla security bug group or are not
otherwise involved in resolving the bug. However, members of the Mozilla security bug group employed by a distributor of Mozilla-based products may share such information within that distributor, provided that this information is shared only with those who have a need to know, to the extent they need to know, and that such information is labeled and treated as the organization generally treats confidential...
Index
71 Monitoring HTTP activity HTTP 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. 72 Observer Notifications XPCOM, XPCOM:Add-ons The following are topics that you can observe during the course of an application. Unless
otherwise noted you register for the topics using the nsIObserverService. 73 Setting HTTP request headers Add-ons, Extensions, HTTP, XUL, XULRunner HTTP is one of the core technologies behind the Web. In addition to the actual content, some important information is passed with HTTP headers for both HTTP requests and responses. 74 Storage Guide, Interfaces, Storage, Toolk...
...Supports object. Attempting to alter this bit will result in an NS_ERROR_ILLEGAL_VALUE. OPT_* values above, OR'd together. Last version set on this context. Scripts typically select this with the "language" attribute. See the VERSION_* consts on jsdIDebuggerService. Unique tag among all valid jsdIContext objects, useful as a hash key. Private data for this context, if it is an nsISupports, |null|
otherwise. Retrieve the underlying context wrapped by this jsdIContext. Top of the scope chain for this context. |true| if this context should be allowed to run scripts, |false|
otherwise. This attribute is only valid for contexts which implement nsIScriptContext. Setting or getting this attribute on any other context will throw a NS_ERROR_NO_INTERFACE exception. Stack frame objects. These are only valid i...
...Used to set the contents of this object. 832 nsIPrefService Interfaces, Interfaces:Scriptable, XPCOM, XPCOM API Reference, XPCOM Interface Reference Call to get a Preferences "Branch" which accesses user preference data. Using a Set method on this object will always create or set a user preference value. When using a Get method a user set value will be returned if one exists,
otherwise a default value will be returned. 833 nsIPrincipal For details on principals, how they work, and how to get the appropriate one, see Security check basics. 834 nsIPrinterEnumerator Interfaces, Interfaces:Scriptable, NeedsContent, XPCOM, XPCOM Interface Reference Returns an array of the names of all installed printers. 835 nsIPrintingPrompt ...
inIDOMUtils
( in nsIDOMNode aNode, in boolean aShowingAnonymousContent ); Parameters aNode A DOM Node for which to retrieve the style nodes. aShowingAnonymousContent Whether you are interested in the XBL flattened tree. Return value A DOM NodeList of the child nodes. If you have requested anonymous content, then if the element has an XBL binding then this will be the binding's anonymous nodes,
otherwise if the element is itself an anonymous node containing an insertion point then this will be a list combining the element's explicit children from its binding parent's anonymous nodes and any children inserted as a result of the insertion point. getContentState() A bit mask of the supported content state flags, which are listed in Content state flags. unsigned long long getContentState( in nsI...
...contains insignificant whitespace. In particular, this will be false if certain CSS white-space styles are in effect. isInheritedProperty() Determines if the specified string names a CSS property that is inherited by default. boolean isInheritedProperty( in AString aPropertyName ); Parameters aPropertyName The name of the CSS property. Return value true if the property is inherited,
otherwise false. parseStyleSheet() Parse CSS and update the style sheet in place. void parseStyleSheet( in nsIDOMCSSStyleSheet aSheet, in DOMString aInput ); Parameters aSheet A DOMCSSStyleSheet. aInput A DOMString. The new source string for the style sheet. Return value void setContentState() Sets the given element as the current owner of the specified state, and removes that state fro...
...lass to remove the lock of. e.g. ":hover". hasPseudoClassLock() Checks whether the element element has a particular pseudo-class lock applied. boolean hasPseudoClassLock( in nsIDOMElement aElement, in DOMString aPseudoClass ); Parameters aElement The element to test. aPseudoClass The pseudo-class lock to test for existence, e.g. ":hover". Return value true if lock exists, false
otherwise clearPseudoClassLocks() Removes any pseudo-class locks from the element. void clearPseudoClassLocks( in nsIDOMElement aElement ); Parameters aElement The element to remove the pseudo-class locks from. ...
mozIStorageConnection
reliable if you are using asynchronous statements or if you are using the connection on multiple threads. schemaVersion long The schema version of the database. This should not be used until the database is ready. The version will be reported as 0 if it is not set. transactionInProgress boolean Returns true if there is a transaction in progress on the database.
Otherwise returns false. Read only. Constants Transaction execution time constants. Constant Value Description TRANSACTION_DEFERRED 0 No database lock is obtained until the first statement is run. TRANSACTION_IMMEDIATE 1 A reserved lock is obtained on the database. TRANSACTION_EXCLUSIVE 2 An exclusive lock is obtained on the database. ...
...difying the database is strongly discouraged! void executeSimpleSQL( in AUTF8String aSQLStatement ); Parameters aSQLStatement The SQL statement to execute. indexExists() This method determines whether or not the given index exists. boolean indexExists( in AUTF8String aIndexName ); Parameters aIndexName The index to check. Return value true if the index exists, false
otherwise. preload() Obsolete since Gecko 1.9 (Firefox 3) This is used to preload the database cache. It loads pages from the start of the database file until the memory cache (specified by "PRAGMA cache_size=") is full or the entire file is read. The cache MUST be active on the database for this to work. This means that you must have a transaction open on the connection, or ha...
...ler instance that is being registered. Return value Returns the previous registered handler, or null if none was previously registered. tableExists() Determines if there exists a table with the given name. boolean tableExists( in AUTF8String aTableName ); Parameters aTableName The SQL table whose existence should be checked. Return value Returns true if the table exists, false
otherwise. See also Storage mozStorage introduction and how-to article mozIStorageStatement Create and execute SQL statements on a SQLite database. mozIStorageValueArray Wraps an array of SQL values, such as a result row. mozIStorageFunction Create a new SQLite function. mozIStorageAggregateFunction Create a new SQLite aggregate function. mozIStorageProgressHandler Monitor progress during the exec...
nsIClipboardDragDropHooks
wDrop() Tells gecko whether a drop is allowed on this content area. boolean allowDrop( in nsIDOMEvent event, in nsIDragSession session ); Parameters event The DOM event (drag gesture). session The drag session from which client can get the flavors present or the actual data. Return value true indicates to the Operating System that if a drop does happen on this browser, it will be accepted.
Otherwise, false to indicates to the Operating System that drop is not allowed. On win32, this will change the cursor to "reject". allowStartDrag() Prevents the drag from starting. boolean allowStartDrag( in nsIDOMEvent event ); Parameters event The DOM event (drag gesture). Return value true if the drag can proceed.
Otherwise, false to show the drag is canceled (Does not go to Operating System). onCo...
...is highly recommended that the implementation be very efficient so user feedback is not negatively impacted. boolean onCopyOrDrag( in nsIDOMEvent aEvent, in nsITransferable trans ); Parameters aEvent The DOM event (drag drop). null if triggered by copy. trans The transferable holding the list of flavors and the data for each flavor. Return value true to indicate that copy/drag can proceed.
Otherwise, false to indicate that the copy/drag is canceled, does not go to Operating System. onPasteOrDrop() Provide an alternative action to the built-in behavior when something is dropped on the browser or in an editor. boolean onPasteOrDrop( in nsIDOMEvent event, in nsITransferable trans ); Parameters event The DOM event (drag drop); null if triggered by paste. trans The transferable holding the ...
...he built-in behavior when something is dropped on the browser or in an editor. boolean onPasteOrDrop( in nsIDOMEvent event, in nsITransferable trans ); Parameters event The DOM event (drag drop); null if triggered by paste. trans The transferable holding the list of flavors and the data for each flavor. Return value true to indicate the action was handled, do not perform built-in behavior.
Otherwise, false to indicate the action was not overridden, do built-in behavior. See also nsIClipboard ...
nsIDOMNSHTMLDocument
boolean doShowUI, in DOMString value ); Parameters commandID The name of the command to execute. See Rich-Text Editing in Mozilla for a list of supported commands. doShowUI This is not implemented in Gecko. value Some commands require an argument. You can pass null for those commands that do not need an argument. Return value true if the command was recognized, false
otherwise. execCommandShowHelp() Obsolete since Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11) This method never did anything but throw an exception, and was removed entirely in Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11). boolean execCommandShowHelp( in DOMString commandID ); Parameters commandID The name of the command. Return value ...
..., trying to write to the document will probably throw. aReplace Whether the document should replace the existing document in session history. Return value The new document. queryCommandEnabled() boolean queryCommandEnabled( in DOMString commandID ); Parameters commandID The name of the command to query. Return value Returns true if the command is supported and enabled, false
otherwise. queryCommandIndeterm() boolean queryCommandIndeterm( in DOMString commandID ); Parameters commandID The name of the command to query. Return value For stateful commands, returns true if the command is in an indeterminate state, false
otherwise. For instance, if there is a selection and part of the selected text is bold, then then bold command is in an indeterminate state. queryComma...
...in an indeterminate state, false
otherwise. For instance, if there is a selection and part of the selected text is bold, then then bold command is in an indeterminate state. queryCommandState() boolean queryCommandState( in DOMString commandID ); Parameters commandID The name of the command to query. Return value For stateful commands, returns true if the command has is active, false
otherwise. queryCommandSupported() boolean queryCommandSupported( in DOMString commandID ); Parameters commandID The name of the command to query. Return value Returns true if the command is supported on the current range, false
otherwise. queryCommandText() Obsolete since Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11) This method never did anything but...
nsIDOMXULElement
us(); nsIDOMNodeList getElementsByAttribute(in DOMString name, in DOMString value); nsIDOMNodeList getElementsByAttributeNS(in DOMString namespaceURI, in DOMString name, in DOMString value); Attributes Attribute Type Description align DOMString Gets/sets the value of the element's align attribute. allowEvents boolean true if the element's allowevents attribute is the string "true",
otherwise false. Removes the attribute if you set it to false. boxObject nsIBoxObject Read only. Gets or creates a box object for the element; browser, editor, iframe, listbox, menu, menupopup, scrollbox, tooltip and tree elements receive specialized box objects allowing access to additional properties not normally available from script. builder nsIXULTemplateBuilder Read only. Retrives the element's t...
...ooltip and tree elements receive specialized box objects allowing access to additional properties not normally available from script. builder nsIXULTemplateBuilder Read only. Retrives the element's template builder, if it has a template. className DOMString Gets/sets the value of the element's class attribute. collapsed boolean true if the element's collapsed attribute is the string "true",
otherwise false. Removes the attribute if you set it to false. contextMenu DOMString Gets/sets the value of the element's contextmenu attribute. controllers nsIControllers Read only. Returns an nsIControllers object that additional controllers may be appended to so as to provide focus-specific actions for commands. database nsIRDFCompositeDataSource Read only. Returns the template builder's database,...
...ment's datasources attribute. dir DOMString Gets/sets the value of the element's dir attribute. flex DOMString Gets/sets the value of the element's flex attribute. flexGroup DOMString Gets/sets the value of the element's flexgroup attribute. height DOMString Gets/sets the value of the element's height attribute. hidden boolean true if the element's hidden attribute is the string "true",
otherwise false. Removes the attribute if you set it to false. id DOMString Gets/sets the value of the element's id attribute. left DOMString Gets/sets the value of the element's left attribute. maxHeight DOMString Gets/sets the value of the element's maxheight attribute. maxWidth DOMString Gets/sets the value of the element's maxwidth attribute. menu DOMString Gets/sets the value of the element'...
nsIEditorSpellCheck
() Checks a given word. In spite of the name, this function checks the word you give it, returning true if the word is misspelled. If the word is misspelled, it will compute the suggestions which you can get from GetSuggestedWord(). boolean CheckCurrentWord( in wstring suggestedWord ); Parameters suggestedWord Missing Description Return value true if the specified word is misspelled;
otherwise false. CheckCurrentWordNoSuggest() Like CheckCurrentWord(), checks the word you give it, returning true if it is misspelled. This is faster than CheckCurrentWord() because it does not compute any suggestions. Note: This does not clear any suggestions left over from previous calls to CheckCurrentWord(), so there may be suggestions, but they will be invalid. boolean CheckCurrentWordNoSuggest( i...
...his is faster than CheckCurrentWord() because it does not compute any suggestions. Note: This does not clear any suggestions left over from previous calls to CheckCurrentWord(), so there may be suggestions, but they will be invalid. boolean CheckCurrentWordNoSuggest( in wstring suggestedWord ); Parameters suggestedWord The word to check. Return value true if the word is misspelled;
otherwise false. GetCurrentDictionary() Returns the name of the dictionary currently in use. AString GetCurrentDictionary(); Parameters None. Return value The name of the dictionary currently in use. Typically, this is an ISO language code, such as "en-US". GetDictionaryList() Retrieves a list of the currently available dictionaries. The strings will typically be language IDs, such as "en-US". void GetDic...
... word The word to ignore when spell checking. InitSpellChecker() Turns on the spell checker for the given editor. void InitSpellChecker( in nsIEditor editor, in boolean enableSelectionChecking ); Parameters editor The nsIEditor on which to enable spell checking. enableSelectionChecking If true, the spell checker is initialized only for checking the current selection;
otherwise, it's initialized for checking the entire document. This affects the behavior of GetNextMisspelledWord()). For spell checking clients with no modal UI (such as inline spell checkers), this flag is not relevant. RemoveWordFromDictionary() Removes a word from the current personal dictionary. void RemoveWordFromDictionary( in wstring word ); Parameters word The word to remove from the c...
nsIExternalProtocolService
datastore or registered with the OS. boolean externalProtocolHandlerExists( in string aProtocolScheme ); Parameters aProtocolScheme The scheme from a url: http, ftp, mailto, and so on. Note: aProtocolScheme should not include a trailing colon, which is part of the URI syntax, not part of the scheme itself. That is, pass "mailto" not "mailto:". Return value true if we have a handler and false
otherwise. getApplicationDescription() Gets a human-readable description for the application responsible for handling a specific protocol. AString getApplicationDescription( in AUTF8String aScheme ); Parameters aScheme The scheme to look up. For example, "mms". Return value This code makes little sense and needs to be cleaned up. -Nickolay <pre> // first construct an nsIURI object using the ioservice ...
... represent a default handler for unknown content. Note: AProtocolScheme should not include a trailing colon, which is part of the URI syntax, not part of the scheme itself (That is pass "mailto" not "mailto:"). nsIHandlerInfo getProtocolHandlerInfo( in ACString aProtocolScheme ); Parameters aProtocolScheme The scheme from a URL: http, ftp, mailto, and so on. Return value The handler, if any;
otherwise a default handler. getProtocolHandlerInfoFromOS() Given a scheme, looks up the protocol info from the OS. This should be overridden by each OS's implementation. nsIHandlerInfo getProtocolHandlerInfoFromOS( in ACString aProtocolScheme, out boolean aFound ); Parameters aProtocolScheme The scheme from a url: http, ftp, mailto, and so on. aFound Was an OS default handler for this scheme found? ...
...For example, a non-exposed protocol would not be loaded by the application in response to a link click or a X-remote openURL command. Instead, it would be deferred to the system's external protocol handler. boolean isExposedProtocol( in string aProtocolScheme ); Parameters aProtocolScheme The scheme from a url: http, ftp, mailto, and so on. Return value true if the protocol is exposed, false
otherwise. loadURI() Used to load a URI via an external application. Might prompt the user for permission to load the external application. void loadURI( in nsIURI aURI, [optional] in nsIInterfaceRequestor aWindowContext ); Parameters aURI The URI to load. aWindowContext The window to parent the dialog against, and, if a web handler is chosen, it is loaded in this window as well. This parameter may b...
nsIMemory
recated since Gecko 2.0 voidPtr realloc(in voidPtr ptr, in size_t newSize); Violates the XPCOM interface guidelines Methods alloc Allocates a block of memory of a particular size. voidPtr alloc( in size_t size ); Parameters size The size of the block to allocate. Return value If the memory cannot be allocated (because of an out-of-memory condition), null is returned.
Otherwise, it returns a pointer to the newly allocated memory segment. The result must be freed with a call to free() when it is no longer needed. free Frees a previously allocated block of memory. void free( in voidPtr ptr ); Parameters ptr The address of the memory block to free. This may be null, in which case nothing happens. heapMinimize() Attempts to shrink the size of the heap. A parti...
...(what constitutes low-memory is platform dependent). This can be used to trigger the memory pressure observers. Note: This method was deprecated in Gecko 2.0. If you need to monitor low memory conditions, you should watch for the Low memory notifications "memory-pressure" notifications instead. boolean isLowMemory(); Parameters None. Return value true if we are in a low-memory situation.
Otherwise false. Note: From Gecko 2.0 always returns false. See bug 592308. realloc() Reallocates a block of memory to a new size. voidPtr realloc( in voidPtr ptr, in size_t newSize ); Parameters ptr The address of the memory block to reallocate. This may be null, in which case realloc behaves like alloc(). newSize Specifies the new size in bytes of the block of memory to allocate. This ma...
...emory to a new size. voidPtr realloc( in voidPtr ptr, in size_t newSize ); Parameters ptr The address of the memory block to reallocate. This may be null, in which case realloc behaves like alloc(). newSize Specifies the new size in bytes of the block of memory to allocate. This may be 0, in which case realloc behaves like alloc(). Return value null if the memory allocation fails.
Otherwise, it returns a pointer to the newly allocated memory segment. The result must be freed with a call to free() when it is no longer needed. Low memory notifications An nsIMemory implementation may be capable of monitoring heap usage. Moreover, a mechanism exists by which a client can receive notifications about low-memory situations. A client that wishes to be notified of low memory situations (f...
nsINavBookmarksService
der is marked as read-only. If this is set to true, UI will not allow the user to add, remove, or reorder children in this folder. The default for all folders is false. Note: This does not restrict API calls, only UI actions. boolean getFolderReadonly( in long long aItemId ); Parameters aItemId The item ID of the folder. Return value Returns true if the folder is marked as read-only,
otherwise returns false. getFolderTitle() Obsolete since Gecko 1.9 (Firefox 3) Note: getItemTitle() provides an alternative for this method. Get the title for a bookmark folder. AString getFolderTitle( in PRInt64 folder ); Parameters folder The folder whose title should be retrieved. Return value The title of the folder. Exceptions thrown invalid argument except...
... ID of the new separator. isBookmarked() This method checks whether or not the given URI is in any bookmark folder. If you want the results to be redirect-aware, use getBookmarkedURIFor() boolean isBookmarked( in nsIURI aURI ); Parameters aURI The URI whose existence in any bookmark folder is needed to be checked. Return value Returns true if the given URI is in any bookmark folder,
otherwise returns false. moveFolder() Obsolete since Gecko 1.9 (Firefox 3) Note: moveItem() provides an alternative for this method. Moves a folder to a different container, preserving its contents. void moveFolder( in PRInt64 folder, in PRInt64 newParent, in PRInt32 index ); Parameters folder The folder to move. newParent The id of the folder's new parent. inde...
...item. void setItemGUID( in long long aItemId, in AString aGUID ); Parameters aItemId The ID of the item to set the GUID of. aGUID The GUID string. setItemIndex() This method changes the index for a item. This method does not change the indices of any other items in the same folder, so ensure that the new index does not already exist, or change the index of other items accordingly,
otherwise the indices will become corrupted. Warning: This is API is intended for scenarios such as folder sorting, where the caller manages the indices of all items in the folder. You must always ensure each index is unique after a reordering. void setItemIndex( in long long aItemId, in long aNewIndex ); Parameters aItemId The ID of the item to modify. aNewIndex The new index. Except...
nsIZipReader
act. outFile The local file destination used to extract the zip entry. findEntries() Returns a string enumerator containing the matching entry names. nsIUTF8StringEnumerator findEntries( in AUTF8String aPattern ); Parameters aPattern A regular expression used to find matching entries in the zip file. Set this parameter to null (javascript) or EmptyCString() (c++) to get all entries;
otherwise, use the following syntax: * matches anything. ? matches one character. $ matches the end of the string. [abc] matches one occurrence of a, b, or c. The only character that must be escaped inside the brackets is ]. ^ and - must never appear in the first and second positions within the brackets, respectively. (In the former case, the behavior specified for '[^az]' will happen.) [a-z] m...
... strings except those containing a 'z'. Note that a pattern may not use '~' multiple times, so a string such as '*~*z*~*y*' is not a valid pattern. (foo|bar) will match either the pattern foo or the pattern bar. Neither of the patterns foo or bar may use the 'pat~pat2' syntax described immediately above. \ will escape a special character. Escaping is required for all special characters unless
otherwise specified. All other characters match case-sensitively. An aPattern not conforming to this syntax has undefined behavior. Return value The nsIUTF8StringEnumerator containing the matching entry names. Exceptions thrown NS_ERROR_ILLEGAL_VALUE On many but not all invalid aPattern values. getCertificatePrincipal() Returns an object describing the entity which signed an entry. par...
...ame of the entry to open() the stream from. Return value The nsIInputStream containing the contents of the specified zip entry. Example demonstrating this function: List Contents of XPI and Read File Contents getInputStreamWithSpec() Returns an input stream containing the contents of the specified zip entry. If the entry refers to a directory (ends with '/'), a directory stream is opened,
otherwise the contents of the file entry is returned. nsIInputStream getInputStreamWithSpec( in AUTF8String aJarSpec, in AUTF8String zipEntry ); Parameters aJarSpec The Spec of the URI for the JAR (only used for directory streams). zipEntry The name of the entry to open() the stream from. Return value The nsIInputStream containing the contents of the specified zip entry. hasEntry() Checks...
nsIZipWriter
ile to the archive. COMPRESSION_DEFAULT 6 Use the default compression method when adding the file to the archive. COMPRESSION_BEST 9 Use the best compression method when adding the file to the archive. Methods addEntryChannel() Adds data from a channel to the Zip file. If the operation is performed on the queue then the channel will be opened asynchronously,
otherwise the channel must support being opened synchronously. void addEntryChannel( in AUTF8String aZipEntry, in PRTime aModTime, in PRInt32 aCompression, in nsIChannel aChannel, in boolean aQueue ); Parameters aZipEntry The path of the file entry to add to the Zip file. This is the path it will be located at within the Zip file. Note: You must use forward slashes ('/') in the path. a...
...file entry to get. Return value An nsIZipEntry object describing the specified entry, or null if there is no such entry. hasEntry() Determines whether or not a specific entry exists in the Zip file. boolean hasEntry( in AUTF8String aZipEntry ); Parameters aZipEntry The path of the file entry to check for. Return value true if there is an entry with the given path in the Zip file,
otherwise returns false. open() Opens the specified Zip file. void open( in nsIFile aFile, in PRInt32 aIoFlags ); Parameters aFile The Zip file to open. aIoFlags The open flags for the Zip file, from prio.h. Exceptions thrown NS_ERROR_ALREADY_INITIALIZED A Zip file is already open. NS_ERROR_INVALID_ARG The aFile parameter is null. NS_ERROR_FILE_NOT_FOUND The specified file was not ...
... saveInZipAs = saveInZipAs.replace(/\\/g,'/'); //remember MUST use forward slash (/) Cu.reportError('--' + saveInZipAs); zw.addEntryFile(saveInZipAs, Ci.nsIZipWriter.COMPRESSION_NONE, entry, false); } } zw.close() } Other examples For other examples, take a look at the unit tests in the source t...
Getting Started Guide
adictions run deeper than that. All these cases show that automatically AddRefing on `output' makes nsCOMPtrs and raw-pointers act differently from the point of view of the clients. The goal is to make them act the same so that nsCOMPtrs can be a drop in replacement (modulo managing its own `ownership'). Given what you now know, the rule is predictable. As described above, and unless you tell it
otherwise, an nsCOMPtr AddRefs when you assign in to it. It does nothing when you assign out of it. Where should I use nsCOMPtrs? You should use an nsCOMPtr any place you use an interface pointer as an owning reference, i.e., where you call AddRef and Release on it. You should use nsCOMPtr as a member variable, where it will simplify setters, and eliminate constructors, destructors, and assignment operat...
...IFoo> myFoo( dont_AddRef(CreateFoo()) ); // Since |CreateFoo| already |AddRef|s its result, we must remind // our |nsCOMPtr| not to. It's easy to forget. Prevent it in advance // by not returning pointers as function results, or else by returning // an |already_AddRefed<T>| as above. void f( nsCOMPtr<T> ) don't pass an nsCOMPtr by value This practice is wasteful, but not
otherwise harmful. There is no need to AddRef parameters, as they are guaranteed to live as long as the function call. You only need to AddRef them as you store them in a structure that will live longer than the function call. Which means the appropriate member of that structure should be an nsCOMPtr, not the function parameter. Additionally, this signature may confuse callers into thinking they need an ns...
...at will live longer than the function call. Which means the appropriate member of that structure should be an nsCOMPtr, not the function parameter. Additionally, this signature may confuse callers into thinking they need an nsCOMPtr just to call the function. void f( const nsCOMPtr<T>& ) don't pass an nsCOMPtr by const reference Exactly as the signature above, this practice is wasteful, but not
otherwise harmful, and has the same impact as passing an nsCOMPtr by value if the caller only supplied a raw pointer. void f( nsCOMPtr<T>* ) avoid passing an nsCOMPtr by address, if possible This practice requires callers to have an nsCOMPtr, and requires them to do a little extra work, as operator& for nsCOMPtrs is private (to help prevent leaks caused by casting; also see bug 59414). This is an accepta...
Add to iPhoto
Application Services The Application Services framework consists of a number of different APIs that provide special services to applications. The Application Services API we'll be using is the Launch Services API, which is used to launch applications and open files in default (or specific, in our case) applications. The function we'll be using i...
...(node == undefined || !node) { return null; } // Is it an image node? var elemName = node.localName.toUpperCase(); if (elemName == "IMG") { return node; } // Nope, return null return null; } This starts by getting the node the popup was opened from. If this is null or undefined, we immediately return null, indicating there is no node associated with the context menu.
Otherwise, we fetch the name of the element and look to see if it's an <img> element. If so, we return that node;
otherwise, we return null. The important thing to take away from this is that this method returns either null or the image node the user right-clicked on. If they right-clicked anything other than an image, it returns null. Responding when the "Add Image to iPhoto" option is chosen When the ...
...a CFString referring to file:///Applications/iPhoto.app, which is iPhoto's default path, using CFStringCreateWithCharacters(). Create the corresponding CFURL object by calling CFURLCreateWithString(). Release the string using CFRelease(), since we're done with it. Call CFURLGetFSRef() to fill out the FSRef structure to reference the same file as the CFURL. If that fails, we display an error;
otherwise, we cast the CFMutableArrayRef into a CFArrayRef by calling ctypes.cast(), then call LSOpenURLsWithRole() to actually send the image to iPhoto. After doing that, we clean up after ourselves by releasing the CFURL object and the array, then shutting down the three libraries we used. Downloading the image The downloadImage() method handles actually downloading the image to a temporary file; it t...
Declaring and Using Callbacks
ks on other threads will cause things to crash. Prerequiste Understanding ABI FunctionType Declaring Callbacks A callback is declared by using ctypes.FunctionType. The first argument is the calling convention, the second argument is the return type, and the third is an array of arguments the callback expects. The return type of the javascript callback must match the return type declared,
otherwise js-ctypes will throw an error saying "unexpected return type". Examples Example 1 This callback that returns bool and has two arguments. var myFuncTypeDeclaration = ctypes.FunctionType(ctypes.default_abi, ctypes.bool, [ctypes.int, ctypes.voidptr_t]); function myJSCallback(cInt, cPtr) { return true; // as the return of the FunctionType was ctypes.bool we must make our javascript callback ...
...ill throw an error saying "unexpected return type". Examples Example 1 This callback that returns bool and has two arguments. var myFuncTypeDeclaration = ctypes.FunctionType(ctypes.default_abi, ctypes.bool, [ctypes.int, ctypes.voidptr_t]); function myJSCallback(cInt, cPtr) { return true; // as the return of the FunctionType was ctypes.bool we must make our javascript callback return bool
otherwise js-ctypes will throw error saying unexpected type return } var myCCallback = myFuncTypeDeclaration.ptr(myJSCallback); Example 2 This callback that returns void and no arguments. When void is the return type, the javascript callback must not return, or it should return undefined. var myFuncTypeDeclaration = ctypes.FunctionType(ctypes.default_abi, ctypes.void_t, []); function myJSCallback() {...
...mple 2 This callback that returns void and no arguments. When void is the return type, the javascript callback must not return, or it should return undefined. var myFuncTypeDeclaration = ctypes.FunctionType(ctypes.default_abi, ctypes.void_t, []); function myJSCallback() { return undefined; // as the return of the FunctionType was ctypes.void_t we must return undefined OR dont return at all
otherwise js-ctypes will throw an error saying unexpected type } var myCCallback = myFuncTypeDeclaration.ptr(myJSCallback); Using Callbacks Since callbacks are function pointers in C, js-ctypes has special handling for function pointer types. Consider the following code: function myJSCallback(foo, bar) { .... }; var funcType = ctypes.FunctionType(...); var funcPtrType = funcType.ptr; var regularFuncPt...
Debugger.Script - Firefox Developer Tools
to WebAssembly code", respectively. If the behavior does not differ, no such emphasized headings will appear. Accessor Properties of the Debugger.Script Prototype Object A Debugger.Script instance inherits the following accessor properties from its prototype: isGeneratorFunction True if this instance refers to a JSScript for a function defined with a function* expression or statement. False
otherwise. isAsyncFunction True if this instance refers to a JSScript for an async function, defined with an async function expression or statement. False
otherwise. displayName If the instance refers to a JSScript, this is the script's display name, if it has one. If the script has no display name -- for example, if it is a top-level eval script -- this is undefined. If the script's function has a...
...object describing the source code location responsible for the bytecode atoffset in this script. The object has the following properties: lineNumber: the line number for which offset is an entry point columnNumber: the column number for which offset is an entry point isEntryPoint: true if the offset is a column entry point, as would be reported by getAllColumnOffsets();
otherwise false. getOffsetsCoverage(): If the instance refers to a JSScript, return null or an array which contains informations about the coverage of all opcodes. The elements of the array are objects, each of which describes a single opcode, and contains the following properties: lineNumber: the line number of the current opcode. columnNumber: the column number of the current...
...lBreakpoints([offset]) If the instance refers to a JSScript, remove all breakpoints set in this script. Ifoffset is present, remove all breakpoints set at that offset in this script; ifoffset is not a valid bytecode offset in this script, throw an error. isInCatchScope([offset]) If the instance refers to a JSScript, this is true if this offset falls within the scope of a try block, and false
otherwise. If the instance refers to WebAssembly code, throw a TypeError. Source Metadata Generated from file: js/src/doc/Debugger/Debugger.Script.md Watermark: sha256:8816a4e8617be32c4ce7f3ae54970fe9c8a7d248175d215a8990ccff23e6efa9 Changeset: 5572465c08a9+ ...
Background Tasks API - Web APIs
s, with browser extensions needing processor time, and so forth. Avoid making changes to the DOM within your idle callback. By the time your callback is run, the current frame has already finished drawing, and all layout updates and computations have been completed. If you make changes that affect layout, you may force a situation in which the browser has to stop and do recalculations that would
otherwise be unnecessary. If your callback needs to change the DOM, it should use Window.requestAnimationFrame() to schedule that. Avoid tasks whose run time can't be predicted. Your idle callback should avoid doing anything that could take an unpredictable amount of time. For example, anything which might affect layout should be avoided. You should also avoid resolving or rejecting Promises, since that w...
...riod is expected to last, as well as whether or not the callback is running because its timeout period has expired. The Window interface is also augmented by this API to offer the new requestIdleCallback() and cancelIdleCallback() methods. Example In this example, we'll take a look at how you can use requestIdleCallback() to run time-consuming, low-priority tasks during time the browser would
otherwise be idle. In addition, this example demonstrates how to schedule updates to the document content using requestAnimationFrame(). Below you'll find only the HTML and JavaScript for this example. The CSS is not shown, since it's not particularly crucial to understanding this functionality. HTML content In order to be oriented about what we're trying to accomplish, let's have a look at the HTML. Th...
...We'll use that to determine if we should update the scroll position to ensure that the log stays at the end when we're done adding content to it. Next, we update the progress and status information if any tasks have been enqueued. If the current maximum value of the progress bar is different from the current total number of enqueued tasks (totalTaskCount), then we update th...
HTMLImageElement.height - Web APIs
Syntax htmlImageElement.height = newHeight; let height = htmlImageElement.height; Value An integer value indicating the height of the image. The terms in which the height is defined depends on whether the image is being rendered to a visual medium or not. ...
...ht of the image. Syntax htmlImageElement.height = newHeight; let height = htmlImageElement.height; Value An integer value indicating the height of the image. The terms in which the height is defined depends on whether the image is being rendered to a visual medium or not. If the image is being rendered to a visual medium such as a screen or printer, the height is expressed in CSS pixels.
Otherwise, the image's height is represented using its natural (intrinsic) height, adjusted for the display density as indicated by naturalHeight. Example In this example, two different sizes are provided for an image of a clock using the srcset attribute. One is 200px wide and the other is 400px wide. Further, the sizes attribute is provided to specify the width at which the image should be drawn given...
...ted by naturalHeight. Example In this example, two different sizes are provided for an image of a clock using the srcset attribute. One is 200px wide and the other is 400px wide. Further, the sizes attribute is provided to specify the width at which the image should be drawn given the viewport's width. HTML Specifically, for viewports up to 400px wide, the image is drawn at a width of 200px;
otherwise, it's drawn at 300px. <p>Image height: <span class="size">?</span>px (resize to update)</p> <img src="/files/17373/clock-demo-200px.png" alt="Clock" srcset="/files/17373/clock-demo-200px.png 200w, /files/17374/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 300px"> JavaScript The JavaScript code looks at the height to determine the height of the image gi...
HTMLImageElement.width - Web APIs
Syntax htmlImageElement.width = newWidth; let width = htmlImageElement.width; Value An integer value indicating the width of the image. The terms in which the width is defined depends on whether the image is being rendered to a visual medium or not. ...
...ted width of the image. Syntax htmlImageElement.width = newWidth; let width = htmlImageElement.width; Value An integer value indicating the width of the image. The terms in which the width is defined depends on whether the image is being rendered to a visual medium or not. If the image is being rendered to a visual medium such as a screen or printer, the width is expressed in CSS pixels.
Otherwise, the image's width is represented using its natural (intrinsic) width, adjusted for the display density as indicated by naturalWidth. Example In this example, two different sizes are provided for an image of a clock using the srcset attribute. One is 200px wide and the other is 400px wide. Further, the sizes attribute is provided to specify the width at which the image should be drawn given th...
...ated by naturalWidth. Example In this example, two different sizes are provided for an image of a clock using the srcset attribute. One is 200px wide and the other is 400px wide. Further, the sizes attribute is provided to specify the width at which the image should be drawn given the viewport's width. HTML Specifically, for viewports up to 400px wide, the image is drawn at a width of 200px;
otherwise, it's drawn at 400px. <p>Image width: <span class="size">?</span>px (resize to update)</p> <img src="/files/16864/clock-demo-200px.png" alt="Clock" srcset="/files/16864/clock-demo-200px.png 200w, /files/16797/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 400px"> JavaScript The JavaScript code looks at the width to determine the width of the image at th...
HTMLInputElement - Web APIs
ative text to use when type is image. height string: Returns / Sets the element's height attribute, which defines the height of the image displayed for the button, if the value of type is image. src string: Returns / Sets the element's src attribute, which specifies a URI for the location of an image to display on the graphical submit button, if the value of type is image;
otherwise it is ignored. width string: Returns / Sets the document's width attribute, which defines the width of the image displayed for the button, if the value of type is image. Properties that apply only to elements of type file accept string: Returns / Sets the element's accept attribute, containing comma-separated list of file types accepted by the server when type is f...
...value can have. (If you set this to a negative number, an exception will be thrown.) pattern string: Returns / Sets the element's pattern attribute, containing a regular expression that the control's value is checked against. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url or email;
otherwise it is ignored. placeholder string: Returns / Sets the element's placeholder attribute, containing a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the type attribute is text, search, tel, url or email;
otherwise it is ignored. readOnly boolean: Returns / ...
... locale backward for the opposite direction none if the direction is unknown size unsigned long: Returns / Sets the element's size attribute, containing visual size of the control. This value is in pixels unless the value of type is text or password, in which case, it is an integer number of characters. Applies only when type is set to text, search, tel, url, email, or password;
otherwise it is ignored. Properties not yet categorized defaultValue string: Returns / Sets the default value as originally specified in the HTML that created this object. dirName string: Returns / Sets the directionality of the element. accessKey string: Returns a string containing a single character that switches input focus to the control when pressed. ...
Drag Operations - Web APIs
he cursor might appear with a plus sign next to it. You can modify the dropEffect property during the dragenter or dragover events, if for example, a particular drop target only supports certain operations. You can modify the dropEffect property to override the user effect, and enforce a specific drop operation to occur. Note that this effect must be one listed within the effectAllowed property.
Otherwise, it will be set to an alternate value that is allowed. event.dataTransfer.dropEffect = "copy"; In this example, copy is the effect that is performed. You can use the value none to indicate that no drop is allowed at this location, although it is preferred not to cancel the event in this case. Within the drop and dragend events, you can check the dropEffect property to determine which effect ...
...ancelled, so you can always ensure that any insertion point cleanup can be done during this event. Performing a Drop When the user releases the mouse, the drag and drop operation ends. If the mouse is released over an element that is a valid drop target, that is, one that cancelled the last dragenter or dragover event, then the drop will be successful, and a drop event will fire at the target.
Otherwise, the drag operation is cancelled, and no drop event is fired. During the drop event, you should retrieve that data that was dropped from the event and insert it at the drop location. You can use the dropEffect property to determine which drag operation was desired. As with all drag-related events, the event's dataTransfer property will hold the data that is being dragged. The getData() method m...
...g a Drag Once the drag is complete, a dragend event is fired at the source of the drag (the same element that received the dragstart event). This event will fire if the drag was successful[1] or if it was cancelled. However, you can use the dropEffect property to determine which drop operation occurred. If the dropEffect property has the value none during a dragend, then the drag was cancelled.
Otherwise, the effect specifies which operation was performed. The source can use this information after a move operation to remove the dragged item from the old location. The mozUserCancelled property will be set to true if the user cancelled the drag (by pressing Escape), and false if the drag was cancelled for other reasons such as an invalid drop target, or if it was successful. A drop can occur insid...
Key Values - Web APIs
l dead keys. Dead keys are keys which are pressed in combination with character keys to generate accented forms of those characters. You can identify which specific dead key was used (if more than one exists) by examining the KeyboardEvent's associated compositionupdate event's data property. You can find a table of the dead keys and the characters they can be used with to generate accented or
otherwise special characters on Linux using GTK. The value of data will be one of the following: CompositionEvent.data value Symbol Comments GDK_KEY_dead_grave (0xFE50) Qt::Key_Dead_Grave (0x01001250) ` GDK_KEY_dead_acute (0xFE51) Qt::Key_Dead_Acute (0x01001251) ' GDK_KEY_dead_circumflex (0xFE52) Qt::Key_Dead_Circumflex (0x01001252) ...
... "MediaPause" Pauses the currently playing media. Note: Some older applications use simply "Pause", but this is not correct. APPCOMMAND_MEDIA_PAUSE GDK_KEY_AudioPause (0x1008FF31) Qt::Key_MediaPause (0x1000085) KEYCODE_MEDIA_PAUSE (127) "MediaPlay" Starts or continues playing media at normal speed, if not already doing so. Has no effect
otherwise. APPCOMMAND_MEDIA_PLAY GDK_KEY_AudioPlay (0x1008FF14) KEYCODE_MEDIA_PLAY (126) "MediaPlayPause" Toggles between playing and pausing the current media. VK_MEDIA_PLAY_PAUSE (0xB3) APPCOMMAND_MEDIA_PLAY_PAUSE Qt::Key_MediaTogglePlayPause (0x1000086) KEYCODE_MEDIA_PLAY_PAUSE (85) "MediaRecord" Starts or resumes recording media. APPCOMMAND_MEDIA...
...[3] Cycles through the available video modes. VK_VIDEO_MODE_NEXT GDK_KEY_Next_VMode (0x1008FE22) "Wink" Causes the device to identify itself in some fashion, such as by flashing a light, briefly changing the brightness of indicator lights, or emitting a tone. VK_WINK "ZoomToggle" [2] Toggles between full-screen and scaled content display, or
otherwise change the magnification level. VK_ZOOM (0xFB) Qt::Key_Zoom (0x01020006) KEYCODE_TV_ZOOM_MODE (255) [1] Don't confuse the media controller VK_APPS key with the Windows VK_APPS key, which is also known as VK_CONTEXT_MENU. That key is encoded as "ContextMenu". [2] Internet Explorer (tested on release 9 and 11) and Firefox 36 and earlier identify the zoom toggle button as "Zoom"...
MediaTrackSettings - Web APIs
ID, though. This value is specific to the source of the track's data and is not usable for setting constraints; it can, however, be used for initially selecting media when calling MediaDevices.getUserMedia(). Properties of audio tracks autoGainControl A Boolean which indicates the current value of the autoGainControl property, which is true if automatic gain control is enabled and is false
otherwise. channelCount A long integer value indicating the current value of the channelCount property, specifying the number of audio channels present on the track (therefore indicating how many audio samples exist in each audio frame). This is 1 for mono, 2 for stereo, and so forth. echoCancellation A Boolean indicating the current value of the echoCancellation property, specifying true if echo cance...
...ong integer value indicating the current value of the channelCount property, specifying the number of audio channels present on the track (therefore indicating how many audio samples exist in each audio frame). This is 1 for mono, 2 for stereo, and so forth. echoCancellation A Boolean indicating the current value of the echoCancellation property, specifying true if echo cancellation is enabled,
otherwise false. latency A double-precision floating point value indicating the current value of the latency property, specifying the audio latency, in seconds. Latency is the amount of time which elapses between the start of processing the audio and the data being available to the next stop in the audio utilization process. This value is a target value; actual latency may vary to some extent for various...
...the amount of time which elapses between the start of processing the audio and the data being available to the next stop in the audio utilization process. This value is a target value; actual latency may vary to some extent for various reasons. noiseSuppression A Boolean which indicates the current value of the noiseSupression property, which is true if noise suppression is enabled and is false
otherwise. sampleRate A long integer value indicating the current value of the sampleRate property, specifying the sample rate in samples per second of the audio data. Standard CD-quality audio, for example, has a sample rate of 41,000 samples per second. sampleSize A long integer value indicating the current value of the sampleSize property, specifying the linear size, in bits, of each audio sample...
MutationObserverInit - Web APIs
subtree Optional Set to true to extend monitoring to the entire subtree of nodes rooted at target. ...
...tional Set to true to monitor the target node (and, if subtree is true, its descendants) for the addition of new child nodes or removal of existing child nodes. The default value is false. attributes Optional Set to true to watch for changes to the value of attributes on the node or nodes being monitored. The default value is true if either of attributeFilter or attributeOldValue is specified,
otherwise the default value is false. attributeFilter Optional An array of specific attribute names to be monitored. If this property isn't included, changes to all attributes cause mutation notifications. attributeOldValue Optional Set to true to record the previous value of any attribute that changes when monitoring the node or nodes for attribute changes; see Monitoring attribute values in MutationO...
... see Monitoring attribute values in MutationObserver for details on watching for attribute changes and value recording. The default value is false. characterData Optional Set to true to monitor the specified target node (and, if subtree is true, its descendants) for changes to the character data contained within the node or nodes. The default value is true if characterDataOldValue is specified,
otherwise the default value is false. characterDataOldValue Optional Set to true to record the previous value of a node's text whenever the text changes on nodes being monitored. For details and an example, see Monitoring text content changes in MutationObserver. The default value is false. Specifications Specification Status Comment DOMThe definition of 'MutationObserverIn...
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
by separating that difference out into independent negotiation logic, so that your application doesn't need to care which end of the connection it is. As far as your application is concerned, it makes no difference whether you're calling out or receiving a call. The best thing about perfect negotiation is that the same code is used for both the caller and the callee, so there's no repetition or
otherwise added levels of negotiation code to write. Perfect negotiation works by assigning each of the two peers a role to play in the negotiation process that's entirely separate from the WebRTC connection state: A polite peer, which uses ICE rollback to prevent collisions with incoming offers. A polite peer, essentially, is one which may send out offers, but then responds if an offer arrives from th...
...x 0, because we passed one stream into addTrack() earlier. We add an unmute event handler to the track, because the track will become unmuted once it starts receiving packets. We put the remainder of our reception code in there. If we already have video coming in from the remote peer (which we can see if the remote view's <video> element's srcObject property already has a value), we do nothing.
Otherwise, we set srcObject to the stream at index 0 in the streams array. The perfect negotiation logic Now we get into the true perfect negotiation logic, which functions entirely independently from the rest of the application. Handling the negotiationneeded event First, we implement the RTCPeerConnection event handler onnegotiationneeded to get a local description and send it using the signaling cha...
...gets sent to the polite peer using the signaling channel. If the incoming message is an ICE candidate rather than an SDP description, it's simply delivered to the ICE layer by passing it into the RTCPeerConnection method addIceCandidate(). If an error occurs here and we didn't just discard an offer due to being the impolite peer during a collision, we throw the error so the caller can handle it.
Otherwise, we drop the error, ignoring it, since it doesn't matter in this context. Perfect negotiation with the updated API The updated code takes advantage of the fact that you can now call setLocalDescription() with no parameters so it just does the right thing for you, as well as the fact that setRemoteDescription() automatically rolls back if necessary. This lets us get rid of the need to use a Prom...
Using DTMF with WebRTC - Web APIs
Track) { receiverPC.ontrack = handleReceiverTrackEvent; } else { receiverPC.onaddstream = handleReceiverAddStreamEvent; } navigator.mediaDevices.getUserMedia(mediaConstraints) .then(gotStream) .catch(err => log(err.message)); } After creating the RTCPeerConnection for the caller (callerPC), we look to see if it has an addTrack() method. If it does, we set hasAddTrack to true;
otherwise, we set it to false. This variable will let the example operate even on browsers not yet implementing the newer addTrack() method; we'll do so by falling back to the older addStream() method. Next, the event handlers for the caller are established. We'll cover these in detail later. Then a second RTCPeerConnection, this one representing the receiving end of the call, is created and stored in re...
...ll do so by falling back to the older addStream() method. Next, the event handlers for the caller are established. We'll cover these in detail later. Then a second RTCPeerConnection, this one representing the receiving end of the call, is created and stored in receiverPC; its onicecandidate event handler is set up too. If addTrack() is supported, we set up the receiver's ontrack event handler;
otherwise, we set up onaddstream. The track and addstream events are sent when media is added to the connection. Finally, we call getUserMedia() to obtain access to the caller's microphone. If successful, the function gotStream() is called,
otherwise we log the error because calling has failed. Adding the audio to the connection As mentioned above, when the audio input from the microphone is obtained, g...
...udioTracks[0]); } dtmfSender.ontonechange = handleToneChangeEvent; } After setting audioTracks to be a list of the audio tracks on the stream from the user's microphone, it's time to add the media to the caller's RTCPeerConnection. If addTrack() is available on the RTCPeerConnection, we add each of the stream's audio tracks, one by one, to the connection using RTCPeerConnection.addTrack().
Otherwise we call RTCPeerConnection.addStream() to add the stream to the call as a single unit. Next we look to see if the RTCPeerConnection.getSenders() method is implemented. If it is, we call it on callerPC and get the first entry in the returned list of senders; this is the RTCRtpSender responsible for transmitting data for the first audio track on the call (which is the track we'll send DTMF over). W...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
ion of an object in space--even if that space if virtual--can be represented using three numbers that indicate its position relative to the origin, whose position is defined to be (0, 0, 0). There's another aspect of the spatial relationship of an object to the origin in space left to be considered: perspective. Perspective, properly applied to the objects in a scene, can take a scene that would
otherwise look as flat as a typical 2D screen and make it pop as if it were truly 3D. There are several kinds of perspective; those are defined and their mathematics explained in the article WebGL model view projection. Importantly, the effect of perspective on a vector can be represented by adding a fourth component to the vector: the perspective component, called w. The value of w is applied by dividing...
...point in the 3D space is actually (x/w, y/w, z/w, 1) or simply (x/w, y/w, z/w). If you're not using perspective, w is always 1. In that situation, the complete coordinates for an object located at (1, 0, 3) are (1, 0, 3, 1). But the location isn't enough to describe an object in 3D space because an object's state in space isn't only about its location, but about its rotation or facing direction,
otherwise known as its orientation. The orientation can be represented using a 3D vector, which is typically normalized so that its length is 1.0. For example, if the object is facing an object located at (3, 1, -2)--that is, three meters to the right, one meter up, and two meters away from the origin point--the result is: [31-2]\left [ \begin{matrix} 3 \\ 1 \\ -2 \end{matrix} \right ] This can also be ...
...The position of the camera in space does not change, only the direction in which it's looking. And that direction does not change other than horizontally. Panning is great for establishing a setting or providing a sense of scope in a vast space or on a vast object. Or just for looking left and right, like simulating the player turning their head in an immersive or VR scenario. ...
Geometry and reference spaces in WebXR - Web APIs
racking space whose native origin tracks the viewer's position and orientation. This is used for environments in which the user can physically move around, and is supported by all instances of XRSession, both immersive and inline, though it's most useful for inline sessions. It's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces.
Otherwise, typically, one of the other reference space types will be used more often. XRReferenceSpace The remainder of this guide explores how to select the right reference space for your app's needs. Defining spatial relationships with reference spaces There are a number of commonly used ways to reference the positions and orientations of objects relative to their environment, as well as to ...
...e local, local-floor, unbounded, or bounded-floor. Floor level reference spaces The reference space types with -floor in their names work just like the corresponding non-floor spaces, except that they attempt to automatically ensure that the viewer is positioned in a safe place at or near (but always above) ground level. This is the plane at which the y coordinate is always 0, unless a floor is
otherwise established. These space types are not viable if the rooms have uneven floors or floors whose height above ground level vary, since they don't support the avatar's vertical position changing. The primary reference space types The viewer reference space corresponds to the viewer's position in space; it's used by the XRViewerPose returned by the XRFrame method getViewerPose(). It's not typically ...
...These space types are not viable if the rooms have uneven floors or floors whose height above ground level vary, since they don't support the avatar's vertical position changing. The primary reference space types The viewer reference space corresponds to the viewer's position in space; it's used by the XRViewerPose returned by the XRFrame method getViewerPose(). It's not typically used directly
otherwise. The only real exception is that you are likely to use the viewer reference space when performing the XR scene inline within web content. The local reference space is typically used to describe a relatively small area, such as a single room. It is not only always available when using an immersive session mode (immersive-vr or immersive-ar), but is always included among the optional features when...
Starting up and shutting down a WebXR session - Web APIs
it may not be enabled by default. There may be options available to allow you to experiment with WebXR even if you don't have a compatible system, however. WebXR polyfill The team designing the WebXR specification has published a WebXR polyfill which you can use to simulate WebXR on browsers which don't have support for the WebXR APIs. If the browser supports the older WebVR API, that is used.
Otherwise, the polyfill falls back to an implementation which uses Google's Cardboard VR API. The polyfill is maintained alongside the specification, and is kept up to date with the specification. Additionally, it is updated to maintain compatibility with browsers as their support for WebXR and other technologies related to it and to the implementation of the polyfill change over time. Be sure to read th...
...heck to see if the user's hardware and software support the presentation mode you wish to use. This can also be used to determine whether to use an immersive or an inline presentation, for example. To find out if a given mode is supported, simply call the XRSystem method isSessionSupported(). This returns a promise which resolves to true if the given type of session is available for use or false
otherwise. const immersiveOK = await navigator.xr.isSessionSupported("immersive-vr"); if (immersiveOK) { // Create and use an immersive VR session } else { // Create an inline session instead, or tell the user about the // incompatibility if inline is required } Creating and starting the session A WebXR session is represented by an XRSession object. To obtain an XRSession, you call your XRSystem'...
... an XRSession can happen either due to the session itself deciding it's time to shut down (such as if the user turns off their XR device), because the user has clicked a button to end the session, or some other situation as appropriate for your application. Here we discuss both how to request a shutdown of the WebXR session and how to detect when the session has ended, whether by your request or
otherwise. Shutting down the session To cleanly shut down the WebXR session when you're done with it, you should call the session's end() method. This returns a promise you can use to know when the shutdown is complete. async function shutdownXR(session) { if (session) { await session.end(); /* At this point, WebXR is fully shut down */ } } When shutdownXR() returns to its caller, the Web...
Using IIR filters - Web APIs
ou can create a highpass filter, or a lowpass filter, or a more bespoke one. And this is where the IIR filter node is useful -- you can create your own if none of the alaready available settings is right for what you want. As well as this, if your audio graph needed a highpass and a bandpass filter within it, you could just use one IIR filter node in place of the two biquad filter nodes you would
otherwise need for this. With the IIRFIlter node it's up to you to set what feedforward and feedback values the filter needs -- this determines the characteristics of the filter. The downside is that this involves some complex maths. If you are looking to learn more there's some information about the maths behind IIR filters here. This enters the realms of signal processing theory -- don't worry if you l...
...t the code to create an IIR filter with the Web Audio API. Setting our IIRFilter co-efficients When creating an IIR filter, we pass in the feedforward and feedback coefficients as options (coefficients is how we describe the values). Both of these parameters are arrays, neither of which can be larger than 20 items. ...
...ns (coefficients is how we describe the values). Both of these parameters are arrays, neither of which can be larger than 20 items. When setting our coefficients, the feedforward values can't all be set to zero,
otherwise nothing would be sent to the filter. Something like this is acceptable: let feedForward = [0.00020298, 0.0004059599, 0.00020298]; Our feedback values cannot start with zero,
otherwise on the first pass nothing would be sent back: let feedBackward = [1.0126964558, -1.9991880801, 0.9873035442]; Note: These values are calculated based on the lowpass filter specified in the filter characteristics of the Web Audio API specification. As this filter node gains more popularity we should be able to collate more coefficient values. Using an IIRFilter in an audio graph Let's creat...
Window: popstate event - Web APIs
history stack If the history entry being activated was created by a call to history.pushState() or was affected by a call to history.replaceState(), the popstate event's state property contains a copy of the history entry's state object. These methods and their corresponding events can be used to add data to the history stack which can be used to reconstruct a dynamically generated page, or to
otherwise alter the state of the content being presented while remaining on the same Document. Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history.back() or history.forward() in JavaScript). Browsers tend to handle the popstate e...
...It happens after the new location has loaded (if needed), displayed, made visible, and so on, after the pageshow event is sent, but before the persisted user state information is restored and the hashchange event is sent. To better understand when the popstate event is fired, consider this simplified sequence o...
...methods such as go()) is removed from the history stack. If the new-entry doesn't have persisted user state and its URL's fragment is non-null, the document is scrolled to that fragment. Next, current-entry is set to new-entry. The destination entry is now considered to be current. If new-entry has serialized state information saved with it, that information is deserialized into History.state;
otherwise, state is null. If the value of state changed, the popstate event is sent to the document. Any persisted user state is restored, if the browser chooses to do so. If the original and new entry's shared the same document, but had different fragments in their URLs, send the hashchange event to the window. As you can see, the popstate event is nearly the last thing done in the process of navigat...
XRWebGLLayer() - Web APIs
identifying the WebGL drawing context to use for rendering the scene for the specified WebXR session. layerInit Optional An object conforming to the XRWebGLLayerInit dictionary, providing configuration options for the new XRWebGLLayer. The options available are: alpha Optional The frame buffer's color buffer will be established with an alpha channel if the alpha Boolean property is true.
Otherwise, the color buffer will not have an alpha channel. The default value is true. antialias Optional A Boolean value which is true if anti-aliasing is to be used when rendering in the context;
otherwise false. The browser selects the anti-aliasing method to use; there is no support for requesting a specific mode yet. The default value is true. depth Optional A Boolean value which, if true, reques...
...The default is true. framebufferScaleFactor Optional A floating-point value which is used to scale the image during compositing, with a value of 1.0 represents the default pixel size for the frame buffer. ...
...n a 1:1 pixel ratio, thereby ensuring that the rendering is occurring at the device's native resolution. The default is 1.0. ignoreDepthValues Optional A Boolean value which indicates whether or not to ignore the contents of the depth buffer while compositing the scene. The default is false. stencil Optional A Boolean value which, if true, requests that the new layer include a stencil buffer.
Otherwise, no stencil buffer is allocated. The default is false. Return value A newly-created XRWebGLLayer which links the specified XRSession to the WebGL context given by context, which will be used as the renderer for the session. Any options specified in layerInit are used to tailor the rendering system's configuration. Exceptions InvalidStateError The new XRWebGLLayer could not be created d...
XRWebGLLayerInit - Web APIs
API's XRWebGLLayerInit dictionary is used to provide configuration options when creating a new XRWebGLLayer object with the XRWebGLLayer() constructor. The constructor's optional layerInit parameter takes an object which must conform to this dictionary. Properties alpha Optional The frame buffer's color buffer will be established with an alpha channel if the alpha Boolean property is true.
Otherwise, the color buffer will not have an alpha channel. The default value is true. antialias Optional A Boolean value which is true if anti-aliasing is to be used when rendering in the context;
otherwise false. The browser selects the anti-aliasing method to use; there is no support for requesting a specific mode yet. The default value is true. depth Optional A Boolean value which, if true, reques...
...The default is true. framebufferScaleFactor Optional A floating-point value which is used to scale the image during compositing, with a value of 1.0 represents the default pixel size for the frame buffer. ...
...n a 1:1 pixel ratio, thereby ensuring that the rendering is occurring at the device's native resolution. The default is 1.0. ignoreDepthValues Optional A Boolean value which indicates whether or not to ignore the contents of the depth buffer while compositing the scene. The default is false. stencil Optional A Boolean value which, if true, requests that the new layer include a stencil buffer.
Otherwise, no stencil buffer is allocated. The default is false. Examples Given an XRSession, xrSession, and a WebGL rendering context, gl, this snippet sets the rendering layer for the session, specifying the ignoreDepthValues option, indicating that the depth buffer should not be used (or should not exist at all), and that the only source for distance information of any given point is its position rel...
An overview of accessible web applications and widgets - Accessibility
nd in dynamic web applications, ARIA provides roles and states that describe the behavior of most familiar UI widgets. Many of these were later added in HTML5, and developers should always prefer using the correct semantic HTML element over using ARIA. The ARIA specification is split up into three different types of attributes: roles, states, and properties. Roles describe widgets that aren't
otherwise available in HTML 4, such as sliders, menu bars, tabs, and dialogs. Properties describe characteristics of these widgets, such as if they are draggable, have a required element, or have a popup associated with them. States describe the current interaction state of an element, informing the assistive technology if it is busy, disabled, selected, or hidden. ARIA attributes are interpreted automati...
... around invalid data, or changing the background color of a checked checkbox), as well as showing or hiding content. State changes ARIA provides attributes for declaring the current state of a UI widget. ...
...idden property has the form shown in Example 2c. Note that the script only updates the aria-hidden attribute (line 2); it does not need to also add or remove a custom classname. Example 2c. JavaScript to update the aria-checked attribute var showTip = function(el) { el.setAttribute('aria-hidden', 'false'); } Role changes ARIA allows developers to declare a semantic role for an element that
otherwise offers incorrect or no semantics. The role of an element should not change. Instead, remove the original element and replace it with an element with the new role. For example, consider an "inline edit" widget: a component that allows users to edit a piece of text in place, without switching contexts. This component has a "view" mode, in which the text is not editable, but is activatable, and an ...
overflow-wrap - CSS: Cascading Style Sheets
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Note: In contrast to word-break, overflow-wrap will only create a break if an entire word cannot be placed on its own line without overflowing. ...
...ow-wrap: normal; overflow-wrap: break-word; overflow-wrap: anywhere; /* Global values */ overflow-wrap: inherit; overflow-wrap: initial; overflow-wrap: unset; The overflow-wrap property is specified as a single keyword chosen from the list of values below. Values normal Lines may only break at normal word break points (such as a space between two words). anywhere To prevent overflow, an
otherwise unbreakable string of characters -- like a long word or URL -- may be broken at any point if there are no
otherwise-acceptable break points in the line. No hyphenation character is inserted at the break point. Soft wrap opportunities introduced by the word break are considered when calculating min-content intrinsic sizes. break-word The same as the anywhere value, with normally unbreakable word...
...L -- may be broken at any point if there are no
otherwise-acceptable break points in the line. No hyphenation character is inserted at the break point. Soft wrap opportunities introduced by the word break are considered when calculating min-content intrinsic sizes. break-word The same as the anywhere value, with normally unbreakable words allowed to be broken at arbitrary points if there are no
otherwise acceptable break points in the line, but soft wrap opportunities introduced by the word break are NOT considered when calculating min-content intrinsic sizes. Formal definition Initial valuenormalApplies tonon-replaced inline elementsInheritedyesComputed valueas specifiedAnimation typediscrete Formal syntax normal | break-word | anywhere Examples Comparing overflow-wrap, word-break, and hy...
shape-outside - CSS: Cascading Style Sheets
by the outside content edge. Each corner radius of this box is the larger of 0 or border-radius - border-width - padding. <basic-shape> The float area is computed based on the shape created by of one of inset(), circle(), ellipse(), polygon(), or as added in the level 2 specification path(). If a <shape-box> is also supplied, it defines the reference box for the <basic-shape> function.
Otherwise, the reference box defaults to margin-box. <image> The float area is extracted and computed based on the alpha channel of the specified <image> as defined by shape-image-threshold. Note: User agents must use the potentially CORS-enabled fetch method defined by the HTML5 specification for all URLs in a shape-outside value. When fetching, user agents must use "Anonymous" mode, set the referrer...
... shapes are of type polygon(), both polygons have the same number of vertices, and use the same <fill-rule>, interpolate between each value in the shape functions. In all other cases no interpolation occurs. ...
...ces, and use the same <fill-rule>, interpolate between each value in the shape functions. In all other cases no interpolation occurs. ...
Creating a cross-browser video player - Developer guides
ile. This provides the player with data such as video duration and format. Note: IE9 behaves differently than most other browsers when a poster attribute is set. Most browsers interpret the presence of a poster attribute to mean that the specified image is to be displayed until the user chooses to play the video. IE9 will only use the specified poster image in this way if preload="none" is set;
otherwise, it will take the first still of the video and display that instead. Three different video sources are provided for the player: MP4, WebM, and Ogg. Using these different source formats gives the best chance of being supported across all browsers that support HTML5 video. For further information on video formats and browser compatibility, see supported media formats. For browsers that do not su...
...d on the video. Play/Pause playpause.addEventListener('click', function(e) { if (video.paused || video.ended) video.play(); else video.pause(); }); When a click event is detected on the play/pause button, the handler first of all checks if the video is currently paused or has ended (via the Media API's paused and ended attributes); if so, it uses the play() method to playback the video.
Otherwise the video must be playing, so it is paused using the pause() method. Stop stop.addEventListener('click', function(e) { video.pause(); video.currentTime = 0; progress.value = 0; }); The Media API doesn't have a stop method, so to mimic this the video is paused, and its currentTime (i.e. the video's current playing position) and the <progress> element's position is set to 0 (more on th...
...idth; video.currentTime = pos * video.duration; }); This piece of code simply uses the clicked position to (roughly) work out where in the progress element the user has clicked, and to move the video to that position by setting its currentTime attribute. Fullscreen The Fullscreen API should be straight forward to use: the user clicks a button, if the video is in fullscreen mode: cancel it,
otherwise enter fullscreen mode. Alas it has been implemented in browsers in a number of weird and wonderful ways which requires a lot of extra code to check for various prefixed versions of attributes and methods so as to call the right one. To detect if a browser actually supports the Fullscreen API and that it is enabled, the following may be called: var fullScreenEnabled = !!(document.fullscreenEnab...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
the descriptions of the standard attributes. Individual attributes accept Valid for the file input type only, the accept attribute defines which file types are selectable in a file upload control. See the file input type. alt Valid for the image button only, the alt attribute provides alternative text for the image, displaying the value of the attribute if the image src is missing or
otherwise fails to load. See the image input type. autocomplete (Not a Boolean attribute!) The autocomplete attribute takes as its value a space-separated string that describes what, if any, type of autocomplete functionality the input should provide. A typical implementation of autocomplete simply recalls previous values entered in the same input field, but more complex forms of autocomplete can exi...
...ich represents <input> elements in the DOM. Also available are those methods specified by the parent interfaces, HTMLElement, Element, Node, and EventTarget. checkValidity() Immediately runs the validity check on the element, triggering the document to fire the invalid event at the element if the value isn't valid. reportValidity() Returns true if the element's value passes validity checks;
otherwise, returns false. select() Selects the entire content of the <input> element, if the element's content is selectable. For elements with no selectable text content (such as a visual color picker or calendar date input), this method does nothing. setCustomValidity() Sets a custom message to display if the input element's value isn't valid. setRangeText() Sets the contents of the specified range...
...o-classes Captions super relevant to the <input> element: Pseudo-class Description :enabled Any currently enabled element that can be activated (selected, clicked on, typed into, etc.) or accept focus and also has a disabled state, in which it can't be activated or accept focus. :disabled Any currently disabled element that has an enabled state, meaing it
otherwise could be activated (selected, clicked on, typed into, etc.) or accept focus were it not disabled. :read-only Element not editable by the user :read-write Element that is editable by the user. :placeholder-shown Element that is currently displaying placeholder text, including <input> and <textarea> elements with the placeholder attribute present that has, as of ...
itemprop - HTML: Hypertext Markup Language
mprop country Ireland itemprop Option 2 itemprop https://www.flickr.com/photos/nlireland/6992065114/ Ring of Kerry itemprop img https://www.flickr.com/photos/nlireland/6992065114/ itemprop website flickr itemprop (token) (token) Tokens are either strings or URL's. An item is called a typed item if it is a URL.
Otherwise, it is a string. Strings cannot contain a period or a colon (see below). If the item is a typed item it must be either: A defined property name, or A valid URL, which refers to the vocabulary definition, or A valid URL that is used as a proprietary item property name (i.e. one not defined in a public specification), or If the item is not a typed item it must be: A strin...
... property name (i.e. one not defined in a public specification), or If the item is not a typed item it must be: A string that contains no "." (U+002E FULL STOP) characters and no ":" characters (U+003A COLON) and is used as a proprietary item property name (again, one not defined in a public specification). Note: the rules above disallow ":" characters in non-URL values because
otherwise they could not be distinguished from URLs. Values with "." characters are reserved for future extensions. Space characters are disallowed because
otherwise the values would be parsed as multiple tokens. Values The property value of a name-value pair is as given for the first matching case in the following list: If the element has an itemscope attribute The value is the item created by...
... If a property's value is a URL, the property must be specified using a URL property element. The URL property elements are the a, area, audio, embed, iframe, img, link, object, source, track, and video elements. Name order Names are unordered relative to each other, but if a particular name has multiple values, they do have a relative order. In the ...
HTTP headers - HTTP
ill be used when the actual request is made. Access-Control-Request-Method Used when issuing a preflight request to let the server know which HTTP method will be used when the actual request is made. Origin Indicates where a fetch originates from. Timing-Allow-Origin Specifies origins that are allowed to see values of attributes retrieved via features of the Resource Timing API, which would
otherwise be reported as zero due to cross-origin restrictions. Do Not Track DNT Expresses the user's tracking preference. Tk Indicates the tracking status of the corresponding response. Downloads Content-Disposition Indicates if the resource transmitted should be displayed inline (default behavior without the header), or if it should be handled like a download and the browser should present ...
...cessfully handle the upgrade-insecure-requests directive. X-Content-Type-Options Disables MIME sniffing and forces browser to use the type given in Content-Type. X-Download-Options The X-Download-Options HTTP header indicates that the browser (Internet Explorer) should not display the option to "Open" a file that has been downloaded from an application, to prevent phishing attacks as the file
otherwise would gain access to execute in the context of the application. (Note: related MS Edge bug). X-Frame-Options (XFO) Indicates whether a browser should be allowed to render a page in a <frame>, <iframe>, <embed> or <object>. X-Permitted-Cross-Domain-Policies Specifies if a cross-domain policy file (crossdomain.xml) is allowed. The file may define a policy to grant clients, such as Adobe's Flash...
...) Indicates whether a browser should be allowed to render a page in a <frame>, <iframe>, <embed> or <object>. X-Permitted-Cross-Domain-Policies Specifies if a cross-domain policy file (crossdomain.xml) is allowed. The file may define a policy to grant clients, such as Adobe's Flash Player, Adobe Acrobat, Microsoft Silverlight, or Apache Flex, permission to handle data across domains that would
otherwise be restricted due to the Same-Origin Policy. See the Cross-domain Policy File Specification for more information. X-Powered-By May be set by hosting environments or other frameworks and contains information about them while not providing any usefulness to the application or its visitors. Unset this header to avoid exposing potential vulnerabilities. X-XSS-Protection Enables cross-site scripti...
Expressions and operators - JavaScript
r, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table. Logical operators Operator Usage Description Logical AND (&&) expr1 && expr2 Returns expr1 if it can be converted to false;
otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true;
otherwise, returns false. Logical OR (||) expr1 || expr2 Returns expr1 if it can be converted to true;
otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false. Logical NOT (!) !expr Returns ...
... Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined. The following code shows examples of the && (logical AND) operator. ...
... For example, var mystring = 'alpha'; mystring += 'bet'; // evaluates to "alphabet" and assigns this value to mystring. Conditional (ternary) operator The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is: condition ? val1 : val2 If condition is true, the operator has the value of val1.
Otherwise it has the value of val2. You can use the conditional operator anywhere you would use a standard operator. For example, var status = (age >= 18) ? 'adult' : 'minor'; This statement assigns the value "adult" to the variable status if age is eighteen or more.
Otherwise, it assigns the value "minor" to status. Comma operator The comma operator (,) simply evaluates both of its operands and retu...
Less than (<) - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x < y Description The operands are compared using the Abstract Relational Comparison algorithm, which is roughly summarised below: First, objects are converted to primitives using Symbol.ToPrimitive. If both values are strings, they are compared as strings, based on the values of the Unicode code points they contain. ...
...github.com/mdn/interactive-examples and send us a pull request. Syntax x < y Description The operands are compared using the Abstract Relational Comparison algorithm, which is roughly summarised below: First, objects are converted to primitives using Symbol.ToPrimitive. If both values are strings, they are compared as strings, based on the values of the Unicode code points they contain. ...
...n.
Otherwise JavaScript attempts to convert non-numeric types to numeric values: Boolean values true and false are converted to 1 and 0 respectively. null is converted to 0. undefined is converted to NaN. Strings are converted based on the values they contain, and are converted as NaN if they do not contain numeric values. If either value is NaN, the operator returns false.
Otherwise the values are compared as numeric values. Examples String to string comparison console.log("a" < "b"); // true console.log("a" < "a"); // false console.log("a" < "3"); // false String to number comparison console.log("5" < 3); // false console.log("3" < 3); // false console.log("3" < 5); // true console.log("hello" < 5); // false consol...
Web video codec guide - Web media technologies
lost quality; other times, the loss of quality is unacceptable and it's necessary to accept a codec configuration that results in a correspondingly larger file. Effect of source video format on encoded output The degree to which the format of the source video will affect the output varies depending on the codec and how it works. If the codec converts the media into an internal pixel format, or
otherwise represents the image using a means other than simple pixels, the format of the original image doesn't make any difference. However, things such as frame rate and, obviously, resolution will always have an impact on the output size of the media. Additionally, all codecs have their strengths and weaknesses. Some have trouble with specific kinds of shapes and patterns, or aren't good at replicating...
...cts are side effects of a lossy encoding process in which the lost or rearranged data results in visibly negative effects. Once an artifact has appeared, it may linger for a while, because of how video is displayed. Each frame of video is presented by applying a set of changes to the currently-visible frame. This means that any errors or artifacts will compound over time, resulting in glitches or
otherwise strange or unexpected deviations in the image that linger for a time. To resolve this, and to improve seek time through the video data, periodic key frames (also known as intra-frames or i-frames) are placed into the video file. The key frames are full frames, which are used to repair any damage or artifact residue that's currently visible. Aliasing Aliasing is a general term for anything that...
...rs. Aside from the lack of Safari support, VP9 is a good choice if you are able to use a WebM container and are able to provide a fallback video in a format such as AVC or HEVC for Safari users. This is especially true if you wish to use an open codec rather than a proprietary one. If you can't provide a fallback and aren't willing to sacrifice Safari compatibility, VP9 in WebM is a good option.
Otherwise, you should probably consider a different codec. Supported bit rates Arbitrary; no maximum unless level-based limitations are enforced Supported frame rates Arbitrary Compression Lossy DCT-based algorithm Supported frame sizes Up to 65,536 x 65,536 pixels Supported color modes Profile Color depths ...
The "codecs" parameter in common media types - Web media technologies
tier (seq_tier is 1), this character is the letter H. The High tier is only available for level 4.0 and up. DD The two-digit component bit depth. This value must be one of 8, 10, or 12; which values are valid varies depending on the profile and other properties. M The one-digit monochrome flag; if this is 0, the video includes the U and V planes in addition to the Y plane.
Otherwise, the video data is entirely in the Y plane and is therefore monochromatic. See YUV in Digital video concepts for details on how the YUV color system works. The default value is 0 (not monochrome). CCC CCC indicates the chroma subsampling as three digits. The first digit is subsampling_x, the second is subsampling_y. If both of those are 1, the third is the value of chroma_sample_...
...o data is entirely in the Y plane and is therefore monochromatic. See YUV in Digital video concepts for details on how the YUV color system works. The default value is 0 (not monochrome). CCC CCC indicates the chroma subsampling as three digits. The first digit is subsampling_x, the second is subsampling_y. If both of those are 1, the third is the value of chroma_sample_position;
otherwise, the third digit is always 0. This, combined with the M component, can be used to construct the chroma subsampling format: Determining the chroma subsampling format subsampling_x subsampling_y Monochrome flag Chroma subsampling format 0 0 0 YUV 4:4:4 1 0 0 ...
...Profile A subset of the Scalable High Profile designed mainly for real-time communticions. 56 04 Scalable High Intra Profile Primarily useful only for production applications, this profile supports only all-intra usage. 56 20 Stereo High Profile The Stereo High Profile provides stereoscopic video using two renderings of the scene (left eye and right eye).
Otherwise, provides the same features as the High profile. 80 00 Multiview High Profile Supports two or more views using both temporal and MVC inter-view prediction. Does not support field pictures or macroblock-adaptive frame-field coding. 76 00 Multiview Depth High Profile Based on the High Profile, to which the main substream must adhere. The remaining substreams mu...
in2 - SVG: Scalable Vector Graphics
the in attribute. Three elements use this attribute: <feBlend>, <feComposite> and <feDisplacementMap>. feBlend For <feBlend>, in2 defines the second input image to the blending operation. ...
...ter primitive,
otherwise result of previous filter primitive Animatable Yes feComposite For <feComposite>, in2 defines the second input image to the compositing operation. Value SourceGraphic | SourceAlpha | BackgroundImage | BackgroundAlpha | FillPaint | StrokePaint | <filter-primitive-reference> Default value SourceGraphic for first filter primitive,
otherwise result of previous filter primitive Animatable Yes feDisplacementMap For <feDisplacementMap>, in2 defines the second input image, which is used to displace the pixels in the image defined in the in attribute. Value SourceGraphic | SourceAlpha | BackgroundImage | BackgroundAlpha | FillPaint | StrokePaint | <filter-primitive-reference> Default value Sour...
... Animatable Yes feDisplacementMap For <feDisplacementMap>, in2 defines the second input image, which is used to displace the pixels in the image defined in the in attribute. Value SourceGraphic | SourceAlpha | BackgroundImage | BackgroundAlpha | FillPaint | StrokePaint | <filter-primitive-reference> Default value SourceGraphic for first filter primitive,
otherwise result of previous filter primitive Animatable Yes Specifications Specification Status Comment Filter Effects Module Level 1The definition of 'in2 for <feDisplacementMap>' in that specification. Working Draft No change Filter Effects Module Level 1The definition of 'in2 for <feComposite>' in that specification. Working Draft No ...
Index - XSLT: Extensible Stylesheet Language Transformations
version) element is not supported. 32 <xsl:for-each> Element, Reference, XSLT, for, for-each The <xsl:for-each> element selects a set of nodes and processes each of them in the same way. It is often used to iterate through a set of nodes or to change the current node. If one or more <xsl:sort> elements appear as the children of this element, sorting occurs before processing.
Otherwise, nodes are processed in document order. 33 <xsl:if> Element, Reference, XSLT, if The <xsl:if> element contains a test attribute and a template. If the test evaluates to true, the template is processed. In this it is similar to an if statement in other languages. To achieve the functionality of an if-then-else statement, however, use the <xsl:choose> element with one <xsl:when...
...cessed in document order. 33 <xsl:if> Element, Reference, XSLT, if The <xsl:if> element contains a test attribute and a template. If the test evaluates to true, the template is processed. In this it is similar to an if statement in other languages. To achieve the functionality of an if-then-else statement, however, use the <xsl:choose> element with one <xsl:when> and one <xsl:
otherwise> children. 34 <xsl:import> Element, Reference, XSLT, import The <xsl:import> element is a top-level element that serves to import the contents of one stylesheet into another stylesheet. Generally speaking, the contents of the imported stylesheet have a lower import precedence than that of the importing stylesheet. This is in contrast to <xsl:include> where the contents of the...
...uld simply be copied as-is to the result tree) from being misunderstood by the processor, it is assigned a temporary namespace which is appropriately re-converted back to the XSLT namespace in the output tree. 39 <xsl:number> Element, Number, Reference, XSLT The <xsl:number> element counts things sequentially. It can also be used to quickly format a number. 40 <xsl:
otherwise> Element, Reference, XSLT,
otherwise The <xsl:
otherwise> element is used to define the action that should be taken when none of the <xsl:when> conditions apply. It is similar to the else or default case in other programing languages. 41 <xsl:output> Element, Reference, XSLT, output The <xsl:output> element controls the characteristics of the output document. To func...
Window: deviceproximity event - Archive of obsolete content
Related Events userproximity ...
... Property Type Description value Read only Double (float) The measured proximity of the distant device (distance in centimetres). min Read only Double (float) The minimum value in the range the sensor detects (if available, 0
otherwise). max Read only Double (float) The maximum value in the range the sensor detects (if available, 0
otherwise). Related Events userproximity ...
url - Archive of obsolete content
Parameters source : string A string to be converted into a URL. If source is not a valid URI, this constructor will throw an exception. ...
...eters uri : string A string to be parsed as Data URL. If is not a valid URI, this constructor will throw an exception. Functions toFilename(url) Attempts to convert the given URL to a native file path. This function will automatically attempt to resolve non-file protocols, such as the resource: protocol, to their place on the file system. An exception is raised if the URL can't be converted;
otherwise, the native file path is returned as a string. Parameters url : string The URL, as a string, to be converted. Returns string : The converted native file path as a string. fromFilename(path) Converts the given native file path to a file: URL. Parameters path : string The native file path, as a string, to be converted. Returns string : The converted URL as a string. isValidURI(uri) Ch...
content/mod - Archive of obsolete content
l is returned. For example target can be a content window itself in which case it's will be returned back. Parameters target : object The object for which we want to obtain the window represented or contained. If a nsIDOMWindow is given, it works as an identify function, returns target itself. Returns nsIDOMWindow|null : The window represented or contained by the target, if any. Returns null
otherwise. attach(modification, target) Function applies given modification to a given target representing a content to be modified. Parameters modification : object The modification we want to apply to the target target : object Target is a value that representing content to be modified. It is valid only when getTargetWindow(target) returns nsIDOMWindow of content it represents. detach(modificatio...
...ed. Parameters modification : object The modification we want to apply to the target target : object Target is a value that representing content to be modified. It is valid only when getTargetWindow(target) returns nsIDOMWindow of content it represents. detach(modification, target) Function removes attached modification. If target is specified modification is removed from that target only,
otherwise modification is removed from all the targets it's being attached to. Parameters modification : object The modification we want to remove from the target target : object Target is a value that representing content to be modified. It is valid only when getTargetWindow(target) returns nsIDOMWindow of content it represents. If target is not provided modification is removed from all targets it's ...
platform/xpcom - Archive of obsolete content
tered, this function does nothing. By default, factories and services are unregistered automatically when the add-on that registered them is unloaded. Parameters factory : object The factory or service to unregister. isRegistered(factory) Find out whether a factory or service is registered. Parameters factory : object Returns boolean : True if the factory or service is registered, false
otherwise. autoRegister(path) Register a component (.manifest) file or all component files in a directory. See nsIComponentRegistrar.autoRegister() for details. Parameters path : string Path to a component file to be registered or a directory containing component files to be registered. factoryByID(id) Given a class ID, this function returns the associated factory or service. If the factory or servi...
...y XPCOM, so usually you don't need to call it yourself. It is passed an interface identifier and searches for the identifier in the interfaces property of: this object any of this object's ancestors any classes in the implements array property of the instance (for example, any classes added to this object via the implements option defined in heritage). If it finds a match, it returns this,
otherwise it throws Components.results.NS_ERROR_NO_INTERFACE. Parameters interface : iid The interface to ask for. This is typically given as a property of the Components.interfaces object. Returns object : The object itself(this). Properties interfaces The set of interfaces supported by this class. Unknown sets this to nsISupports. Factory Use this class to register an XPCOM factory. To register...
system/xul-app - Archive of obsolete content
n is running. With the exception of ids, each of these properties exposes the attribute of the same name on the nsIXULAppInfo interface. For more information, see the MDN documentation. Globals Functions is(name) Checks whether the host application is the given application. Parameters name : string A host application name. Returns boolean : True if the host application is name and false
otherwise. isOneOf(names) Checks whether the host application is one of the given applications. Parameters names : array An array of host application names. Returns boolean : True if the host application is one of the names and false
otherwise. versionInRange(version, lowInclusive, highExclusive) Compares a given version to a version range. See the MDN documentation for details on version comparis...
...he MDN documentation for details on version comparisons. Parameters version : string The version to compare. lowInclusive : string The lower bound of the version range to compare. The range includes this bound. highExclusive : string The upper bound of the version range to compare. The range does not include this bound. Returns boolean : True if version falls in the given range and false
otherwise. Properties ID The GUID of the host application. For example, for Firefox this value is "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}". name The host application name. The possible values here are: "Firefox" "Fennec" "Mozilla" "SeaMonkey" "Sunbird" "Thunderbird" "Firefox"and"Fennec"` are the most commonly used values. version The host application version. platformVersion The Gecko/XU...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
accessed by other modules. These can be IDL files describing XPCOM interfaces, which are used to generate normal C++ header files for inclusion in your source files. They can also be normal C++ header files that are to be used directly by other modules. The easiest way to accomplish the latter is to use inline implementations for all methods so you don't have any additional linking dependencies.
Otherwise you will have to link statically to your module if you use these public headers in other modules. Personally I would discourage this practice (among other things, static linking means the same code gets loaded more than once into memory, and the code won't be available from JavaScript or other non-C++ languages) and encourage the use of XPCOM wherever possible. The makefile in the public/ ...
...ME = myextension EXPORTS = \ myHeader.h \ $(NULL) XPIDLSRCS = \ myIFirstComponent.idl \ myISecondComponent.idl \ $(NULL) include $(topsrcdir)/config/rules.mk XPIDL_MODULE is the name of the generated XPT file that contains type information about your IDL interfaces. If you have multiple modules, make absolutely sure that you use a different value for XPIDL_MODULE for each one.
Otherwise the first module's XPT file will be overwritten by the second and you'll get NS_ERROR_XPC_BAD_IID errors when you try to access its IDL interfaces from your code. The files under EXPORTS are copied directly to the /mozilla/$(MOZ_OBJDIR)/dist/include/ directory and are thus accessible from other modules (the value of MOZ_OBJDIR is defined in /mozilla/.mozconfig). XPIDLSRCS are run through the IDL ...
How to convert an overlay extension to restartless - Archive of obsolete content
rk. If not, a file:// URI might be fine for you. Restartless add-ons can easily get a URI for their install location on startup, so you should look into what you can do with that. Step 3: No more nsIFile access for files internal to your bundle For an extractionless extension, access to files internal to your bundle will not be possible using the nsIFile interface. If you need to read data, or
otherwise access files within your bundle, there are two options. The first is to use the nsIZipReader interface which permits continuing to use nsIInputStreams, etc. The second is to re-code to use XMLHttpRequest. A file:// URI to the install location, or .xpi file, is available in installPath property of the bootstrap data structure passed to the startup(), shutdown(), install(), and uninstall() functio...
...r to do so reliably. Errors can erratically happen on next load of the same file in certain instances. (at minimum, when strings are added/removed) The apparently accepted solution to reliably load new versions is to always create bundles with a unique URL so as to bypass the cache. This is accomplished by passing a random number in a parameter after a '?'. (this random ID is
otherwise ignored) The loaded string bundle is still cached on startup and should still be cleared out of the cache on addon shutdown. This just bypasses the built-in cache for repeated loads of the same path so that a newly installed update loads cleanly. */ return Services.strings.createBundle(path + "?" + Math.random()); } Just do strings.GetStringFromName(stringID) as you normally w...
Intercepting Page Loads - Archive of obsolete content
e user sees anything in the tab. HTTP Observers Another common way of detecting and intercepting loads is using HTTP observer topics. This is how the Tamper Data extension and others do it. HTTP notifications are fired for all HTTP requests originating from Firefox. They are window-independent, so it is better to keep your observer code in non-chrome objects (your XPCOM service or jsm module).
Otherwise you have to make sure to avoid duplicated work if you have 2 or more windows open. There are 2 HTTP topics you can listen to, as specified in the Observer Notifications page: Topic Description http-on-modify-request Called as an http request is made. The channel is available to allow you to modify headers and such. http-on-examine-response Called after a resp...
...arsed into DOM tree, so this is not the best approach for the typical Greasemonkey-style extensions. Notes on usage: Efficiency is very important when adding HTTP observers. Remember that your observe method will be called for every HTTP request made by Firefox, usually several dozen per page visit. In the previous example, one of the first things we do is check if the URL is of interest to us,
otherwise we let it go. Avoid heavy, time-consuming operations, or the user's browsing experience will become exasperating. . You have to take into account that a page load may involve several HTTP requests, specially when redirects are involved. If you enter gmail.com in your browser, you will probably be redirected a few times before reaching the page that actually displays any content. All of these "h...
Index - Archive of obsolete content
945 Template Builder Interface XUL, XUL_Template_Guide When inserting an element into a XUL document, the element is checked to see if it has a datasources attribute. If so, a template builder will be created for the element and attached to the element. If the element is a <tree> element and has the flags attribute set to "dont-build-content", a tree builder will be created.
Otherwise, a content builder will be created. Both types of builder share much of the same code except for how they generate output to be displayed. Both types of builders implement the nsIXULTemplateBuilder interface, while the tree builder also implements the nsIXULTreeBuilder interface.</tree> 946 Template Logging Debugging problems with a template can be difficult as many problems...
... vbox XUL Elements, XUL Reference A container element which can contain any number of child elements. This is equivalent to the box element, except it defaults to vertical orientation. 1215 where XUL Elements, XUL Reference Indicate a condition that must match for a template result to be used. If the condition is true, the corresponding action body is generated;
otherwise the result is ignored and no content is generated. 1216 window XUL Elements, XUL Reference Describes the structure of a top-level window. It is the root node of a XUL document. It is by default a horizontally oriented box. As it is a box, all box attributes can be used. By default, the window will have a platform-specific frame around it. 1217 wizard XUL Elemen...
Template Builder Interface - Archive of obsolete content
<< PreviousNext >> When inserting an element into a XUL document, the element is checked to see if it has a datasources attribute. If so, a template builder will be created for the element and attached to the element. If the element is a <tree> element and has the flags attribute set to "dont-build-content", a tree builder will be created.
Otherwise, a content builder will be created. Both types of builder share much of the same code except for how they generate output to be displayed. Both types of builders implement the nsIXULTemplateBuilder interface, while the tree builder also implements the nsIXULTreeBuilder interface. The builder associated with an element is accessible via the element's 'builder' property both for content builders and for tree builders. An element that does n...
...mplate after a refresh call, although there may situtations where this will be necessary. If you do plan on determining the datasources dynamically, it is common to start with an empty datasource using the special URI 'rdf:null'. <tree datasources="rdf:null" ref="http://www.xulplanet.com/rdf/myphotos"> This will create a composite datasource with no datasources in it. This syntax is necessary as
otherwise you wouldn't be able to specify a value for the datasources attribute, and a template builder would not be attached to the element. In a chrome context, the datasource 'rdf:local-store' is always included even if you don't specify it. This is something to watch out for if you are going to be manipulating the composite datasource. One more note: the datasources attribute may use either absolute or...
Code Samples - Archive of obsolete content
Launch a file on your computer To launch a file on your computer, use code like this. Change the first line to specify the file that you want to launch. You can launch an executable file or some other file that your operating system knows how to open. Note: On operating systems that use backslash characters, double each backslash character. ...
...vice;1"] .getService(Components.interfaces.nsIExternalProtocolService) .loadUrl(uri) Compose an e-mail To compose an e-mail, use the same code as in the section Open a web page above. Change the first line to specify: const url = "mailto://" Open an application window To open one of the application's windows, use code like this. If the window already exists, this code just focusses it. ...
menu - Archive of obsolete content
des an assigned key set in the key attribute. This attribute does not apply to menus directly on the menubar. accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. allowevents Type: boolean If true, events are passed to children of the element.
Otherwise, events are passed to the element only. crop Type: one of the values below If the label of the element is too big to fit in its given space, the text will be cropped on the side specified by the crop attribute. An ellipsis will be used in place of the cropped text. If the box direction is reversed, the cropping is reversed. start ...
...o true when the menu is open. The open attribute is not present if the menu is closed. sizetopopup Type: one of the values below Indicates how the menu width and the menupopup width are determined. If the sizetopopup attribute is left out or set to none, the menu will be its preferred width and the popup may extend outside of this width, unaffected by the maximum width of the menu itself.
Otherwise, the menu will size itself to at least the size of the popup. If the menu has a maximum width, the popup will also be this width. none The width of the popup will not be constrained to the size of the menu. pref The preferred width of the menu label or button will be the size needed for the popup contents. This is the default value for menulists. always Both the preferred and mini...
panel - Archive of obsolete content
he label on the titlebar. left Type: integer Overrides the horizontal position of the popup specified by the showPopup method. level Type: one of the values below Specifies whether the panel appears on top of all windows, or just on top of the window the panel is in. If this attribute is not set, the popup window level depends on the platform. On Linux, the default value is top,
otherwise, the default value is parent. If a panel has one or more text fields, this attribute should not be set,
otherwise IME or on-screen keyboard popups will appear incorrectly. For these reasons, you should avoid setting the level if not needed. top The panel is shown in front of all other normal windows, including those of other applications. parent The panel is shown just above the windo...
...is for a panel that provides a tree for an autocomplete element. autocomplete-richlistbox Specify this for a panel that provides a richlistbox for an autocomplete element. arrow Specify this for a panel that provides an arrow pointing at its anchor. drag Specify this for a panel that's being used as a drag image for a drag and drop operation.
Otherwise leave this attribute out. Note: The arrow will draw as long as the panel doesn't overlap the anchor. If they overlap, the anchor won't be drawn. The panel may not appear on the side of the anchor that you requested in which case the arrow will automatically adjust. Properties accessibleType Type: integer A value indicating the type of accessibility object for the el...
toolbar - Archive of obsolete content
bar. Methods insertItem( id, beforeNode, wrapper, beforePermanent ) Not in SeaMonkey 1.x Return type: element Add an item with the given id to the toolbar. The new item is added just before the item given by the second argument. If the second argument is null, but the beforePermanent argument is true, the item is added to the beginning of the toolbar before the first permanent item.
Otherwise, if the beforePermanent argument is false, the new item is added to the end of the toolbar. The third argument can be used to wrap the new item in another element. Usually, the last argument will be null as it is mainly for the use of the customize dialog. The id should match an element in the toolbar's toolbarpalette. Some special ids may also be used to create special spacing items: separa...
... Related Elements toolbarbutton, toolbargrippy, toolbaritem, toolbarpalette, toolbarseparator, toolbarset, toolbarspacer, toolbarspring, toolbox Interfaces nsIAccessibleProvider ...
where - Archive of obsolete content
For more information, see Where Elements. Attributes ignorecase, multiple, negate, rel, subject, value Examples (example needed) Attributes ignorecase Type: boolean Set to true to indicate that the case does not matter when making comparisons. ...
...e used. If the condition is true, the corresponding action body is generated;
otherwise the result is ignored and no content is generated. For more information, see Where Elements. Attributes ignorecase, multiple, negate, rel, subject, value Examples (example needed) Attributes ignorecase Type: boolean Set to true to indicate that the case does not matter when making comparisons.
Otherwise, the default value is false, to indicate that the value should match with the same case. multiple Type: boolean Set to true to indicate that the value contains multiple values separated by commas. Any of the values may match.
Otherwise, the entire value string is compared. negate Type: boolean Set to true to indicate that the comparison should be reversed. The where clause match...
Mozilla release FAQ - Archive of obsolete content
es (first as milestones, and more recently as versioned releases) have been made. As of the time of this update, Mozilla 1.0 Release Candicate 2 is the most recent release. What is the current version of Mozilla? Mozilla is continually available via CVS, and also is occasionally released as versioned numbers. If built from CVS, the date of the CVS checkout is the best way to refer to the version,
otherwise use the release number. Older versions used milestone numbers (e.g. the Milestone 7 release was known as M7). What is the relation between Mozilla versions and Netscape versions? The current arrangement between Netscape (AOL) and the Mozilla project is that Mozilla develops its own releases, and when Netscape (AOL) is preparing to make a release, it takes the current version of Mozilla, makes mod...
...s would make web servers more complex, slower, and likely hurt the transfer time that this proposal is attempting to save. Also, progressive display of the webpage would be completely gone with this idea. For these reasons, this is generally considered a bad idea. I'd like to port Mozilla to XXXOS. Any advice? If you're targeting a relatively recent Unix, you probably will have very few problems.
Otherwise, the more Unixlike the target system is, the easier your port will go. I would suggest that before you devote much time and effort to your port, you consider: How many users the OS has that are likely to use Mozilla Does the OS support multitasking well enough for Mozilla Does the OS have a sufficiently evolved GUI for Mozilla to work Does the OS have sufficient networking support for Mo...
Security Controls - Archive of obsolete content
First, security weaknesses in the system need to be resolved. ...
...nality and usability that users require. Another fundamental principle with security controls is using multiple layers of security--defense in depth. For example, sensitive data on a server may be protected from external attack by several controls, including a network-based firewall, a host-based firewall, and OS patching. The motivation for having multiple layers is that if one layer fails or
otherwise cannot counteract a certain threat, other layers might prevent the threat from successfully breaching the system. A combination of network-based and host-based controls is generally most effective at providing consistent protection. Original Document Information Author(s): U.S. Department of Commerce Title: Federal Information Processing Standard Publication 200, Minimum Security Requireme...
What is accessibility? - Learn web development
n public buildings generally have wheelchair ramps or elevators), it is also not right to exclude someone from a website because they have a visual impairment. We are all different, but we are all human, and therefore have the same human rights. Accessibility is the right thing to do. Providing accessible sites is part of the law in some countries, which can open up some significant markets that
otherwise would not be able to use your services or buy your products. Building accessible sites benefit everyone: Semantic HTML, which improves accessibility, also improves SEO, making your site more findable. Caring about accessibility demonstrates good ethics and morals, which improves your public image. Other good practices that improve accessibility also make your site more usable by other group...
...ganization estimates that "285 million people are estimated to be visually impaired worldwide: 39 million are blind and 246 have low vision." (see Visual impairment and blindness). That's a large and significant population of users to just miss out on because your site isn't coded properly -- almost the same size as the population of the United States of America. People with hearing impairments
Otherwise known as people with auditory impairments or deaf people, this group of people has either low hearing levels or no hearing at all. Hearing-impaired people do use ATs (see Assistive Devices for People with Hearing, Voice, Speech, or Language Disorders), but there are not really special ATs specific for computer/web use. There are, however, specific techniques for providing textual alternatives to...
Cascade and inheritance - Learn web development
these values. inherit Sets the property value applied to a selected element to be the same as that of its parent element. Effectively, this "turns on inheritance". initial Sets the property value applied to a selected element to the initial value of that property. unset Resets the property to its natural value, which means that if the property is naturally inherited it acts like inherit,
otherwise it acts like initial. Note: There is also a newer value, revert, which has limited browser support. Note: See Origin of CSS declarations in Introducing the CSS Cascade for more information on each of these and how they work. We can look at a list of links and explore how the universal values work. The live example below allows you to play with the CSS and see what happens when you make ch...
...y level. For example, a million class selectors combined would not be able to overwrite the rules of one id selector. A more accurate way to evaluate specificity would be to score the specificity levels individually starting from highest and moving on to lowest when necessary. Only when there is a tie between selector scores within a specificity level do you need to evaluate the next level down;
otherwise, you can disregard the lower specificity level selectors since they can never overwrite the higher specificity levels. !important There is a special piece of CSS that you can use to overrule all of the above calculations, however you should be very careful with using it -- !important. This is used to make a particular property and value the most specific thing, thus overriding the normal rules...
Overflowing content - Learn web development
CSS may help you create boxes that scale better with varying amounts of content. As with scroll, you get a scrollbar in the scrolling dimension whether or not there is enough content to cause a scrollbar. Note: You can specify x and y scrolling using the overflow property, passing two values. If two keywords are specified, the first applies to overflow-x and the second applies to overflow-y.
Otherwise, both overflow-x and overflow-y are set to the same value. For example, overflow: scroll hidden would set overflow-x to scroll and overflow-y to hidden. If you only want scrollbars to appear when there is more content than can fit in the box, use overflow: auto. This allows the browser to determine if it should display scrollbars. In the example below, remove content until it fits into the box...
...n order to create a consistent scrolling experience. Unwanted overflow in web design Modern layout methods (described in CSS layout) manage overflow. They largely work without assumptions or dependencies for how much content there will be on a web page. This has not always been the norm. In the past, some sites were built with fixed-height containers to align bottoms of boxes. These boxes may
otherwise have no relationship to each other. This was fragile. In a legacy application, you may encounter a box where content is overlaying other content on the page. Now you can recognize that this happens with overflow. Ideally, you will refactor the layout to not rely on fixed-height containers. When developing a site, always keep overflow in mind. Test designs with large and small amounts of content.
Client-side form validation - Learn web development
lue is not in the required syntax (when type is email or url), or false if the syntax is correct. If true, the element matches the :invalid CSS pseudo-class. valid: Returns true if the element meets all its validation constraints, and is therefore considered to be valid, or false if it fails any constraint. If true, the element matches the :valid CSS pseudo-class; the :invalid CSS pseudo-class
otherwise. valueMissing: Returns true if the element has a required attribute, but no value, or false
otherwise. If true, the element matches the :invalid CSS pseudo-class. willValidate: Returns true if the element will be validated when the form is submitted; false
otherwise. The Constraint Validation API also makes the following methods available on the above elements. checkValidity(): Retu...
...If the element is invalid, this method also fires an invalid event on the element. setCustomValidity(message): Adds a custom error message to the element; if you set a custom error message, the element is considered to be invalid, and the specified error is displayed. ...
Mozilla splash page - Learn web development
ements -- each one linking to an interesting Mozilla-related page. To complete this section you'll need to insert an <img> element inside each one containing appropriate src, alt, srcset and sizes attributes. In each case (except one -- which one is inherently responsive?) we want the browser to serve the 120px wide version when the viewport width is 500px wide or less, or the 400px wide version
otherwise. Make sure you match the correct images with the correct links! Note: To properly test the srcset/sizes examples, you'll need to upload your site to a server (using Github pages is an easy and free solution), then from there you can test whether they are working properly using browser developer tools such as the Firefox Network Monitor. An art directed red panda Inside the <div> with the cl...
... Github pages is an easy and free solution), then from there you can test whether they are working properly using browser developer tools such as the Firefox Network Monitor. An art directed red panda Inside the <div> with the class of red-panda, we want to insert a <picture> element that serves the small portrait panda image if the viewport is 600px wide or less, and the large landscape image
otherwise. Example The following screenshots show what the splash page should look like after being correctly marked up, on a wide and narrow screen display. Assessment or further help If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Glitch is probably better for this example, as it al...
Graceful asynchronous programming with Promises - Learn web development
o .then() creates a new promise. This is very useful; because the blob() method also returns a promise, we can handle the Blob object it returns on fulfillment by invoking the .then() method of the second promise. Because we want to do something a bit more complex to the blob than just run a single method on it and return the result, we'll need to wrap the function body in curly braces this time (
otherwise it'll throw an error). Add the following to the end of your code: let promise3 = promise2.then(myBlob => { }) Now let's fill in the body of the executor function. Add the following lines inside the curly braces: let objectURL = URL.createObjectURL(myBlob); let image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); Here we are running the...
... for "${url}" finished.`); }); } This logs a simple message to the console to tell us when each fetch attempt has finished. Note: then()/catch()/finally() is the async equivalent to try/catch/finally in sync code. Building your own custom promises The good news is that, in a way, you've already built your own promises. When you've chained multiple promises together with .then() blocks, or
otherwise combined them to create custom functionality, you are already making your own custom async promise-based functions. Take our fetchAndDecode() function from the previous examples, for example. Combining different promise-based APIs together to create custom functionality is by far the most common way you'll do custom things with promises, and shows the flexibility and power of basing most modern ...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
oLocaleTimeString(); document.getElementById('demo').textContent = time; } const createClock = setInterval(displayTime, 1000); Just like setTimeout(), setInterval() returns an identifying value you can use later when you need to clear the interval. Clearing intervals setInterval() keeps running a task forever, unless you do something about it. You'll probably want a way to stop such tasks,
otherwise you may end up getting errors when the browser can't complete any further versions of the task, or if the animation being handled by the task has finished. You can do this the same way you stop timeouts -- by passing the identifier returned by the setInterval() call to the clearInterval() function: const myInterval = setInterval(myFunction, 2000); clearInterval(myInterval); Active learning: Cr...
... your display values if the amount is less than 10, so it looks more like a traditional clock/watch. To pause the stopwatch, you'll want to clear the interval. To reset it, you'll want to set the counter back to 0, clear the interval, and then immediately update the display. You probably ought to disable the start button after pressing it once, and enable it again after you've stopped/reset it.
Otherwise multiple presses of the start button will apply multiple setInterval()s to the clock, leading to wrong behavior. Note: If you get stuck, you can find our version here (see the source code also). Things to keep in mind about setTimeout() and setInterval() There are a few things to keep in mind when working with setTimeout() and setInterval(). Let's review these now. Recursive timeouts Ther...
Drawing graphics - Learn web development
on <canvas> elements using JavaScript. Graphics on the Web As we talked about in our HTML Multimedia and embedding module, the Web was originally just text, which was very boring, so images were introduced -- first via the <img> element and later via CSS properties such as background-image, and SVG. This however was still not enough. While you could use CSS and JavaScript to animate (and
otherwise manipulate) SVG vector images -- as they are represented by markup -- there was still no way to do the same for bitmap images, and the tools available were rather limited. The Web still had no way to effectively create animations, games, 3D scenes, and other requirements commonly handled by lower level languages such as C++ or Java. The situation started to improve when browsers began to support...
...t object using the Image() constructor. The returned object is the same type as that which is returned when you grab a reference to an existing <img> element). We then set its src attribute to equal our Firefox logo image. At this point, the browser starts loading the image. We could now try to embed the image using drawImage(), but we need to make sure the image file has been loaded first,
otherwise the code will fail. We can achieve this using the onload event handler, which will only be invoked when the image has finished loading. Add the following block below the previous one: image.onload = function() { ctx.drawImage(image, 50, 50); } If you load your example in the browser now, you should see the image embeded in the canvas. But there's more! What if we want to display onl...
What is JavaScript? - Learn web development
then run the code that updates the text label. And much more! What is even more exciting however is the functionality built on top of the client-side JavaScript language. So-called Application Programming Interfaces (APIs) provide you with extra superpowers to use in your JavaScript code. APIs are ready-made sets of code building blocks that allow a developer to implement programs that would
otherwise be hard or impossible to implement. They do the same thing for programming that ready-made furniture kits do for home building -- it is much easier to take ready-cut panels and screw them together to make a bookshelf than it is to work out the design yourself, go and find the correct wood, cut all the panels to the right size and shape, find the correct-sized screws, and then put them together to...
...aced below. Note: If your example doesn't seem to work, go through the steps again and check that you did everything right. Did you save your local copy of the starting code as a .html file? Did you add your <script> element just before the </head> tag? Did you enter the JavaScript exactly as shown? JavaScript is case sensitive, and very fussy, so you need to enter the syntax exactly as shown,
otherwise it may not work. Note: You can see this version on GitHub as apply-javascript-internal.html (see it live too). External JavaScript This works great, but what if we wanted to put our JavaScript in an external file? Let's explore this now. First, create a new file in the same directory as your sample HTML file. Call it script.js -- make sure it has that .js filename extension, as that's ho...
Introduction to client-side frameworks - Learn web development
ic areas of software development. In the context of frameworks, DSLs are variations on JavaScript or HTML that make it easier to develop with that framework. Crucially, none of the frameworks require a developer to use a specific DSL, but they have almost all been designed with a specific DSL in mind. Choosing not to employ a framework's preferred DSL will mean you miss out on features that would
otherwise improve your developer experience. You should seriously consider the support matrix and DSLs of a framework when making a choice for any new project. Mismatched browser support can be a barrier to your users; mismatched DSL support can be a barrier to you and your teammates. Framework Browser support Preferred DSL Supported DSLs Angular IE9+ TypeScript HT...
...hey need to, but they are not dependent upon it. Static site generators take time to learn, just like any other tool, which can be a barrier to your development process. Static sites can have as few or as many unique pages as you want. Just as frameworks empower you to quickly write client-side JavaScript applications, static site generators allow you a way to quickly create HTML files you would
otherwise have written individually. Like frameworks, static site generators allow developers to write components that define common pieces of your web pages, and to compose those components together to create a final page. In the context of static site generators, these components are called templates. Web pages built by static site generators can even be home to framework applications: if you want one sp...
Accessible Toolkit Checklist
"Native" skin option in your software, then get all look and feel from current OS skin. The high contrast theme can be toggled dynamically with LeftAlt+LeftShift+printscreen Expose the SPI_GETSCREENREADER flag to XML/scripts so that apps can alter behavior Use system highlight color where possible for item selection, but never use that exact color in more than 1 place at a time,
otherwise screen reader will read everything with that color whenever highlight changes Pay attention to SPI_GETCARETWIDTH for the correct width of the caret Pay attention to 'route mouse pointer to default button' setting It's possible that the user wants mnemonics hidden except when the alt key is pressed. This can be supported through SPI_GETKEYBOARDCUES and SPI_GETMENUUNDERLINES ...
...kes do the right thing MSAA support (default state) Links Enter key activates link (thus default button no longer shows dark border when link is focused) MSAA support, including linked and traversed states, and accessible value that holds destination URL Text fields - single and multiple line It's probably best to use native widgets for these,
otherwise accessibility support will be quite difficult Tab should always focus the next item, not insert a tab, unless there's a really good reason and another way to navigate Always use system selection color,
otherwise screen reader won't read the text Make sure the caret is never blinking when focus is not in text field Handle standard editing keys, such as arrow keys, home, end...
Adding a new event
ge. All messages are defined by macro in "messages" section of BasicEvents.h. Define event class name You need to add an event class name in EventClassList.h. Use NS_EVENT_CLASS macro for adding it. The macro takes two arguments, aPrefix and aName. aPrefix defines prefix of event class name which should be Widget or Internal. Widget should be used if the event class is dispatched from widget.
Otherwise, i.e., the event class is just used for internal event class of a DOM event class, it should be Internal. aName defines its event class specific name and it must end with "Event" or "EventBase". The latter is used only for abstruct super event class whose instance will never be created. Please note that aName must not be same as other event classes even if aPrefix is different. I.e., defining b...
...} DoSomethingWith(internalEvent->mBar); aEvent->PreventDefault(); return NS_OK; } Implement DOM event class Generate DOM event implementation if it's possible If you're creating simple DOM event class, it might be generated automatically. If it's possible, you just need to add an entry to GENERATED_EVENTS_WEBIDL_FILES in dom/webidl/moz.build. Define and create DOM event class manually
Otherwise, you need to implement a DOM event class yourself. The best place to create FooEvent.h and FooEvent.cpp is in dom/events/.
Otherwise, you need to specify the path to the header file in dom/bindings/Bindings.conf. When you create a DOM event class, its name should be same as the name defined in its standard specification. And it should be in mozilla::dom namespace. For example, KeyboardEvent whic...
Adding a new CSS property
e to use. If the property's values can be expressed as a single value, or as a space-separated or comma-separated list of values that can be described by the VARIANT_* flags (also in nsCSSProps.h), you should use CSS_PROPERTY_PARSE_VALUE or CSS_PROPERTY_PARSE_VALUE_LIST, and set the appropriate VARIANT_* flags in the entry in nsCSSPropList.h (and maybe also CSS_PROPERTY_VALUE_LIST_USES_COMMAS).
Otherwise, set the variant entry in the nsCSSPropList entry to 0. If you need custom parsing code, this can be inserted at one of two different places: you can override the entire property value parsing by using CSS_PROPERTY_PARSE_FUNCTION, which is generally the right thing to do for shorthand properties. Or, preferably, you can still use CSS_PROPERTY_PARSE_VALUE or ..._VALUE_LIST and just override the...
...item, not for a whole list, as for properties like background-image or transform-timing-function.) If the property takes a list of keywords other than inherit/initial/etc., auto, none, or normal (which can be expressed using the VARIANT_* flags), you should use VARIANT_KEYWORD and add a keyword table to the nsCSSProps class. The name of this keyword table needs to go in the nsCSSPropList entry;
otherwise that keyword table should be null. If you need a keyword table, you should include auto, normal, or none (if needed) in that table rather than combining VARIANT_KEYWORD with VARIANT_AUTO, VARIANT_NORMAL, or VARIANT_NONE. If you add a shorthand property, you'll need to use the CSS_PROP_SHORTHAND macro. You'll need to use CSS_PROPERTY_PARSE_FUNCTION as described above; you can't use the other op...
Application cache implementation overview
lineCacheUpdate it self is the core of the update process. During initiation the update is first looking for an existing nsIApplicationCache object using nsIApplicationCacheService::GetActiveCache() with the manifest URL to load from as an argument. When found, this update is processing an "update" and this cache is used as a cache to satisfy each manifest item and the manifest it self load from.
Otherwise, this is "first download". Then creates a new nsIApplicationCache for the given manifest URL using nsIApplicationCacheService::CreateApplicationCache(). This new cache version is now pending to be activated after all following long and complicated download process passes. Until that it is not used for loading resources from. After these steps the update is in INITIALIZED state waiting to be sched...
...rocessNextURI self-invocation cycle is stopped. From now on ProcessNextURI can only be called from LoadCompleted() again. Note: the ProcessNextURI method early returns when state of the update is different then DOWNLOADING. On DOWNLOADING state LoadCompleted checks whether load of the item succeeded. If so, its marked as valid in the new cache version and ProcessNextURI() is called.
Otherwise, the update invokes onerror and 'finishes'. When ProcessNextURI discovers there are no more items to download it starts a "manifest check" implemented by nsManifestCheck. nsManifestCheck downloads the manifest from the server one more time and checks its content has not changed again. The results is passed to the original update via ManifestCheckCompleted method. ...
Debugging on Mac OS X
hich has security implications), it is recommended to debug with try builds or local builds. The differences are explained below. try Server Builds In most cases, developers needing to debug a build as close as possible to the production environment should use a try build. These builds enable Hardened Runtime and only differ from production builds in that they are not Notarized which should not
otherwise affect functionality, (other than the ability to easily launch the browser on macOS 10.15+ -- see quarantine note below). At this time, developers can obtain a Hardened Runtime build with the com.apple.security.get-task-allow entitlement allowed by submitting a try build and downloading the dmg generated by the "Rpk" shippable build job. A debugger can be attached to Firefox processes of these bu...
...dd "-P profilename", where profilename is the name of a profile you created previously. Repeat that to also add the argument "-no-remote". Also in the "Arguments" panel, you may want to add an environment variable MOZ_DEBUG_CHILD_PROCESS set to the value 1 to help with debugging e10s. Select "Build" from the left of the scheme editor window, and check that there is nothing listed under Targets (
otherwise it may cause problems when you try to run the executable for debugging since you will get build errors). Click "Close" to close the scheme editor. At this point you can run the application from Xcode, and when you pause or hit breakpoints it should show open the correct source file at the correct line. Setting up lldb lldb is the debugger XCode provides/uses. One important issue that the M...
How Mozilla determines MIME Types
r the MIME type given the content. This should allow reliable detection of all image types Mozilla supports. Checks whether the data is HTML by looking for some common HTML tags. The URI is handed to the ExternalHelperAppService for MIME type guessing If all else fails, the buffer (i.e. the first few bytes of the file) is searched for embedded nulls; if none are found, text/plain will be used,
otherwise application/octet-stream. 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 (co...
... Helper Applications A somewhat related issue are the helper applications. When loading an URI with a type that Mozilla can not handle, a helper app dialog shows up, and the displayed information comes from these sources: Ask the OS for a handler of the given <extension, MIME Type> pair. Note that the extension here comes from the Content-Disposition header if present, and from the URL itself
otherwise. This is where the listed "default application" comes from. The "data source" (that is, the list of helper applications) is searched for an entry with the MIME type of the URI. The data source is the mimeTypes.rdf file in the profile directory. If this fails, the data source is searched via the extension (Content-Disposition as above). If one of these lookups succeed, this is where the applicati...
How to implement a custom autocomplete search component
the browser's URL history (Firefox: 1.0+; SeaMonkey: 1.1+) form-history: Search the values that the user has entered into form fields. (Firefox: 1.0+; SeaMonkey: 2.0+) file: Search file names (Firefox: 2.0+; Thunderbird: 2.0+; SeaMonkey: 1.1+; GTK builds only). The component uses the autocompletesearchparam attribute or searchParam property to allow the developer to define the default directory
otherwise only paths beginning with / or ~/ will be autocompleted. Building your custom autocomplete search components Sometimes, you may want to build your own autocomplete source. To do so you need the following: Create an XPCOM component that implements the nsIAutoCompleteSearch interface. Make sure the contract ID of your XPCOM component follows the following form: "@mozilla.org/autocomplete/search...
...mponent in Javascript will step you through the process. Because creating an XPCOM component in order to build a custom autocomplete source can be enough to discourage some developers, below is an example JavaScript XPCOM component called "simple-autocomplete" that implements the necessary interfaces. Note: When copying the examples below, change the UUID that uniquely identifies the component,
otherwise you might have problems if your component gets installed along another component derived from those same examples. That can happen! So, get a UUID from http://www.famkruithof.net/uuid/uuidgen, for example, and paste it in. Basic example for Gecko 2.0 and up (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) This example is your first best try because: it has no specific logic (it just returns a dumm...
IME handling guide
like autocomplete. Additionally, IME may be used for handwriting systems or speech input systems on some platforms. If IME is available on focused elements, we call that state "enabled". If IME is not fully available(i.e., user cannot enable IME), we call this state "disabled". If IME is enabled but users use direct input mode (e.g., for inputting Latin characters), we call it "IME is closed".
Otherwise, we call it "IME is open". (FYI: "open" is also called "active" or "turned on". "closed" is also called "inactive" or "turned off") So, this document is useful when you're try to fix a bug for text input in Gecko. Composition string and clauses Typical Japanese IME can input two or more words into a composition string. When a user converts from Hiragana characters to Chinese characters the com...
...t First character rect of mText. When mText is empty string, this should be caret rect. mCaret::mOffset Always same as selection start offset even when selection isn't collappsed. mCaret::mRect Caret rect at mCaret::mOffset. If caret isn't actually exists, it's computed with a character rect at the offset. mTextRectArray::mStart If there is composition, mStart is same as mCompositionStart.
Otherwise, UINT32_MAX. mTextRectArray::mRects Each character rects of composition string. mEditorRect The rect of editor element. mozilla::ContentCacheInChild This exists only in remote processes. This is created as a member of PuppetWidget. When PuppetWidget receives notifications to IME from IMEContentObserver in the remote process, it makes this class modify its cached content. Then, this class d...
Widget Wrappers
a widget. There are 'group' wrappers which provide information about the widget across all windows, and 'single' wrappers which provide information about a specific instance in a specific window. Group wrapper Methods forWindow() A method to obtain a single window wrapper for a widget, in the window aWindow passed as the only argument. Properties All of a wrapper's properties are read-only unless
otherwise indicated. Attribute Description id the widget's ID type the type of widget (button, view, custom). For XUL-provided widgets, this is always 'custom' provider the provider type of the widget, id est one of PROVIDER_API or PROVIDER_XUL instances an array of all instances (single window wrappers) of the widget. This array is NOT live. ...
... Attribute Description id the widget's ID type the type of widget (button, view, custom). For XUL-provided widgets, this is always 'custom' provider the provider type of the widget, id est one of PROVIDER_API or PROVIDER_XUL node reference to the corresponding DOM node anchor the anchor on which to anchor panels ope...
FileUtils.jsm
ce key. nsIFile getFile( string key, array pathArray, bool followLinks ); Parameters key The nsIDirectoryService key to start from (see Getting special files for more info) pathArray An array of path components to locate beneath the directory specified by key. The last item in this array must be the leaf name of a file. followLinks Optional True if links should be followed, false
otherwise. Return value Returns a nsIFile object for the file specified. The file is NOT created if it does not exist, however all required directories along the way are. getDir() Gets a directory at the specified hierarchy under a nsIDirectoryService key. nsIFile getDir( string key, array pathArray, bool shouldCreate, bool followLInks ); Parameters key The nsIDirectoryService key to st...
...ir( string key, array pathArray, bool shouldCreate, bool followLInks ); Parameters key The nsIDirectoryService key to start from (see Getting special files for more info) pathArray An array of path components to locate beneath the directory specified by key. shouldCreate Optional True if the directory hierarchy specified in pathArray should be created if it does not exist, false
otherwise. followLinks Optional True if links should be followed, false
otherwise location specified. Return value Returns a nsIFile object for the location specified. If the directory requested does not exist, it is created, along with any parent directories that need to be created. Note: If you want to use the full path to get to the directory you cannot use getDir. Instead use the file constructo...
OS.File for the main thread
rwrite than to check manually whether the file exists. This operation is OS-optimized under OS X (native operation copyfile), Linux/Android (native operation splice), and Windows (native operation CopyFile). OS.File.exists() Determine whether a file exists Promise<bool> exists( in string path ) Arguments path The name of the file Promise resolves to true if the file exists, false
otherwise Performance note: For the sake of performance, you should avoid this function whenever possible. For instance, rather than calling exists() to determine if a directory should be created with makeDir, you should rather create the directory with makeDir and catch the error if the directory exists. This will ensure that you only need to perform one I/O operation rather than two. OS.File.getCurre...
...a new directory Promise<void> makeDir( in string path, [optional] in object options ) throws OS.File.Error Arguments path The full name of the directory to create. optionsOptional Options for creating the directory. To specify options, pass an object that may contain some of the following flags: ignoreExisting If true, succeed even if the directory already exists (default behavior).
Otherwise, fail if the directory already exists. NOTE: If from is specified then even if ignoreExisting is specified as false, it will not fail due to pre-existence of directories, because the from option tells makeDir to make the folders if not found. unixMode (ignored under non-Unix platforms) If specified, file creation mode, as per libc function mkdir. If unspecified, directories are created with a d...
Using JavaScript code modules
The URL for a code module As you can see from the example above, you need a URL to import a code module. (The URL in the example is "resource://app/my_module.jsm".) Code modules can only be loaded using a chrome: (), resource:, or file: URL. If you're writing an extension for Firefox 4 and already have a chrome.manif...
...e solution is moving the call to Components.utils.import() into the XPCOM component constructor (discussion). Packaging notes It's important to note that you should not typically put your JavaScript code modules in a JAR file in your add-on. Firefox 3.6 doesn't support them at all, and there's only one case in which it's remotely useful: a Firefox 4-only add-on which must be installed unpacked.
Otherwise placing code modules in a JAR file breaks compatibility unnecessarily. Importing CommonJS modules The JavaScript code modules described here are not the same thing as CommonJS modules, but you can import CommonJS modules into any scope where you can use Components.utils.import. Just call the following: const { require } = Cu.import("resource://gre/modules/commonjs/toolkit/require.js", {}) Thi...
Memory reporting
pecific fields return n; } virtual size_t SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf) const override { return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf); } // data members }; Things to note about SizeOfExcludingThis when it is virtual. If D has data members that point to other objects, then D::SizeOfExcludingThis must override B::SizeOfExcludingThis.
Otherwise, if we have a B* pointer that actually points to a D object, we'll end up calling B::SizeOfExcludingThis instead of D::SizeOfExcludingThis, and thus we'll fail to measure any objects that D's fields point to. D::SizeOfExcludingThis must also call B::SizeOfExcludingThis, to ensure that any objects pointed to by fields inherited from B are measured. However, if D does not have any of its own field...
...pointed to by more than one other object) it gets more difficult, and might even require some way to mark objects that have been counted (and then a way to unmark them once the measurement is complete). It's easy to get confused as to whether you should use SizeOfIncludingThis or SizeOfExcludingThis. A good rule of thumb: if you're calling the method via a pointer, you usually want the former,
otherwise you want the latter. For example: foo->SizeOfIncludingThis() // yes foo.SizeOfExcludingThis() // yes foo.SizeOfIncludingThis() // no foo->SizeOfExcludingThis() // no Sometimes memory reporters are stand-alone objects, like the MyStringReporter example above. But often you'll have a singleton object that needs measuring, in which case it is usually better not to have a separate reporter o...
L20n Javascript API
n in one of supported locales; the Context instance will try to retrieve a fallback translation from the next locale in the fallback chain, Compiler.Error, when L20n is unable to evaluate an entity to a string; there are two types of errors in this category: Compiler.ValueError, when L20n can still try to use the literal source string of the entity as fallback, and Compiler.IndexError
otherwise. ctx.removeEventListener(event: String, callback: Function) Remove an event listener previously registered with addEventListener. ctx.updateData(ctxdata: Object) Update the context data which will be available to all entities in the context. The ctxdata is an object which extends the context data per key and per level of hierarchy. In other words, the following two calls: ctx.upd...
... After that, each time locale list is modified (retranslation case) the callback will be executed. ...
nss tech note2
KCS #11 module. It works by inserting a special set of entry points between NSS and the module. To enable the module logger, you must set the environment variable NSS_DEBUG_PKCS11_MODULE to the name of the target module. For example, to log the softoken, use: NSS_DEBUG_PKCS11_MODULE="NSS Internal PKCS #11 Module" Note: In the Command Prompt on Windows, do not quote the name of the target module,
otherwise the quotes are considered part of the name. For example, to log the softoken on Windows, use: set NSS_DEBUG_PKCS11_MODULE=NSS Internal PKCS #11 Module The logger is available by default in debug builds. For optimized builds, NSS must be built with the variable DEBUG_PKCS11 set. Modes of Operation The logger has several modes of operation: 1. Only display the sequence of PKCS #11 calls. To ...
...n optimized builds. The number of calls to each PKCS #11 function will be counted, and the time spent in each function as well. A summary of performance data is dumped during NSS shutdown. No additional environment variables are required for this mode. If the environment variable NSS_OUTPUT_FILE is set, its value will be used as the path name of the file to which the final output will be written.
Otherwise, the output will be written to stdout. ...
Python binding for NSS
The Beast CVE fix in NSS causes only one octet to be sent in the first socket packet and then the remaining data is sent normally, this is known as 1/n-1 record splitting. The example and test SSL code sent short messages and then did a ...
...) nss.nss.make_line_pairs() nss.nss.oid_dotted_decimal() nss.nss.oid_str() nss.nss.oid_tag() nss.nss.oid_tag_name() nss.nss.read_der_from_file() nss.nss.x509_alt_name() nss.nss.x509_ext_key_usage() nss.nss.x509_key_usage() The following class methods and properties were added: Note: it's a method if the name is suffixed with (), a propety
otherwise Socket.next() Socket.readlines() Socket.sendall() SSLSocket.next() SSLSocket.readlines() SSLSocket.sendall() AuthKeyID.key_id AuthKeyID.serial_number AuthKeyID.get_general_names() CRLDistributionPoint.issuer CRLDistributionPoint.get_general_names() CRLDistributionPoint.get_reasons() CertDB.find_crl_by_cert() CertDB.find_c...
ssltyp.html
ory associated with a SECItem structure. Syntax #include <prtypes.h> SECStatus SECItem_FreeItem ( SECItem *item, PRBool freeItem) Parameter This function has the following parameter: item A pointer to a SECItem structure. freeItem When PR_FALSE, free only the structure pointed to.
Otherwise, free both the structure pointed to and the SECItem structure itself. Returns The function returns one of these values: If successful, SECSuccess. If unsuccessful, SECFailure. Use PR_GetError to retrieve the error code. Description This function frees the memory associated with the structure to which the specified item points, when that structure is no longer used.
...ry associated with a SECItem structure. Syntax #include <prtypes.h> SECStatus SECItem_ZfreeItem ( SECItem *item, PRBool freeItem) Parameter This function has the following parameter: item A pointer to a SECItem structure. freeItem When PR_FALSE, free only the structure pointed to.
Otherwise, free both the structure pointed to and the SECItem structure itself. Returns The function returns one of these values: If successful, SECSuccess. If unsuccessful, SECFailure. Use PR_GetError to retrieve the error code. Description This function is similar to SECItem_FreeItem, except that it overwrites the structures to be freed with zeroes before it frees them. Ze...
NSS tools : signtool
efault compression value used by both the -J and -Z options is 6. -d certdir Specifies your certificate database directory; that is, the directory in which you placed your key3.db and cert7.db files. To specify the current directory, use "-d." (including the period). The Unix version of signtool assumes ~/.netscape unless told
otherwise. The NT version of signtool always requires the use of the -d option to specify where the database files are located. -e extension Tells signtool to sign only files with the given extension; for example, use -e".class" to sign only Java class files. Note that with Netscape Signing Tool version 1.1 and later this option can appear multipl...
...d option with the -G option. With the Unix version of Netscape Signing Tool, omitting the -d option causes the tool to install the keys and certificate in the Communicator key and certificate databases. If you are installing the keys and certificate in the Communicator databases, you must exit Communicator before using this option;
otherwise, you risk corrupting the databases. In all cases, the certificate is also output to a file named x509.cacert, which has the MIME-type application/x-x509-ca-cert. Unlike certificates normally used to sign finished code to be distributed over a network, a test certificate created with -G is not signed by a recognized certificate authority. Inst...
Necko walkthrough
peInputStream::AsyncWait), with target thread set to the current thread, i.e. main. So, subsequent callbacks will be dispatched to the main thread. nsPipeInputStream::AsyncWait sets the callback to be used later for a response if a target is specified (in this case, the main thread), callback is proxied via an nsInputStreamReadyEvent, which is created now and may be called later
Otherwise, the callback would be called directly, when the socket is readable Et voila, the transaction has been posted to the socket thread, and the main thread continues on, unblocked from network IO. So, on the socket thread... The event queue works around to nsHttpConnectionMgr::OnMsgNewTransaction (with the nsHttpTransaction passed as a param - Remember the event was posted earlier by InitiateTr...
...essNewTransaction (Notice the check that we're on gSocketThread) Gets conn info (i.e. hostname and port) from the transaction, and then gets or creates a connection entry from the connection table, an nsClassHashtable<nsCStringHashKey, nsConnectionEntry> called mCT in nsHttpConnectionMgr. If a connection entry already exists matching the required conn info, then that one will be used;
otherwise a new one is created (MakeNewConnection - creates socket etc.). Note: nsConnectionEntry has a single nsHttpConnectionInfo object attached, a pending queue of nsHttpTransactions, and 3 arrays for connections: active nsHttpConnections idle nsHttpConnections nsHalfOpenSockets nsHttpConnectionMgr::TryDispatchTransaction There is a series of decisions about ...
Rhino overview
(and thus ECMA conformant) for version 1.3 and greater. Array.prototype.toString and Object.prototype.toString Version 1.2 only returns array or object literal notation ("[1]" or "{a:1, b:2}" for example). In version 1.3 and greater these functions are ECMA conformant. Array constructor Array(i) for a number argument i constructs an array with a single element equal to i for version 1.2 only.
Otherwise the ECMA conformant version is used (an array is constructed with no elements but with length property equal to i). String.prototype.substring For version 1.2 only, the two arguments are not swapped if the first argument is less than the second one. All other versions are ECMA compliant. String.prototype.split For version 1.2 only, split performs the Perl4 special case when given a single spa...
...he interpreter if interpretive mode is in effect. Second, it may be a generated class if classfile generation is supported. An embedding can distinguish the two cases by calling isInterpreterClass() in the Context class. If it is the interpreter class, call the getInterpreterSecurityDomain() method of Context to obtain the security domain of the currently executing interpreted script or function.
Otherwise, it must be a generated class, and an embedding can call getSecurityDomain() in the class implementing SecuritySupport. When the class was defined and loaded, the appropriate security domain was associated with it, and can be retrieved by calling this method. Once the security domain has been determined, an embedding can perform whatever checks are appropriate to determine whether access should b...
Hacking Tips
*) (mir=0x33dbdf0) at .../js/src/jit/Ion.cpp:1570 (gdb) iongraph mir function 0 (asm.js compilation): success; 1 passes. /* open your png viewer with the result of iongraph */ This gdb instrumentation is supposed to work with debug builds, or with optimized build compiled with --enable-jitspew configure flag. External programs such as iongraph, dot, and your png viewer are search into the PATH,
otherwise custom one can either be configured with environment variables (GDB_IONGRAPH, GDB_DOT, GDB_PNGVIEWER) before starting gdb, or with gdb parameters (set iongraph-bin <path>, set dot-bin <path>, set pngviewer-bin <path>) within gdb. Enabling GDB instrumentation may require launching a JS shell executable that shares a directory with a file name "js-gdb.py". If js/src/js does not provide the "iongr...
...estrict programs of these groups to the first core of the CPU. This is a list of cpu, which means that we can allocate 2 cores by doing 0-1 instead of 0. $ cgset -r cpuset.cpus=0 /benchmarks $ cgset -r cpuset.cpus=0 /benchmarks/mask $ cgset -r cpuset.cpus=0 /benchmarks/negate-mask Then we restrict programs of these groups to the first memory node. Most of the time you will only have one,
otherwise you should read what is the best setting to set here. If this is not set, you will have some error when you will try to write a pid in /sys/fs/cgroup/cpuset/benchmarks/mask/tasks while running cgexec. $ cgset -r cpuset.mems=0 /benchmarks $ cgset -r cpuset.mems=0 /benchmarks/mask $ cgset -r cpuset.mems=0 /benchmarks/negate-mask Then we limit the performance of the CPU, as a proportion suc...
Introduction to the JavaScript shell
ects. See js/src/shell/js.cpp (around shell_functions) for more. build() Returns the date and time at which the JavaScript shell was built. Note: clear() with no parameters really clears everything. This includes all these built-in functions. clone(function, [scope]) Clones the specified function object. If scope isn't specified, the new object's parent is the same as the original object's.
Otherwise, the new object is placed in the scope of the object specified by scope. countHeap([start[, kind]]) Added in SpiderMonkey 1.8 Count the number of live GC things in the heap, or things reachable from start when it is given and is not null. kind is either 'all' (default) to count all things or one of 'object', 'double', 'string', 'function', 'qname', 'namespace', 'xml' to count only things of tha...
...pression ...]) Evaluates the expression(s) and displays the result(s) on stdout, separated by spaces (" ") and terminated by a newline ("\n"). putstr(expression) Evaluates the expression and displays the result on stdout. quit([status]) Exits the shell. status defaults to 0 if omitted. read(filename[, type]) Reads and returns the contents of file. If type is "binary" returns an Uint8Array,
otherwise returns an UTF-8 decoded string. readline() Reads a single line of input from stdin, returning it to the caller. You can use this to create interactive shell programs in JavaScript. Reflect.parse() See Parser API. Note: This function is intended only for use when testing the JavaScript engine. seal(object[, deep]) Seals the specified object, or an object graph if deep is true. By sealing a...
JS::CompileOptions
ibutes. If one assigns a function, that function's script's source does not belong to the DOM element; the function's definition must appear elsewhere.) JSString *elementAttributeName() const If this source belongs to a DOM element because it is an event handler content attribute or an event handler IDL attribute, this returns the name of that attribute, a string.
Otherwise, this returns NULL. JSScript *introductionScript() const Returns a pointer to JSScript which introduces the file. bool copy(JSContext *cx, const ReadOnlyCompileOptions &rhs) Copy compile options from rhs. Returns false if it failed to duplicate owning properties. bool setFile(JSContext *cx, const char *f) Duplicate null-terminated string f for filename(). Retur...
... hasIntroductionInfo bool true if setIntroductionInfo is called. Description In the most common use case, a CompileOptions instance is allocated on the stack, and holds non-owning references to non-POD option values: strings; principals; objects; and so on. The code declaring the instance guarantees that such option values will outlive the CompileOptions itself: objects are
otherwise rooted; principals have had their reference counts bumped; strings will not be freed until the CompileOptions goes out of scope. In this situation, CompileOptions only refers to things others own, so it can be lightweight. In some cases, however, we need to hold compilation options with a non-stack-like lifetime. For example, JS::CompileOffThread needs to save compilation options where a worker ...
JS_ConstructObject
bject's prototype, or NULL. parent JSObject * The object to serve as the new object's parent, or NULL. argc unsigned int (only in JS_ConstructObjectWithArguments) The number of arguments to pass to the constructor. argv jsval * (only in JS_ConstructObjectWithArguments) The array of arguments to pass to the constructor. This may be null if argc is zero.
Otherwise, the first argc elements of this array must be populated with valid jsval values. The caller does not need to ensure that the array elements are rooted. Description JS_ConstructObject creates a new object of the specified class, with the specified prototype and parent, then invokes a constructor function to initialize the new object. cx is a pointer to a context associated with the runtim...
...w we find the appropriate constructor and default prototype, see JS_NewObject: Choosing a Default Prototype. Roughly speaking, we use parent or cx to find a global object, and then find clasp's constructor in that global object. If parent is NULL, the engine chooses an object to serve as the new object's parent. On success, JS_ConstructObject returns a pointer to the newly instantiated object.
Otherwise it returns NULL. The new object created by these functions is subject to garbage collection. The object should be made GC-reachable immediately. See the JSAPI User Guide. See Also JS_DefineObject JS_NewObject bug 757551 ...
JS_ConvertValue
Context * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. type JSType The type to which the value is to be converted. type must be one of JSTYPE_VOID, JSTYPE_OBJECT, JSTYPE_FUNCTION, JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_BOOLEAN.
Otherwise JS_ConvertValue reports an error. vp JS::MutableHandleValue Out parameter. On success, *vp receives the converted value. Description JS_ConvertValue converts a JavaScript value, v, to the specified type. On success, the converted value is stored in *vp. Typically users of this function set vp to point to v, so that if conversion is successful, v now contains the converted v...
...ically users of this function set vp to point to v, so that if conversion is successful, v now contains the converted value. JS_ConvertValue calls other, type-specific conversion routines based on the type argument. Converting any value to JSTYPE_VOID always succeeds. The result is undefined value. Converting to JSTYPE_OBJECT works exactly like JS::ToObject if v.isNullOrUndefined() is false,
otherwise the result is nullptr. Converting to JSTYPE_FUNCTION works like JS_ValueToFunction, but better: the result is a function object that has not been stripped of its lexical scope. It is safe to call the result (e.g. using JS_CallFunctionValue). Converting to JSTYPE_STRING works like JS::ToString. Converting to JSTYPE_NUMBER works exactly like JS::ToNumber. Converting to JSTYPE_BOOLEAN works exac...
JS_DeleteProperty2
. name or id const char * or const char16_t or JS::HandleId Name of the property to delete. namelen size_t (only in JS_DeleteUCProperty2) The length of name in characters; or -1 to indicate that name is null-terminated. succeeded bool * Out parameter. On success, *succeeded receives false if the property was not deleted because it is permanent and true
otherwise. Description JS_DeleteProperty2 removes a specified property, name, from an object, obj, and stores true or false in *succeeded. It behaves like the JavaScript expression delete obj[name]. JS_DeleteUCProperty2 is the Unicode version of the function. JS_DeletePropertyById2 is the same but takes a JS::HandleId for the property name. First, a property lookup is performed. Then one of the fo...
...as no property with the given name or id, or if obj inherits the specified property from its prototype, then *succeeded is set to true and obj's JSClass.delProperty hook is called (which may change *succeeded). No property is deleted, but this is not an error. If obj has the specified property but it is permanent, then *succeeded receives false. No property is deleted, but this is not an error.
Otherwise obj has a non-permanent own property with the given name or id. In this case, *succeeded is set to true and obj's JSClass.delProperty hook is called (which may change *succeeded). If the hook returns false, the error is propagated.
Otherwise, if obj is not configurable, an error is raised.
Otherwise, *succeeded receives true and the property is removed. These functions return true on success, r...
JS_EncodeCharacters
the converted string, in bytes. On failure, *dstlenp receives the number of bytes written to dst before the error occurred. Description JS_EncodeCharacters copies the characters of a jschar array into a char array, converting the 16-bit values to 8-bit values. If SpiderMonkey was built with JS_C_STRINGS_ARE_UTF8 defined or JS_SetCStringsAreUTF8 was called, the string is converted to UTF-8.
Otherwise each character is simply truncated to 8 bits. If UTF-8 is turned on, the length of the encoded string may vary. To calculate the number of bytes needed, call JS_EncodeCharacters twice, like this: /* Determine how many bytes to allocate. */ size_t dstlen = 0; if (!JS_EncodeCharacters(cx, src, srclen, NULL, &dstlen)) return JS_FALSE; /* Allocate. */ char *dst = (char *...
...(cx, dstlen); if (dst == NULL) return JS_FALSE; /* Convert characters to bytes. */ JS_EncodeCharacters(cx, src, srclen, dst, &dstlen); /* Use the converted bytes for something. */ ... /* Remember to free the bytes afterwards. */ JS_free(cx, dst); return JS_TRUE; On success, JS_EncodeCharacters sets *dstlenp to the real result length and returns JS_TRUE.
Otherwise it reports an error and returns JS_FALSE. This happens if the destination is too small for the resulting string or if the source buffer isn't proper UTF-16 because it contains unpaired surrogate values. The user is responsible for allocating and freeing the memory of the destination string. JS_EncodeCharacters never adds a trailing null character. To obtain a null-terminated string, allocate an ...
JS_ExecuteScript
initialized quite as described in any of the three cases in ECMA 262-3 ?10.2. Instead: The scope chain is initialized to contain obj, followed by its parent, then its parent's parent, etc. until NULL is reached. Variable initialization is performed. If the JSOPTION_VAROBJFIX option is in effect (recommended), then the last object in the scope chain is used as the variable object.
Otherwise obj is used. The this value is obj. scopeChain JS::AutoObjectVector & An explicit scope chain. scopeChain must not include the global object on it; that's implicit. It needs to contain the other objects that should end up on the scripts's scope chain. Objects in the vector should be ordered from inner to the outer scope. script JS::HandleScript The ...
...scription JS_ExecuteScript executes a previously-compiled script, script. JS::CloneAndExecuteScript handles a cross-compartment script. If the script is cross-compartment, it is cloned into the current compartment before executing. If the script executes successfully, rval receives the value from the last executed expression statement processed in the script, and JS_ExecuteScript returns true.
Otherwise it returns false, and the value left in rval is unspecified. The JSAPI User Guide contains example code using compiled scripts. To execute a script that has not been compiled, use JS::Evaluate instead. See Also MXR ID Search for JS_ExecuteScript MXR ID Search for JS::CloneAndExecuteScript JS::Compile JS::Evaluate bug 993438 bug 1145294 -- removed obj from JS::CloneAndExecuteScript. b...
JS_ExecuteScriptVersion
initialized quite as described in any of the three cases in ECMA 262-3 ?10.2. Instead: The scope chain is initialized to contain obj, followed by its parent, then its parent's parent, etc. until NULL is reached. Variable initialization is performed. If the JSOPTION_VAROBJFIX option is in effect (recommended), then the last object in the scope chain is used as the variable object.
Otherwise obj is used. The this value is obj. script JSObject * The compiled script to execute. rval jsval * Out parameter. On success, *rval receives the value from the last executed expression statement processed in the script. version JSVersion Version for the script. Description JS_ExecuteScript executes a previously-compiled script, sc...
...val receives the value from the last executed expression statement processed in the script. version JSVersion Version for the script. Description JS_ExecuteScript executes a previously-compiled script, script. If the script executes successfully, *rval receives the value from the last executed expression statement processed in the script, and JS_ExecuteScript returns true.
Otherwise it returns false, and the value left in *rval is unspecified. To execute a script that has not been compiled, use JS::Evaluate instead. See Also JS::Compile JS_ExecuteScript JS::Evaluate bug 1095660 ...
JS_GetParent
oObject operator), an object initializer ({a: 1, b: 2}), or an array initializer ([1, 2, 3]), has the global object as its parent. The parent of a Function created by evaluating a function declaration or function expression in a script depends on the lexical scope of the function. If there is no enclosing function, with statement, or block scope, then the Function's parent is the global object.
Otherwise, the parent is implementation-defined. It may be a Call, With, or Block object representing the function's dynamic scope, or it may be the global object. In any case the global object is guaranteed appear on the new function's parent chain. The initial parent of an object created via the JSAPI depends on the particular JSAPI function (of which there are many that create objects, including but...
...Object, JS_ValueToObject, JS_NewArrayObject, JS_NewScriptObject, JS_NewFunction, JS_CompileFunction, JS_DefineFunction, JS_DefineFunctions, and JS_InitClass). Some of these functions allow the application to specify a parent object. If the JSAPI function creating the object has a parent parameter, and the application passes a non-null value to it, then that object becomes the new object's parent.
Otherwise, if the context is running any scripts or functions, a default parent object is selected based on those.
Otherwise, if the context has a global object, it is used.
Otherwise the new object has no parent. This is often the case for the global object, which is typically the first object created in a new context. The preferred way to set an object's parent is by using the parent parameter to JS_...
JS_InitClass
arent_proto. JS_InitClass uses parent_proto to build a prototype object for the class. The prototype object inherits properties and methods from the parent_proto object you provide. Once the constructor or prototype is created, JS_InitClass defines a property on obj. The name of the property is clasp->name. Its value is the constructor function if constructor is non-null, and the prototype object
otherwise. The property has the stub getter and setter and no property attributes. (If your constructor function requires property attributes, such as JSPROP_ENUMERATE, use JS_SetPropertyAttributes to modify the attributes of the property created by JS_InitClass.) After building the constructor and prototype, JS_InitClass adds properties and methods. Ordinary properties and methods are added to the prototy...
...a is NULL. The JSCLASS_CONSTRUCT_PROTOTYPE flag is one way to avoid this inconsistency. Warning: If the class is a JSExtendedClass, make sure that the additional reserved fields at the end of the JSExtendedClass are NULL. JSExtendedClass structs should usually be global, and in this case the compiler automatically initializes these fields to NULL. (This is a feature of the C and C++ languages.)
Otherwise, use memset. See Also MXR ID Search for JS_InitClass JS_GetClass JS_InstanceOf ...
JS_NewFunction
The context in which to create the new function. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. call JSNative Native C/C++ implementation of this function. nargs unsigned Number of arguments the function expects. flags unsigned Pass JSFUN_CONSTRUCTOR to make a native that can be called as a constructor,
otherwise 0. parent JS::Handle<JSObject*> Pointer to the parent object for this function. If this is NULL, a default parent object is used. Obsolete since JSAPI 39 name const char * Name to assign to the new function. If this is NULL, the new function has no name. id JS::Handle<jsid> A pointer to jsid of the name to assign to the new function. Added ...
... is JSFUN_CONSTRUCTOR, a created function can be called as a constructor. parent may be used to specify the new function's parent; NULL is usually the right thing here. name is the name to assign to the function. If name is NULL, the new function has no name. (JS_GetFunctionId, passed the new function, will return NULL.) On success, JS_NewFunction returns a pointer to the newly created function.
Otherwise it reports an out-of-memory error and returns NULL. See Also MXR ID Search for JS_NewFunction MXR ID Search for JS_NewFunctionById JS_CallFunction JS_CallFunctionName JS_CallFunctionValue JS_CompileFunction JS_CompileUCFunction JS_DefineFunction JS_DefineFunctions JS_GetFunctionName JS_GetFunctionObject bug 607695 - added JS_NewFunctionById bug 1140573 - removed parent parameter ...
JS_NewGlobalObject
based on the specified class. The new object has no parent. It initially has no prototype either, since it is typically the first object created; call JS_InitStandardClasses to create all the standard objects, including Object.prototype, and set the global object's prototype. The constructor clasp->construct is not called. On success, JS_NewGlobalObject returns a pointer to the new object.
Otherwise it returns NULL. Debugger API Hook During global creation, we fire notifications to callbacks registered via the Debugger API. These callbacks are arbitrary script, and can touch the global in arbitrary ways. When that happens, the global should not be in a half-baked state. But this creates a problem for consumers that need to set slots on the global to put it in a consistent state. This API ...
... way for consumers to set slots atomically (immediately after the global is created), before any debugger hooks are fired. It's unfortunately on the clunky side, but that's the way the cookie crumbles. If callers have no additional state on the global to set up, they may pass FireOnNewGlobalHook to JS_NewGlobalObject, which causes that function to fire the hook as its final act before returning.
Otherwise, callers should pass DontFireOnNewGlobalHook, which means that they are responsible for invoking JS_FireOnNewGlobalObject upon successfully creating the global. If an error occurs and the operation aborts, callers should skip firing the hook. But
otherwise, callers must take care to fire the hook exactly once before compiling any script in the global's scope (we have assertions in place to enforc...
JS_NewNumberValue
ler must be in a request on this JSContext. d jsdouble The numeric value to convert. rval jsval * Out parameter. On success, *rval receives a JavaScript number with the value d. Description JS_NewNumberValue converts a C floating-point number of type jsdouble to jsval, the type of JavaScript values. The result is an integer jsval if d can be stored that way.
Otherwise, a new floating-point jsval is created. Some space for the new value may be allocated from the JS garbage collection heap. In this case, the value is subject to garbage collection until you protect against it using a local root, an object property, or the JS_AddRoot function. This can be avoided by using the address of a rooted variable as rval. On success, JS_NewNumberValue stores a numeric js...
...eated. Some space for the new value may be allocated from the JS garbage collection heap. In this case, the value is subject to garbage collection until you protect against it using a local root, an object property, or the JS_AddRoot function. This can be avoided by using the address of a rooted variable as rval. On success, JS_NewNumberValue stores a numeric jsval in *rval and returns JS_TRUE.
Otherwise it returns JS_FALSE and the value left in *rval is unspecified. See Also JS_NumberValue bug 752223 ...
JS_ValueToId
An unsigned integer index of array to convert. chars JS::TwoByteChars The string to convert. key JSProtoKey The prototype key to convert. idp JS::MutableHandleId Out parameter. On success, *idp receives the converted jsid. Description JS_ValueToId converts a specified JS::Value, v, to a jsid. If v is an integer, *idp receives an integer jsid.
Otherwise, if E4X support is enabled and v is an object, *idp receives an object jsid.
Otherwise, *idp receives an interned string jsid based on the value of v. If v is not a string, it is converted to a string as if by calling JS_ValueToString. JS_StringToId and JS_CharsToId convert a specified string to a jsid. JS_IndexToId converts a specified integer index to an integer jsid. JS::ProtoKeyToId conver...
...ng jsid based on the value of v. If v is not a string, it is converted to a string as if by calling JS_ValueToString. JS_StringToId and JS_CharsToId convert a specified string to a jsid. JS_IndexToId converts a specified integer index to an integer jsid. JS::ProtoKeyToId converts a specified prototype key to a jsid. On success, JS_ValueToId stores the converted value in *idp and returns true.
Otherwise it returns false. The inverse of JS_ValueToId is JS_IdToValue. MXR ID Search for JS_ValueToId See Also MXR ID Search for JS_IdToValue MXR ID Search for JS_StringToId MXR ID Search for JS_IndexToId MXR ID Search for JS_CharsToId MXR ID Search for JS::ProtoKeyToId JS_ValueToId bug 698495 - added JS_IndexToId bug 830500 - added JS_CharsToId bug 959787 - added JS_StringToId bug 987669 ...
JS_ValueToNumber
operator described in ECMA 262-3 ?9.3. If v is already a number, conversion succeeds. If v is undefined, null, false, or true, conversion succeeds, and the result is NaN, 0, 0, or 1 respectively. If v is a string, conversion proceeds as specified in ECMA 262-3 ?9.3.1. JS_ValueToNumber always succeeds in this case, returning JS_TRUE. If the string is not a numeric string, *dp is set to NaN.
Otherwise v is an object. JS_ValueToNumber carries out the following steps to convert it to a number. If at any step an error or exception occurs, or conversion succeeds, the rest of the steps are skipped. (This behavior is implemented by v's JSObjectOps.defaultValue hook, so host objects can override it all.) First, the object's JSClass.convert callback is called. For objects of standard classes, th...
...his behavior is implemented by v's JSObjectOps.defaultValue hook, so host objects can override it all.) First, the object's JSClass.convert callback is called. For objects of standard classes, this is JS_ConvertStub, which simply calls v.valueOf() if present. If the convert callback produces a primitive value, the value is converted to a number as described above and conversion succeeds.
Otherwise, the resulting object's toString method, if any, is called. If that produces a primitive value, the value is converted to a number as described above and conversion succeeds.
Otherwise conversion fails with a TypeError. On success, JS_ValueToNumber stores the converted value in *dp and returns JS_TRUE. On error or exception, it returns JS_FALSE, and the value left in *dp is undefined. ...
JS_ValueToString
cript expression ""+v. If v is already a string, conversion succeeds. If v is true, false, null, or undefined, conversion succeeds, and the result is the string "true", "false", "null", or "undefined", accordingly. If v is a number, conversion succeeds, and the result is a string representation of that number as specified in ECMA 262-3 ?9.8.1. This might be "NaN", "Infinity", or "-Infinity".
Otherwise the result is a decimal representation of the number, possibly using exponential notation.
Otherwise v is an object. JS_ValueToString uses the steps below to convert it to a string. If at any point an error or exception occurs, or conversion succeeds, the rest of the steps are skipped. (This behavior is implemented by v's JSObjectOps.defaultValue method, so host objects can override it all.) ...
...o a string. If at any point an error or exception occurs, or conversion succeeds, the rest of the steps are skipped. (This behavior is implemented by v's JSObjectOps.defaultValue method, so host objects can override it all.) If v.toString() is a function, it is called. If that method returns a primitive value, the value is converted to a string as described above and conversion succeeds.
Otherwise, the resulting object's JSClass.convert callback is called. For standard classes, this is JS_ConvertStub, which simply calls v.valueOf() if present. If the convert callback produces a primitive value, the value is converted to a string as described above and conversion succeeds.
Otherwise conversion fails with a TypeError. On success, JS_ValueToString returns a pointer to a string. On ...
Redis Tips
key value INCR key INCRBY key int INCRBYFLOAT key float GETSET key value GET and SET are fairly obvious. SETNX sets a value on a key only if there is no existing value. This is so useful. And it is a single, atomic command. redis> get foo (nil) redis> setnx foo 17 (integer) 1 redis> get foo "17" redis> setnx foo 42 (integer) 0 The return value from SETNX is 1 if the value was set, 0
otherwise. INCR, INCRBY, and INCRBYFLOAT all increment counters. They are also atomic operations. They return the post-increment value of your key. redis> set foo 42 OK redis> incr foo (integer) 43 redis> incrby foo 17 (integer) 60 Notice that these results come back as numbers, not strings. INCRBYFLOAT is in redis 2.6. GETSET is awesome. It sets the value of a key, and returns the value the...
...TTL PERSIST SETEX Example: redis> set foo 42 OK redis> ttl foo (integer) -1 redis> expire foo 5 (integer) 1 Three seconds later ... redis> ttl foo (integer) 2 A further two seconds later ... redis> get foo (nil) redis> ttl foo (integer) -1 Using EXPIRE you set an expiration in seconds from the present. TTL tells you the time-to-live for the key, if there is an expiration set on it.
Otherwise, you get -1. Note that you get -1 both when there's no expiration and when there's no key. If you change your mind, and you want to save the key from oblivion, you can PERSIST it to undo the EXPIRE command. EXPIREAT lets you specify the expiration date of a key in unix timestamp. SETEX is an atomic shortcut for SET + EXPIRE. Using ZSETs, you can periodically cull expired objects by us...
XUL Accessibility
d to generating accessible name and description. ...
...m element subtree if the child node is hidden then it's ignored excepting the case when the element used as label is hidden itself If the child node is text node then its rendered value is appended If the child node is element then if it implements nsIDOMXULLabeledControlElement then the value of label property is appended
otherwise if it's a label element then then value attribute is appended
otherwise append tooltiptext attribute append the accessible value Searching specific element in neighbour of the element search inside the element subtree go up through parents (max level is 5) and search inside theirs subtrees if the element is anonymous then search in whole anonymous subtree, here the attribute anonid is used instead of id attribute Accessible properties This section describes co...
Mork
ex buffer and replacing it with the alias value for the hex key (explained below). A mid has two components: the ID itself, to the left of the colon, and the scope, to the right of the colon. There are two types of meta-rows, those of rows and those of tables. However, since the meta-row of a row never appears to be used, I will generally use 'meta-row' to refer to the meta-row of a table, unless
otherwise qualified. Dictionaries A dictionary establishes a series of aliases. If inside the meta-dictionary, the only cell we care about is if the key is 'a' (for atom scope). This value is used to establish which dictionary the aliases are added to. Most files will have just two dictionaries: the column scope dictionary ('c') and the value scope dictionary ('v', the default). The keys are hexadecimal n...
...able. Rows For the most part, a row should not be seen outside of a table; the only time I have seen one outside a table is for table meta-rows. The first mid, as you should expect by now, is the row ID, with the scope being an important part of the ID, in that 1:scope1 is not the same row as 1:scope2. If the scope is not specified, then it is the default scope of the table (if it has one) or 'r'
otherwise. These row IDs are global, even if defined in a table. Indeed, defining a row in a table is a shortcut for both defining a row and adding the row to the table. The presence of an initial minus means to delete all cells before adding new cells. A minus after the mid indicates that the next cell should be deleted. I haven't seen that case though, so it may not be an issue in practice. The rowRefere...
XPCOM glue
t xpcomglue.lib. It should not link against xpcomglue_s.lib or xpcom.lib. Embedders using the standalone glue typically also need to avoid linking against NSPR as well. However, when using threadsafe together with the glue libraries from Gecko 1.8 or later, a special step needs to be taken to use NS_IMPL_THREADSAFE_ISUPPORTSn. This is because it forces a dependency on the NSPR library, which can
otherwise be avoided. As described in bug 299664, the preprocessor symbol XPCOM_GLUE_USE_NSPR needs to be defined. Using Mozilla internal linkage Mozilla internal code defines MOZILLA_INTERNAL_API while compiling and links against xpcom.lib and xpcom_core.lib. In almost all cases embedders should *not* use internal linkage. Components using internal linkage will have shared-library dependencies against n...
...kg-config --cflags --libs libxul.pc These instructions are for Mozilla 1.8 and above. When using a SDK from Mozilla 1.7 or earlier, you must define MOZILLA_STRICT_API when using any form of the glue. Linux and Mac: Make sure the Gecko libraries are listed after your object (.o) files on the link line. Linux and Mac: Write the linker options exactly as stated (just replacing the /path/to/sdk/),
otherwise you get an undefined symbol: ...NS_TableDrivenQI...QITableEntry... at runtime (not compile time) (in debug builds) or your module just won't load (in optimized builds). In principle, #include "mozilla-config.h" should also work, if it's the first #include in .cpp, but preprocessor option is how it's usually included. For XULRunner 2.0, you also need to link against mozalloc. This is not a bac...
XPCshell Test Manifest Expressions
Comments If an expression contains a # (pound/hash) character outside of a string, the character and the rest of the line will be treated as a comment. This is useful as the entire line will generally be reported whenever tests are reported as being skipped, meaning the comment as well as the express...
... One of: 'windows', 'cocoa', 'gtk2', 'android' processor - The CPU which the code is compiled for One of: 'x86', 'x86_64', 'arm' bits - The pointer size of the CPU architecture, in bits One of 32, 64, possibly unknown debug - Set to true if this build is a debug build, false
otherwise crashreporter - Set to true if this build has crash reporting code enabled, false
otherwise. Comments If an expression contains a # (pound/hash) character outside of a string, the character and the rest of the line will be treated as a comment. This is useful as the entire line will generally be reported whenever tests are reported as being skipped, meaning the comment as well as the expression itself will appear in any logs where this is reported. ...
imgIContainer
tions thrown Missing Exception Missing Description Native code only!copyCurrentFrame Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Create and return a new copy of the current frame that you can write to and
otherwise inspect the pixels of. gfxImageSurface copyCurrentFrame(); Parameters None. Return value Missing Description Exceptions thrown Missing Exception Missing Description Native code only!copyFrame Create and return a new copy of the given frame that you can write to and
otherwise inspect the pixels of. gfxImageSurface copyFrame( in PRUint32 aWhichFrame, in PRUint32 aFlags ); Parameter...
... aContext The Thebes context to draw the image to. aFilter The filter to be used if we're scaling the image. aUserSpaceToImageSpace The transformation from user space (for example, appunits) to image space. aFill The area in the context to draw pixels to. When aFlags includes FLAG_CLAMP, the image will be extended to this area by clamping image sample coordinates.
Otherwise, the image will be automatically tiled as necessary. aSubimage The area of the image, in pixels, that we are allowed to sample from. aViewportSize The size (in CSS pixels) of the viewport that would be available for the full image to occupy, if we were drawing the full image. (Note that we might not actually be drawing the full image -- we might be restricted by aSubimage -- but w...
mozIThirdPartyUtil
RI(in nsIURI aFirstURI, in nsIURI aSecondURI); boolean isThirdPartyWindow(in nsIDOMWindow aWindow, [optional] in nsIURI aURI); Methods isThirdPartyChannel() Determine whether the given channel and its content window hierarchy is third party. This is done as follows: If aChannel is an nsIHttpChannel and has the 'forceAllowThirdPartyCookie' property set, then: If aURI is null, return false.
Otherwise, find the URI of the channel, determine whether it is foreign with respect to aURI, and return. Find the URI of the channel and determine whether it is third party with respect to the URI of the channel. If so, return. Obtain the bottommost nsIDOMWindow, and its same-type parent if it exists, from the channel's notification callbacks. Then: If the parent is the same as the bottommost window, a...
..., and its same-type parent if it exists, from the channel's notification callbacks. Then: If the parent is the same as the bottommost window, and the channel has the LOAD_DOCUMENT_URI flag set, return false. This represents the case where a toplevel load is occurring and the window's URI has not yet been updated. (We have already checked that aURI is not foreign with respect to the channel URI.)
Otherwise, return the result of isThirdPartyWindow() with arguments of the channel's bottommost window and the channel URI, respectively. Therefore, both the channel's URI and each level in the window hierarchy associated with the channel is tested. For example, if aURI is "http://mail.google.com/", aChannel has a URI of "http://google.com/", and its parent is the topmost content window with a URI of "h...
nsIAuthInformation
dialog. After the user entered the authentication information, it should set the attributes of this object to indicate to the caller what was entered by the user. Attributes Attribute Type Description authenticationScheme AUTF8String The authentication scheme used for this request, if applicable. If the protocol for this authentication does not support schemes, this will be the empty string.
Otherwise, this will be a string such as "basic" or "digest". This string will always be in lowercase. Read only. domain AString The initial value should be used to prefill the dialog or be shown in some other way to the user. On return, this parameter should contain the domain entered by the user. This attribute is only used if flags include #NEED_DOMAIN. flags unsigned long Flags describing this dia...
... Read only. password AString The initial value should be used to prefill the dialog or be shown in some other way to the user. The password should not be shown in clear. On return, this parameter should contain the password entered by the user. realm AString The server-supplied realm of the authentication as defined in RFC 2617. Can be the empty string if the protocol does not support realms.
Otherwise, this is a human-readable string like "Secret files". Read only. username AString The initial value should be used to prefill the dialog or be shown in some other way to the user. On return, this parameter should contain the username entered by the user. This field can only be changed if the #ONLY_PASSWORD flag is not set. Constants Constant Value Description AUTH_HOST 1 This dialog bel...
nsIBrowserHistory
removePages( [array, size_is(aLength)] in nsIURI aURIs, in unsigned long aLength, in boolean aDoBatchNotify /* parameter removed in Gecko 9.0 */ ); Parameters aURIs An array of page URIs to be removed from history. aLength The number of pages listed in the aURIs array. aDoBatchNotify Obsolete since Gecko 9.0 If set to true, the BeginUpdateBatch and EndUpdateBatch events are sent;
otherwise, no notification of changes to the history is provided. This parameter was removed in Gecko 9.0. removePagesByTimeframe() Removes all pages within the given timeframe, using a batch. void removePagesByTimeframe( in long long aBeginTime, in long long aEndTime ); Parameters aBeginTime The time of the first page to remove, in microseconds from epoch. aEndTime The time of the last pa...
...the host to be removed. An empty value for this parameter means local files and anything else without a hostname. You can also pass in the localized "(local files)" title given to you by a history query to remove all history information for local files. aEntireDomain If set to true, it will assume aHost is a domain, and remove all pages from the entire domain, including subdomains. Set to false
otherwise. removeVisitsByTimeframe() Removes all visits within the given timeframe, using a batch. Any pages that become unvisited as a result are also deleted. void removeVisitsByTimeframe( in long long aBeginTime, in long long aEndTime ); Parameters aBeginTime The time of the first page to remove, in microseconds from epoch. aEndTime The time of the last page to remove, in microseconds fr...
nsICacheVisitor
deviceID, in nsICacheEntryInfo entryInfo); Methods visitDevice() This method is called to provide information about a cache device. boolean visitDevice( in string deviceID, in nsICacheDeviceInfo deviceInfo ); Parameters deviceID Specifies the device being visited. deviceInfo Specifies information about this device. Return value Returns true to start visiting all entries for this device,
otherwise returns false to advance to the next device. visitEntry() This method is called to provide information about a cache entry. boolean visitEntry( in string deviceID, in nsICacheEntryInfo entryInfo ); Parameters deviceID Specifies the device being visited. entryInfo Specifies information about this entry. Return value Returns true to visit the next entry on the current device, or if the end o...
...This method is called to provide information about a cache entry. boolean visitEntry( in string deviceID, in nsICacheEntryInfo entryInfo ); Parameters deviceID Specifies the device being visited. entryInfo Specifies information about this entry. Return value Returns true to visit the next entry on the current device, or if the end of the device has been reached, advance to the next device,
otherwise returns false to advance to the next device. See also nsICache nsICacheDeviceInfo nsICacheEntryInfo ...
nsICachingChannel
s offline. This flag will not be transferred through a redirect. LOAD_BYPASS_LOCAL_CACHE 1 << 28 This load flag causes the local cache to be skipped when fetching a request. Unlike LOAD_BYPASS_CACHE, it does not force an end-to-end load (That is, it does not affect proxy caches). LOAD_BYPASS_LOCAL_CACHE_IF_BUSY 1 << 29 This load flag causes the local cache to be skipped if the request would
otherwise block waiting to access the cache. LOAD_ONLY_FROM_CACHE 1 << 30 This load flag inhibits fetching from the net if the data in the cache has been evicted. An error of NS_ERROR_DOCUMENT_NOT_CACHED will be sent to the listener's onStopRequest in this case. This flag is set automatically when the application is offline. LOAD_ONLY_IF_MODIFIED 1 << 31 This load flag controls what happens when a do...
...e listener will only see OnStartRequest followed by OnStopRequest. Methods isFromCache() Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) This method finds out whether or not this channel's data is being loaded from the cache. boolean isFromCache(); Parameters None. Return value Returns true if this channel's data is being loaded from the cache,
otherwise returns false. This value is undefined before the channel fires its OnStartRequest notification and after the channel fires its OnStopRequest notification. See also nsICache ...
nsIClipboard
boolean hasDataMatchingFlavors( [array, size_is(aLength)] in string aFlavorList, in unsigned long aLength, in long aWhichClipboard ); Parameters aFlavorList An array of ASCII strings. aLength The length of the aFlavorList. aWhichClipboard Specifies the clipboard to which this operation applies. Return value Returns true, if data is present and it matches the specified flavor.
Otherwise it returns false. setData() This method sets the data from a transferable on the native clipboard. void setData( in nsITransferable aTransferable, in nsIClipboardOwner anOwner, in long aWhichClipboard ); Parameters aTransferable The transferable containing the data to put on the clipboard. anOwner The owner of the transferable. aWhichClipboard Specifies the clipboard to which t...
...oard. anOwner The owner of the transferable. aWhichClipboard Specifies the clipboard to which this operation applies. supportsSelectionClipboard() This method allows clients to determine if the implementation supports the concept of a separate clipboard for selection. boolean supportsSelectionClipboard(); Parameters None. Return value Returns true if kSelectionClipboard is available.
Otherwise it returns false. supportsFindClipboard() This method allows clients to determine if the implementation supports the concept of a separate clipboard for find search strings. boolean supportsFindClipboard(); Parameters None. Return value Returns true if the separate clipboard for find search strings is supported.
Otherwise it returns false. See also nsIClipboardOwner nsITransferable ...
nsIController
in string command ); Parameters command The name of the command to execute. isCommandEnabled() Implement this method to indicate whether or not the specified command is enabled. boolean isCommandEnabled( in string command ); Parameters command The name of the command whose availability is to be checked. Return value Return true if the specified command is currently available to be used;
otherwise, it should return false. onEvent() Implement this method to process the event with the specified name. void onEvent( in string eventName ); Parameters eventName The name of the event to process. supportsCommand() Implement this method to report whether or not the command with the specified name is supported. boolean supportsCommand( in string command ); Parameters command The name of the...
...vent( in string eventName ); Parameters eventName The name of the event to process. supportsCommand() Implement this method to report whether or not the command with the specified name is supported. boolean supportsCommand( in string command ); Parameters command The name of the command to determine whether or not it is supported. Return value true if the specified command is supported;
otherwise false. See also nsICommandController nsIControllers XUL Tutorial/Commands ...
nsIDocShell
DocShells are active if this is true, which is the default state. Note: Starting in Gecko 8.0, isActive is false for documents in minimized windows. isAppTab boolean Sets whether a docshell is an app tab. An app tab docshell may behave differently than a non-app tab docshell in some cases, such as when handling link clicks. Docshells are not app tabs unless told
otherwise. isExecutingOnLoadHandler boolean Returns true if the docshell is currently executing the onLoad Handler. Read only. isInUnload boolean Find out whether the docshell is currently in the middle of a page transition (after the onunload event has fired, but before the new document has been set up) Read only. isOffScreenBrowser boolean If true, this docs...
...ry (if loading from SH) firstParty true if this is the master top-level document. aDocShell If the load was succesfully initiated, this receives the nsIDocShell that actually performed the load. aRequest The new channel created for the load. isBeingDestroyed() boolean isBeingDestroyed(); Parameters None. Return value Returns true if the docshell is being destroyed, false
otherwise. Native code only!loadStream Loads a given stream. This will give priority to loading the requested stream in the object implementing this interface. If it can not be loaded here however, the URL dispatched will go through its normal process of content loading. void loadStream( in nsIInputStream aStream, in nsIURI aURI, in ACString aContentType, in ACString aContentCharset, in nsIDocShe...
nsIDragService
long aX, in long aY ); Parameters aX The X coordinate to which to move the popup being dragged. aY The Y coordinate to which to move the popup being dragged. endDragSession() Tells the Drag Service to end a drag session. This is called when an external drag occurs. void endDragSession( in PRBool aDoneDrag ); Parameters aDoneDrag If aDoneDrag is true, the drag has finished,
otherwise the drag has just left the window. fireDragEventAtSource() Obsolete since Gecko 43 (Firefox 43 / Thunderbird 43 / SeaMonkey 2.40)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Fire a drag event at the source of the drag. This was changed in Gecko 43, see the following section. void ...
...DOMNode, and the offset calculated so that the initial location for the image appears in the same screen position as where the element is located. The node must be within a document. Currently, supported images are all DOM nodes. If this is an HTML <image> or <canvas> element, the drag image is taken from the image data. If the element is in a document, it will be rendered at its displayed size,
otherwise, it will be rendered at its real size. For other types of elements, the element is rendered into an offscreen buffer in the same manner as it is currently displayed. The document selection is hidden while drawing. The aDragEvent must be supplied as the current screen coordinates of the event are needed to calculate the image location. void invokeDragSessionWithImage( in nsIDOMNode aDOMNode, ...
nsIEffectiveTLDService
were insufficient subdomain levels in the hostname to satisfy the requested aAdditionalParts value. NS_ERROR_HOST_IS_IP_ADDRESS This exception is thrown if aURI is a numeric IPv4 or IPv6 address. NS_ERROR_UNEXPECTED Or other error returned by nsIIDNService.normalize() when the hostname contains characters disallowed in URIs. getBaseDomainFromHost() Returns the base domain of a host string.
Otherwise identical to getBaseDomain(). Note: It is strongly recommended that you use getBaseDomain() if a suitable nsIURI is available. Only use this method if this is not the case. ACString getBaseDomainFromHost( in AUTF8String aHost, in PRUint32 aAdditionalParts Optional ); Parameters aHost The host string to be analyzed. aAdditionalParts Optional The number of domain name parts to be ret...
...ions thrown NS_ERROR_INVALID_ARG This exception is thrown if the hostname in aURI is empty. NS_ERROR_HOST_IS_IP_ADDRESS This exception is thrown if aURI is a numeric IPv4 or IPv6 address. NS_ERROR_UNEXPECTED Or other error returned by nsIIDNService.normalize() when the hostname contains characters disallowed in URIs. getPublicSuffixFromHost() Returns the public suffix of a host string.
Otherwise identical to getPublicSuffix(). Note: It is strongly recommended to use getBaseDomain() if a suitable nsIURI is available. Only use this method if this is not the case. ACString getPublicSuffixFromHost( in AUTF8String aHost ); Parameters aHost The host string to be analyzed. Return value An ACString containing the public suffix. Exceptions thrown NS_ERROR_INVALID_ARG This except...
nsIEventListenerService
in nsIDOMEventTarget target, in DOMString type, in nsIDOMEventListener listener, in boolean useCapture ); Parameters target The nsIDOMEventTarget for the event target to listen an event. type The event name to listen. listener The nsIDOMEventListener which listens the event. useCapture True if to listen the event in capture phase,
otherwise, false. removeSystemEventListener() Remove a system-group eventlistener from a event target. void removeSystemEventListener( in nsIDOMEventTarget target, in DOMString type, in nsIDOMEventListener listener, in boolean useCapture ); Parameters target The nsIDOMEventTarget for the event target listening the event. type The listening event name. listener...
... Remarks nsIEventListenerService was introduced with bug 448602. See also nsIEventListenerInfo nsIEventTarget ...
nsIFaviconService
TE or nsIFaviconService.FAVICON_LOAD_NON_PRIVATE to indicate that any network requests performed should act like ones from a private browsing context (ie. no history entries, only store in the temporary disk cache, etc.). This should be determined via PrivateBrowsingUtils.isWindowPrivate(someRelatedWindow) if the favicon may expose the user's private browsing data by performing a network request,
otherwise FAVICON_LOAD_NON_PRIVATE may be used. aCallback Optional from Gecko 2.0 An nsIFaviconDataCallback. Example var ioservice = Components.classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService); var pageURI = ioservice.newURI("http://www.mozilla.org/", null, null); var faviconURI = ioservice.newURI("http://www.mozilla.org/favico...
... later with SetFaviconData(). However, any favicons not associated with a visited web page, a bookmark, or a "place:" URI will be expired when history cleanup is done * (typically at app shutdown, but also possibly if the user clears their * cache or history). This will send out history notifications if the new favicon has any data. This means that you should try to set data first if you have it,
otherwise the page might not get a notification sent for it since data setting does not send notifications. void setFaviconUrlForPage( in nsIURI aPageURI, in nsIURI aFaviconURI ); Parameters aPageURI URI of the page whose favicon is being set. aFaviconURI URI of the favicon to associate with the page. See also Places Using the Places favicon service Using the Places annotation se...
nsIFileProtocolHandler
he corresponding nsIFile if possible. A local file will be created if the URL string begins with file://. nsIFile getFileFromURLSpec( in AUTF8String url ); Parameters url The url string to convert. Return value A reference to a new nsIFile object. getURLSpecFromActualFile() Converts the nsIFile to the corresponding URL string. Should only be called on files which are not directories.
Otherwise identical to getURLSpecFromFile(), but is usually more efficient. Warning: This restriction may not be enforced at runtime! AUTF8String getURLSpecFromActualFile( in nsIFile file ); Parameters file The nsIFile to convert. Return value Corresponding url string. The resulting string may contain URL-escaped characters. getURLSpecFromDir() Converts the nsIFile to the corresponding URL ...
...ent. Warning: This restriction may not be enforced at runtime! AUTF8String getURLSpecFromActualFile( in nsIFile file ); Parameters file The nsIFile to convert. Return value Corresponding url string. The resulting string may contain URL-escaped characters. getURLSpecFromDir() Converts the nsIFile to the corresponding URL string. Should only be called on files which are directories.
Otherwise identical to getURLSpecFromFile(), but is usually more efficient. WARNING: This restriction may not be enforced at runtime! AUTF8String getURLSpecFromDir( in nsIFile file ); Parameters file The nsIFile to convert. Return value Corresponding url string. The resulting string may contain URL-escaped characters. getURLSpecFromFile() Converts the nsIFile to the corresponding URL string. I...
nsIHttpServer
e of the server */ void registerFile(in string path, in nsIFile file); /** * Registers a custom path handler. ...
... handler * @param handler * an object which will handle any requests which generate the given status * code, or null to remove any existing handler. If the handler throws an * exception during server operation, fallback is to the genericized error * handler (the x00 version), then to 500, using a user-defined error * handler if one exists or the server default handler
otherwise. Fallback * will never occur from a user-provided handler that throws to the same * handler as provided by the server, e.g. a throwing user 404 falls back to * 400, not a server-provided 404 that might not throw. * @note * If the error handler handles HTTP 500 and throws, behavior is undefined. */ void registerErrorHandler(in unsigned long code, in nsIHttpRequestHandl...
nsIIDNService
ame isn't in the whitelist, it's converted into ACE format. The resulting string is useful for display purposes, and ensures that the encoding is consistent with nsIURI.GetHost(). AUTF8String convertToDisplayIDN( in AUTF8String input, out boolean isASCII ); Parameters input The string to convert to display format. isASCII On return, this is set to true if the result is ASCII or ACE encoded;
otherwise it's false. Return value The display formatted hostname. convertUTF8toACE() Converts the specified hostname from UTF-8 to ACE format, using the IDNA "ToASCII" algorithm. ACString convertUTF8toACE( in AUTF8String input ); Parameters input The hostname to convert to ACE format. Return value The ACE encoded version of the hostname. isACE() Determines whether or not the specified hostname is AC...
...CII" algorithm. ACString convertUTF8toACE( in AUTF8String input ); Parameters input The hostname to convert to ACE format. Return value The ACE encoded version of the hostname. isACE() Determines whether or not the specified hostname is ACE encoded. boolean isACE( in ACString input ); Parameters input The string to check. Return value Returns true if the specified string is ACE encoded;
otherwise, returns false. normalize() Performs the Unicode normalization needed for hostnames in IDN. This is useful if you need to normalize a hostname separately from converting it to display format. AUTF8String normalize( in AUTF8String input ); Parameters input The hostname to normalize. Return value The normalized hostname. See also IDN Charter IDN site IDNA specification ...
nsIInstallLocation
temLocation( in AString id ); Parameters id The GUID of the item. Return value The location of the item. getStageFile() Returns the most recently staged package (for example the last XPI or JAR in a directory) for an item and removes items that do not qualify. nsIFile getStageFile( in AString id ); Parameters id The ID of the staged package. Return value An nsIFile if the package exists
otherwise null. itemIsManagedIndependently() Determines whether or not an item's resources are managed by the Extension System or by some other user or process. For example, items linked to by text links are managed by the user, and items linked to from Registry Install Locations are usually managed by other applications or installers. boolean itemIsManagedIndependently( in AString id ); Parameters id ...
...y some other user or process. For example, items linked to by text links are managed by the user, and items linked to from Registry Install Locations are usually managed by other applications or installers. boolean itemIsManagedIndependently( in AString id ); Parameters id The GUID of the item. Return value true if the item's resources are managed independently of the Extension System, false
otherwise. removeFile() Removes a file from the stage. This cleans up the stage if there is nothing else left after the remove operation. void removeFile( in nsIFile file ); Parameters file The file to remove. stageFile() Stages the specified file by copying it to some location from where it can be retrieved later to complete installation. nsIFile stageFile( in nsIFile file, in AString id ); Para...
nsIJSID
er string Read only. The string representation of the internal nsID. valid boolean Read only. Returns true if the JSID has been initialised. Methods equals() This method determines if this nsIJSID has the same nsID as another nsIJSID. boolean equals( in nsIJSID other ); Parameters other The other nsIJSID to compare to. Return value true if the nsIJSID's are valid and have the same nsID,
otherwise false. Violates the XPCOM interface guidelines getID() const nsID* getID(); Parameters None. Return value A pointer to the internal nsID structure. initialize() Initializes the JSID. void initialize( in string idString ); Parameters idString The number to initialize the JSID, in string format, e.g. {00000000-0000-0000-c000-000000000046}. A JSID can only be initialized once. toString(...
...ructure. initialize() Initializes the JSID. void initialize( in string idString ); Parameters idString The number to initialize the JSID, in string format, e.g. {00000000-0000-0000-c000-000000000046}. A JSID can only be initialized once. toString() This methods returns a string representation of the object. string toString(); Parameters None. Return value The name of the JSID if it has one,
otherwise the string representation of its nsID. ...
nsILocalFile
ndRelativeNativePath( in ACString relativeFilePath ); Parameters relativeFilePath A native relative path. For security reasons, this cannot contain '..' or cannot start with a directory separator '/'. Must be in the native file system character set. Exceptions thrown NS_ERROR_FILE_UNRECOGNIZED_PATH Indicates that relativeFilePath incorrectly begins with a path separator character or
otherwise contains invalid characters. appendRelativePath() Appends a relative native path to the current path of the nsILocalFile object. void appendRelativePath( in AString relativeFilePath ); Parameters relativeFilePath A native relative path. For security reasons, this cannot contain '..' or cannot start with a directory separator '/' . Exceptions thrown NS_ERROR_FILE_UNRECOGNIZED_PATH...
...the current path of the nsILocalFile object. void appendRelativePath( in AString relativeFilePath ); Parameters relativeFilePath A native relative path. For security reasons, this cannot contain '..' or cannot start with a directory separator '/' . Exceptions thrown NS_ERROR_FILE_UNRECOGNIZED_PATH Indicates that relativeFilePath incorrectly begins with a path separator character or
otherwise contains invalid characters. getRelativeDescriptor() Returns a relative file path in an opaque, cross platform format. It is therefore not a native path. ACString getRelativeDescriptor( in nsILocalFile fromFile ); Parameters fromFile The file from which the descriptor is relative. There is no defined result if this parameter is null. Return value An opaque string value with undefin...
nsILoginManager
passed. fillForm() Fills out a form with login information, if appropriate information is available. Note: This method will attempt to fill out the form regardless of the setting of the signon.autofillForms preference. boolean fillForm( in nsIDOMHTMLFormElement aForm ); Parameters aForm The HTMLform to attempt to fill out. Return value true if the form was successfully filled out;
otherwise false. findLogins() Searches for logins matching the specified criteria. Called when looking for logins that might be applicable to a given form or authentication request. void findLogins( out unsigned long count, in AString aHostname, in AString aActionURL, in AString aHttpRealm, [retval, array, size_is(count)] out nsILoginInfo logins ); Parameters count The number of elements...
...ins = myLoginMgr.getAllLogins({}); getLoginSavingEnabled() Reports whether or not saving login information is enabled for a host. boolean getLoginSavingEnabled( in AString aHost ); Parameters aHost The hostname to check. This argument should be in the origin URL format, with no pathname. For example: "https://www.site.com". Return value true if login saving is enabled for the host,
otherwise false. modifyLogin() Modifies an existing login by replacing it with a new one. If newLoginData is a nsILoginInfo, all of the old login's nsILoginInfo properties are changed to the values from newLoginData (but the old login's nsILoginMetaInfo properties are unmodified). If newLoginData is a nsIPropertyBag, only the specified properties will be changed. The nsILoginMetaInfo properties of oldL...
nsIMsgDBView
dex The index of the new thread. nsMsgViewIndex is defined as a unsigned long in MailNewsTypes2.idl. navigateStatus() Indicates if the passed motion type is currently valid. boolean navigateStatus(in nsMsgNavigationTypeValue motion); Parameters motion The nsMsgNavigationTypeValue. Defined in ther interface: nsMsgNavigationType. Return values True if the motion is available. False
otherwise. getKeyAt() Gets the key for the message at a particular index. nsMsgKey getKeyAt(in nsMsgViewIndex index); Parameters index The index of the message. nsMsgViewIndex is defined as a unsigned long in MailNewsTypes2.idl. Return value The key of the message. nsMsgKey is defined as an unsigned long in MailNewsTypes2.idl. getFolderForViewIndex() Mainly for search. Gets the folder of th...
...e if the delete was successful. findIndexFromKey() Gets the index of a message with a particular key. nsMsgViewIndex findIndexFromKey(in nsMsgKey aMsgKey, in boolean aExpand); Parameters aMsgKey The Key of the message. nsMsgKey is defined as an unsigned long in MailNewsTypes2.idl. aExpand Whether or not to expand the thread or group the message is in.
Otherwise, the index may be the index of the thread and not the message. Return value The index of the message. nsMsgViewIndex is defined as a unsigned long in MailNewsTypes2.idl. ExpandAndSelectThreadByIndex() void ExpandAndSelectThreadByIndex(in nsMsgViewIndex aIndex, in boolean aAugment); Parameters aIndex The index of the thread to expand and select. nsMsg...
nsIMsgIncomingServer
Read only. canSearchMessages boolean Read only. canUndoDeleteOnServer boolean Read only. constructedPrettyName AString helper function to construct the pretty name in a server type specific way - for example, mail for foo@test.com, news on news.mozilla.org. Read only. defaultCopiesAndFoldersPrefsToServer boolean If the server supports Fcc/Sent/etc, default prefs can point to the server.
Otherwise, copies and folders prefs should point to Local Folders. By default this value is set to true via global pref 'allows_specialfolders_usage' (mailnews.js). For Nntp, the value is overridden to be false. If ISPs want to modify this value, they should do that in their rdf file by using this attribute. Please look at mozilla/mailnews/base/ispdata/aol.rdf for usage example. displayStartupPage boolea...
...e local mail store, such as "mailbox", "imap", or "news" used to construct URIs. Read only. loginAtStartUp boolean logonFallback boolean maxMessageSize long offlineSupportLevel long password ACString passwordPromptRequired boolean If the password for the server is available either via authentication in the current session or from password manager stored entries, return false.
Otherwise, return true. If password is obtained from password manager, set the password member variable. Read only. performingBiff boolean port long prettyName AString pretty name - should be "userid on hostname" if the pref is not set. realHostName ACString real hostname of the server (if server name is changed it is stored here) realUsername ACString real username of the server (if username...
nsINavBookmarkObserver
arentGUID ); Parameters aItemId The id of the item that was added. aParentId The id of the folder to which the item was added. aIndex The item's index in the folder. aItemType The type of the item that was added. This should be one of the nsINavBookmarksService.Type constants. aURI The URI of the item that was added when aItemType is TYPE_BOOKMARK, null
otherwise. aTitle The title of the added item. aDateAdded The stored date added value, in microseconds from the epoch. aGUID The unique ID associated with the item. aParentGUID The unique ID associated with the item's parent. onItemChanged() This method notifies this observer that an item's information has changed. It is called whenever any attributes like "title" are c...
...arameters aItemId The ID of the item that was removed. aParentId The ID of the folder from which the item was removed. aIndex The index of the item that was removed from the folder. aItemType The type of the item that was removed. This should be one of the nsINavBookmarksService.Type constants. aURI The URI of the added item if it was TYPE_BOOKMARK, null
otherwise. aGUID The unique ID associated with the item. aParentGUID The unique ID associated with the item's parent. onItemReplaced() Obsolete since Gecko 1.9 (Firefox 3) Notify this observer that a bookmark has been replaced. void onItemReplaced( in PRInt64 folder, in nsIURI item, in nsIURI newItem ); Parameters folder The folder in which the b...
nsIParentalControlsService
system presents user interface to handle the override request (such as an "enter an administrator's password" dialog box). boolean requestURIOverride( in nsIURI aTarget, in nsIInterfaceRequestor aWindowContext Optional ); Parameters aTarget The URI to be overridden. aWindowContext Optional The window generating the event. Return value true if the block was successfully overridden,
otherwise false. requestURIOverrides() Requests that a set of URIs be allowed through the parental control filters. This method may block while the operating system presents user interface to handle the override request (such as an "enter an administrator's password" dialog box). boolean requestURIOverrides( in nsIArray aTargets, in nsIInterfaceRequestor aWindowContext Optional ); Parameters a...
... ...
nsIPrincipal
ssing Description equals() Returns whether the other principal is equivalent to this principal. Principals are considered equal if they are the same principal, they have the same origin, or have the same certificate fingerprint ID. boolean equals( in nsIPrincipal other ); Parameters other The other principal to compare against. Return value true if the two principals are equivalent;
otherwise false. Native code only!getJSPrincipals Returns the JS equivalent of the principal. JSPrincipals getJSPrincipals( in JSContext cx ); Parameters cx Missing Description Return value Missing Description getPreferences() Returns the security preferences associated with this principal. void getPreferences( out string prefBranch, out string id, out string subjectName, out string ...
...e should consider a certificate principal for a given URI subsuming a codebase principal for the same URI? Not sure what the immediate benefit would be, but I think the setup could make some code (e.g. MaybeDowngradeToCodebase) clearer. boolean subsumes( in nsIPrincipal other ); Parameters other Missing Description Return value true if this principal subsumes the specified principal;
otherwise false. ...
nsIProtocolHandler
ol) is banned. When a URI containing this port number is encountered, this method is called to ask if the protocol handler wants to override the ban. boolean allowPort( in long port, in string scheme ); Parameters port The port for which an override is being requested. scheme The scheme for which an override is being requested. Return value Return true if the override is approved;
otherwise, return false. newChannel() Constructs a new channel from the given URI for this protocol handler. nsIChannel newChannel( in nsIURI aURI ); Parameters aURI The URI for which to construct a channel. Return value Return the newly constructed channel. newURI() Makes a URI object that is suitable for loading by this protocol, where the URI string is given as an UTF-8 string. The calle...
...aracter sequences may or may not be %xx escaped. aOriginCharset The character set of the document from which this URI string originated. This corresponds to the character set that should be used when communicating this URI to an origin server. If this is null, then UTF-8 encoding is assumed and no character transformation is not performed. aBaseURI If null, aSpec must specify an absolute URI.
Otherwise, aSpec may be resolved relative to aBaseURI, depending on the protocol. If the protocol has no concept of relative URIs, this parameter is ignored. Return value The new URI object suitable for loading using the protocol. See also nsIProxiedProtocolHandler Adding a New Protocol to Mozilla Writing a Firefox Protocol Handler Custom about: URLs - Similar to adding new protocol but adding on...
nsIProtocolProxyService
When this flag is passed to resolve, resolve may throw the exception NS_BASE_STREAM_WOULD_BLOCK to indicate that it failed due to this flag being present. Methods resolve() Deprecated since Gecko 18 This method has been removed in Firefox 18. Use resolveAsync instead Previous doc This method returns a nsIProxyInfo instance that identifies a proxy to be used for loading the given URI.
Otherwise, this method returns null indicating that a direct connection should be used. If this proxy is unavailable, getFailoverForProxy() may be called to determine the correct secondary proxy to be used. If the protocol handler for the given URI supports nsIProxiedProtocolHandler, then the nsIProxyInfo instance returned from resolve may be passed to the nsIProxiedProtocolHandler.newProxiedChannel() ...
...ts that do not correspond to a RESOLVE_ flag are reserved for future use. Return value An nsIProxyInfo object or null for a direct connection. Note: If PAC is configured, and the PAC file has not yet been loaded, then this method will return a nsIProxyInfo instance with a type of "unknown" to indicate to the consumer that asyncResolve should be used to wait for the PAC file to finish loading.
Otherwise, the consumer may choose to treat the result as type "direct" if desired. See nsIProxiedProtocolHandler.newProxiedChannel(). asyncResolve() This method is an asychronous version of the resolve method. Unlike resolve, this method is guaranteed not to block the calling thread waiting for DNS queries to complete. This method is intended as a substitute for resolve when the result is not needed im...
nsIPushService
etched nsIPushSubscription. Example pushService.getSubscription( "chrome://my-module/push", scriptSecurityManager.getSystemPrincipal(), (code, subscription) => { if (!Components.isSuccessCode(code)) { Cu.reportError("Error fetching subscription: " + code); return; } // `subscription == null` if the `(scope, principal)` pair doesn't have a // push subscription.
Otherwise, it's an instance of `nsIPushSubscription`. } ); unsubscribe() Drops an existing push subscription. void unsubscribe( in DOMString scope, in nsIPrincipal principal, in nsIUnsubscribeResultCallback callback ); Parameters scope The unique scope URL, as passed to nsIPushService.subscribe(). principal The subscription nsIPrincipal, as passed to nsIPushService.subscribe(). callbac...
...ription. } ); Receiving Push Messages Subscriptions created from privileged code use XPCOM observer notifications instead of service worker events. You can use the global nsIObserverService to listen for these notifications. Messages sent to system subscriptions are broadcasted to all push-message observers. Your nsIObserver should ensure the data parameter matches your subscription scope.
Otherwise, your code may try to handle messages meant for other subscriptions. Topic Subject Data Description Push API Counterpart push-message nsIPushMessage if the message has a payload; null for blank messages. Scope Fired when a push message is sent to a system subscription. ServiceWorkerGlobalScope.onpush push-subscription-change null Scope ...
nsITaskbarPreviewController
which are obtained immediately prior to calling this method. boolean drawPreview( in nsIDOMCanvasRenderingContext2D ctx ); Parameters ctx An nsIDOMCanvasRenderingContext2D object representing the drawing context into which the preview is to be rendered. Note that this context is not actually attached to a canvas element. Return value true if you want a frame drawn around the preview,
otherwise false. drawThumbnail() Invoked by the taskbar preview when it needs to draw the thumbnail in the taskbar's application preview window. boolean drawThumbnail( in nsIDOMCanvasRenderingContext2D ctx, in unsigned long width, in unsigned long height ); Parameters ctx An nsIDOMCanvasRenderingContext2D object representing the drawing context into which the thumbnail is to be rendered. Not...
...s to be rendered. Note that this context is not actually attached to a canvas element. width The width of the surface backing the drawing context. height The height of the surface backing the drawing context. Note: It's guaranteed that width / height will equal the thumbnailAspectRatio, within the margin of rounding errors. Return value true if you want a frame drawn around the thumbnail,
otherwise false. onActivate() Invoked when the user clicks on the tab preview. boolean onActivate(); Parameters None. Return value true if the top level window corresponding to the preview should be activated, false if activation is not accepted. onClick() Invoked when one of the buttons on the window preview's toolbar is clicked by the user. void onClick( in nsITaskbarPreviewButton button ); ...
nsIWindowsRegKey
lue The name of the n'th value under this key. getValueType() This method returns the type of the value with the given name. unsigned long getValueType( in AString name ); Parameters name The name of the value to query. Return value One of the "TYPE_" constants. hasChanged() boolean hasChanged(); Parameters None. Return value This method returns true if the key has changed and false
otherwise. This method will always return false if startWatching() was not called. hasChild() This method checks to see if the key has a child by the given name. boolean hasChild( in AString name ); Parameters name The name of the requested child key. Return value true if the key has a child by the given name. hasValue() This method checks to see if the key has a value by the given name. boole...
...eValue() This method removes the value with the given name. void removeValue( in AString name ); Parameters name The name of the value to be removed. startWatching() This method starts watching the key to see if any of its values have changed. The key must have been opened with mode including ACCESS_NOTIFY. If recurse is true, then this key and any of its descendant keys are watched.
Otherwise, only this key is watched. void startWatching( in boolean recurse ); Parameters recurse Indicates whether or not to also watch child keys. stopWatching() This method stops any watching of the key initiated by a call to startWatching(). This method does nothing if the key is not being watched. void stopWatching(); Parameters None. writeBinaryValue() This method writes the binary cont...
nsIZipReaderCache
nsIZipReader getInnerZip( in nsIFile zipFile, in AUTF8String zipEntry ); Parameters zipFile The zip file. zipEntry The zip entry. Return value The nsIZipReader for the given zip file. getZip() Returns a (possibly shared) cached nsIZipReader for a zip file. If the zip reader for the given file is not in the cache, a new nsIZipReader is opened (see nsIZipReader.open()).
Otherwise the previously created nsIZipReader is returned. Note: If nsIZipReader.close has been called on the shared nsIZipReader, this method will return the closed nsIZipReader nsIZipReader getZip( in nsIFile zipFile ); Parameters zipFile The zip file. Return value The nsIZipReader for the given zip file. init() Initializes a new zip reader cache. void init( in unsigned long cacheSize ); ...
...le ); Parameters zipFile The zip file. Return value The nsIZipReader for the given zip file. init() Initializes a new zip reader cache. void init( in unsigned long cacheSize ); Parameters cacheSize The number of released entries to maintain before beginning to throw some out. The number of outstanding entries can be much greater than this number, this is the count for those
otherwise unused entries. See also nsIZipReader ...
Weak reference
observer. After all, the observable must send messages to each observer, notifying it of the appropriate state changes. To do that, it will call a method on the observer, so it needs a pointer. And the call would fail if the pointer were allowed to dangle, therefore, the pointer should be a owning reference. This design, however, is flawed, as it holds the observer in existence longer than would
otherwise be necessary. The observer may only need a short life compared to the thing being observed. It might go away after the first interesting event, even. But in this design, by hitching its life to the observable, it is kept on life-support long past any need or use. What is actually needed in this case, is either out-of-band signaling, where when the observer wants to go away, it unregisters itself...
...MTypeInfo<nsISupportsWeakReference>::GetIID()) ) *aInstancePr = NS_STATIC_CAST(nsISupportsWeakReference*, this); // ... } Alternatives This technique is useful, but in situations where you need this, there are two alternatives which you may want to consider: You might hold an owning reference, but arrange to Release it out-of-band; this must be before the destructor, which would
otherwise never be called. You might hold a raw pointer (without AddRefing and Releaseing it), and avoid using it in cases where it might dangle. See also The source xpcom/base/nsIWeakReference.idl xpcom/glue/nsWeakReference.h xpcom/glue/nsWeakReference.cpp XPCOM ownership guidelines Using nsCOMPtr Original Document Information Author: Scott Collins Last Updated Date: Septem...
Debugger.Environment - Firefox Developer Tools
nvironment instance is live, the referent remains live. Garbage collection has no visible effect on Debugger.Environment instances. Accessor Properties of the Debugger.Environment Prototype Object A Debugger.Environment instance inherits the following accessor properties from its prototype: inspectable True if this environment is a debuggee environment, and can therefore be inspected. False
otherwise. All other properties and methods of Debugger.Environment instances throw if applied to a non-inspectable environment. type The type of this environment object, one of the following values: "declarative", indicating that the environment is a declarative environment record. Function calls, calls to eval, let blocks, catch blocks, and the like create declarative environment records. ...
...e no such object). Both "object" and "with" environments have object properties that provide the object whose properties they reflect as variable bindings. callee If this environment represents the variable environment (the top-level environment within the function, which receives var definitions) for a call to a functionf, then this property's value is a Debugger.Object instance referring tof.
Otherwise, this property's value is null. optimizedOut True if this environment is optimized out. False
otherwise. For example, functions whose locals are never aliased may present optimized-out environments. When true, getVariable returns an ordinary JavaScript object whose optimizedOut property is true on all bindings, and setVariable throws a ReferenceError. Function Properties of the Debugger.Envir...
Debugger.Object - Firefox Developer Tools
e Debugger.Object prototype A Debugger.Object instance inherits the following accessor properties from its prototype: proto The referent's prototype (as a new Debugger.Object instance), or null if it has no prototype. class A string naming the ECMAScript [[Class]] of the referent. callable true if the referent is a callable object (such as a function or a function proxy); false
otherwise. name The name of the referent, if it is a named function. If the referent is an anonymous function, or not a function at all, this is undefined. This accessor returns whatever name appeared after the function keyword in the source code, regardless of whether the function is the result of instantiating a function declaration (which binds the function to its name in the enclosing scope) or...
...rovides [DebuggerHostAnnotationsForFirefox annotations] for its host objects. Function Properties of the Debugger.Object prototype The functions described below may only be called with a this value referring to a Debugger.Object instance; they may not be used as methods of other kinds of objects. The descriptions use "referent" to mean "the referent of this Debugger.Object instance". Unless
otherwise specified, these methods are not invocation functions; if a call would cause debuggee code to run (say, because it gets or sets an accessor property whose handler is debuggee code, or because the referent is a proxy whose traps are debuggee code), the call throws a Debugger.DebuggeeWouldRun exception. getProperty(name) Return the value of the referent's property namedname, or undefined if i...
Using the Beacon API - Web APIs
tor.sendBeacon() The Beacon API's Navigator.sendBeacon() method sends a beacon request to the server in the global browsing context. The method takes two arguments: the URL and the data to send. The data argument is optional and its type may be an ArrayBufferView, Blob, DOMString, or FormData. If the browser successfully queues the request for delivery, the method returns true and returns false
otherwise. The following example specifies a handler for the load and beforeunload events. The handler calls sendBeacon() with the current URL. window.onload = window.onunload = function analytics(event) { if (!navigator.sendBeacon) return; var url = "https://example.com/analytics"; // Create the data to send var data = "state=" + event.type + "&location=" + location.href; // Send the beacon ...
..."success" : "fail"); } else { postMessage("Worker: self.navigator.sendBeacon is unsupported"); } } See Also Beacon API (Overview) Beacon standard Beacon CanIUse data ...
Beacon API - Web APIs
API's Navigator.sendBeacon() method is used to send a beacon of data to the server in the global browsing context. The method takes two arguments, the URL and the data to send in the request. The data argument is optional and its type may be an ArrayBufferView, Blob, DOMString, or FormData. If the browser successfully queues the request for delivery, the method returns "true" and returns "false"
otherwise. Worker context The Beacon API's Navigator.sendBeacon() method is used to send a beacon of data to the server from the worker global scope. The method takes two arguments, the URL and the data to send in the request. The data argument is optional and its type may be an ArrayBufferView, Blob, DOMString, or FormData. If the browser successfully queues the request for delivery, the method returns ...
... ...
CanvasRenderingContext2D.isPointInPath() - Web APIs
The algorithm by which to determine if a point is inside or outside the path. Possible values: "nonzero": The non-zero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to check against. If unspecified, the current path is used. Return value Boolean A Boolean, which is true if the specified point is contained in the current or specified path,
otherwise false. Examples Checking a point in the current path This example uses the isPointInPath() method to check if a point is within the current path. 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, ...
...nvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const result = document.getElementById('result'); ctx.rect(10, 10, 100, 100); ctx.fill(); result.innerText = ctx.isPointInPath(30, 70); Result Checking a point in the specified path Whenever you move the mouse, this example checks whether the cursor is in a circular Path2D path. If yes, the circle becomes green,
otherwise it is red. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Create circle const circle = new Path2D(); circle.arc(150, 75, 50, 0, 2 * Math.PI); ctx.fillStyle = 'red'; ctx.fill(circle); // Listen for mouse moves canvas.addEventListener('mousemove', function(event) { // Check whether point is inside circ...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
king of a path. Syntax ctx.isPointInStroke(x, y); ctx.isPointInStroke(path, x, y); Parameters x The x-axis coordinate of the point to check. y The y-axis coordinate of the point to check. path A Path2D path to check against. If unspecified, the current path is used. Return value Boolean A Boolean, which is true if the point is inside the area contained by the stroking of a path,
otherwise false. Examples Checking a point in the current path This example uses the isPointInStroke() method to check if a point is within the area of the current path's stroke. 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(...
...'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 the stroke of an elliptical Path2D path. If yes, the ellipse's stroke becomes green,
otherwise it is red. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Create ellipse const ellipse = new Path2D(); ellipse.ellipse(150, 75, 40, 60, Math.PI * .25, 0, 2 * Math.PI); ctx.lineWidth = 25; ctx.strokeStyle = 'red'; ctx.fill(ellipse); ctx.stroke(ellipse); // Listen for mouse moves canvas.addEventListener(...
Clients.openWindow() - Web APIs
w(url).then(function(windowClient) { // Do something with your WindowClient }); Parameters url A USVString representing the URL of the client you want to open in the window. Generally this value must be a URL from the same origin as the calling script. Return value A Promise that resolves to a WindowClient object if the URL is from the same origin as the service worker or a null value
otherwise. Examples // Send notification to OS if applicable if (self.Notification.permission === 'granted') { const notificationObject = { body: 'Click here to view your messages.', data: { url: self.location.origin + '/some/path' }, // data: { url: 'http://example.com' }, }; self.registration.showNotification('You\'ve got messages!', notificationObject); } // Notification click even...
... if (!hadWindowToFocus) clients.openWindow(e.notification.data.url).then(windowClient => windowClient ? windowClient.focus() : null); })); }); Specifications Specification Status Comment Service WorkersThe definition of 'Clients: openWindow' in that specification. Working Draft Initial definition. ...
Constraint validation API - Web APIs
ue is valid. If the element's value is not valid, it returns a localized validation message. This will be displayed in the UI if the element is the only form control with a validity problem; if a custom error message is set using setCustomValidity(), this will be shown. willValidate A read-only boolean property that returns true if the element is a candidate for constraint validation; and false
otherwise. Elements with the HTMLObjectElement interface are never candidates for constraint validation. Others may be barred from constraint validation depending on specific conditions. Methods checkValidity() Checks the element's value against its constraints. If the value is invalid, it fires an invalid event at the element and returns false;
otherwise it returns true. reportValidity() HTMLFormEl...
...lid, it fires an invalid event at the element and returns false;
otherwise it returns true. reportValidity() HTMLFormElement method Checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an invalid event at the element, returns false, and then reports the validity status to the user in whatever way the user agent has available.
Otherwise, it returns true. setCustomValidity(message) Sets a custom error message string to be shown to the user upon submitting the form, explaining why the value is not valid -- when a message is set, the validity state is set to invalid. To clear this state, invoke the function with an empty string passed as its argument. In this case the custom error message is cleared, the element is considered val...
DOMTokenList.contains() - Web APIs
Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then test for the existence of "c" in the list, and write the result into the <span>'s Node.textContent. ...
... Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then test for the existence of "c" in the list, and write the result into the <span>'s Node.textContent. ...
DataTransfer.mozUserCancelled - Web APIs
Example This example shows the use of the mozUserCancelled property in the dragend event handler. ...
... Example This example shows the use of the mozUserCancelled property in the dragend event handler. ...
Introduction to the DOM - Web APIs
whole DOM is available for use): <body onload="window.alert('Welcome to my home page!');"> Another example. This function creates a new H1 element, adds text to that element, and then adds the H1 to the tree for this document: <html> <head> <script> // run this function when the document is loaded window.onload = function() { // create a couple of elements in an
otherwise empty HTML page const heading = document.createElement("h1"); const heading_text = document.createTextNode("Big Head!"); heading.appendChild(heading_text); document.body.appendChild(heading); } </script> </head> <body> </body> </html> Fundamental data types This reference tries to describe the various objects and types in simple terms. But th...
...cise. To run examples that only demonstrate the basic relationship of the interface to the HTML elements, you may want to set up a test page in which interfaces can be easily accessed from scripts. The following very simple web page provides a <script> element in the header in which you can place functions that test the interface, a few HTML elements with attributes that you can retrieve, set, or
otherwise manipulate, and the web user interface necessary to call those functions from the browser. You can use this test page or create a similar one to test the DOM interfaces you are interested in and see how they work on the browser platform. You can update the contents of the test() function as needed, create more buttons, or add elements as necessary. <html> <head> <title>DOM Tests</title> <sc...
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
t use Javascript's "\s" because that includes non-breaking * spaces (and also some other characters). */ /** * Determine whether a node's text content is entirely whitespace. * * @param nod A node implementing the |CharacterData| interface (i.e., * a |Text|, |Comment|, or |CDATASection| node * @return True if all of the text content of |nod| is whitespace, *
otherwise false. */ function is_all_ws( nod ) { // Use ECMA-262 Edition 3 String and RegExp features return !(/[^\t\n\r ]/.test(nod.textContent)); } /** * Determine if a node should be ignored by the iterator functions. * * @param nod An object implementing the DOM1 |Node| interface. * @return true if the node is: * 1) A |Text| node that is all whitespace * 2...
...{ // Use ECMA-262 Edition 3 String and RegExp features return !(/[^\t\n\r ]/.test(nod.textContent)); } /** * Determine if a node should be ignored by the iterator functions. * * @param nod An object implementing the DOM1 |Node| interface. * @return true if the node is: * 1) A |Text| node that is all whitespace * 2) A |Comment| node * and
otherwise false. */ function is_ignorable( nod ) { return ( nod.nodeType == 8) || // A comment node ( (nod.nodeType == 3) && is_all_ws(nod) ); // a text node, all ws } /** * Version of |previousSibling| that skips nodes that are entirely * whitespace or comments. (Normally |previousSibling| is a property * of all DOM nodes that gives the sibling node, the node that is * a child of the sa...
EffectTiming.fill - Web APIs
nd backwards: The animation's effects should be reflected by the element(s) state prior to playing and retained after the animation has completed playing, in spite of and during any endDelay, delay and/or pending or finished playState. "auto" If the animation effect the fill mode is being applied to is a keyframe effect (KeyframeEffect or KeyframeEffectReadOnly), "auto" is equivalent to "none".
Otherwise, the result is "both". Examples Here are a few examples. Fill mode: none HTML content The HTML is pretty simple. We have a <div> named "main" which is a container for the element we'll be animating, which is a <div> with the ID "box". Below that, another <div> serves as a button that will trigger the animation to begin. <div class="main"> <div id="box"> <div id="text">Look! A box!</d...
...wo keyframes; the first defines what affect is applied to the element immediately after the animation first begins to play, and the second defines the effect applied to the element in the last moment before it ends. Those phrases are crucial. Let's look at why. The first keyframe says that when the animation begins, the element should be rotated 90? to the left. That means that unless we specify
otherwise using the fill property, the instant the animation is started the element will be rotated to the left 90?, and then it will animate smoothly from there. Since by default the box isn't rotated, The last keyframe says that the animation's final frame should draw the animation rotated 90? to the right from its original orientation. var boxRotationTiming = { duration: 2000, iterations: 1, fil...
Element: mousewheel event - Web APIs
o the top or left. Note: On macOS, the scroll distance (and therefore the value of detail) is computed based on the accelerated scroll distance. On Linux, 2 or -2 is set per native wheel event. wheelDelta, wheelDeltaX and wheelDeltaY value The wheelDelta attribute value is an abstract value which indicates how far the wheel turned. If the wheel has rotated away from the user, it's positive,
otherwise negative. This means that the delta value sign is different from DOM Level 3 Event's wheel. However, the meaning of the amount of these values is not the same between browsers. See following explanation for the detail. IE and Opera (Presto) only support wheelDelta attribute and do not support horizontal scroll. The wheelDeltaX attribute value indicates the wheelDelta attribute value along the h...
...wever, the meaning of the amount of these values is not the same between browsers. See following explanation for the detail. IE and Opera (Presto) only support wheelDelta attribute and do not support horizontal scroll. The wheelDeltaX attribute value indicates the wheelDelta attribute value along the horizontal axis. When a user operates the device for scrolling to right, the value is negative.
Otherwise, i.e., if it's to left, the value is positive. The wheelDeltaY attribute value indicates the wheelDelta attribute value along the vertical axis. The sign of the value is the same as the wheelDelta attribute value. Internet Explorer The value is the same as the delta value of Windows' WM_MOUSEWHEEL or WM_MOUSEHWHEEL. It means that if the mouse wheel doesn't support high resolution scroll, the v...
EventTarget.addEventListener() - Web APIs
, null, options); window.removeEventListener("test", null, options); } catch(err) { passiveSupported = false; } This creates an options object with a getter function for the passive property; the getter sets a flag, passiveSupported, to true if it gets called. That means that if the browser checks the value of the passive property on the options object, passiveSupported will be set to true;
otherwise, it will remain false. We then call addEventListener() to set up a fake event handler, specifying those options, so that the options will be checked if the browser recognizes an object as the third parameter. Then, we call removeEventListener() to clean up after ourselves. (Note that handleEvent() is ignored on event listeners that aren't called.) You can check whether any option is supported th...
...ner that uses the options in question, you can do something like this: someElement.addEventListener("mouseup", handleMouseUp, passiveSupported ? { passive: true } : false); Here we're adding a listener for the mouseup event on the element someElement. For the third parameter, if passiveSupported is true, we're specifying an options object with passive set to true;
otherwise, we know that we need to pass a Boolean, and we pass false as the value of the useCapture parameter. If you'd prefer, you can use a third-party library like Modernizr or Detect It to do this test for you. You can learn more from the article about EventListenerOptions from the Web Incubator Community Group. Examples Add a simple listener This example demonstrates how to use addEventListener()...
FetchEvent.preloadResponse - Web APIs
Example This code snippet is from the navigation preload page. The ServiceWorkerGlobalScope.onfetch event handler listens for the fetch event. When fired, pass a promise that back to the controlled page to FetchEvent.respondWith(). ...
... Example This code snippet is from the navigation preload page. The ServiceWorkerGlobalScope.onfetch event handler listens for the fetch event. When fired, pass a promise that back to the controlled page to FetchEvent.respondWith(). ...
FetchEvent.respondWith() - Web APIs
L. The way the HTML specification handles redirects for navigations ends up using the request URL for the resulting Window.location. This means sites can still provide an "alternate" view of a web page when offline without changing the user-visible URL. Syntax fetchEvent.respondWith( // Promise that resolves to a Response. ); Parameters A Response or a Promise that resolves to a Response.
Otherwise, a network error is returned to Fetch. Return value undefined. Exceptions Exception Notes NetworkError A network error is triggered on certain combinations of FetchEvent.request.mode and Response.type values, as hinted at in the "global rules" listed above. InvalidStateError The event has not been dispatched or respondWithWith() has already been invoke...
... NetworkError A network error is triggered on certain combinations of FetchEvent.request.mode and Response.type values, as hinted at in the "global rules" listed above. InvalidStateError The event has not been dispatched or respondWithWith() has already been invoked. Examples This fetch event tries to return a response from the cache API, falling back to the network
otherwise. addEventListener('fetch', event => { // Prevent the default, and handle the request ourselves. event.respondWith(async function() { // Try to get the response from a cache. const cachedResponse = await caches.match(event.request); // Return it if we found one. if (cachedResponse) return cachedResponse; // If we didn't find a match in the cache, use the network. retur...
Using files from web applications - Web APIs
ileElem) { fileElem.click(); } }, false); You can style the new button for opening the file picker as you wish. Using a label element to trigger a hidden file input element To allow opening the file picker without using JavaScript (the click() method), a <label> element can be used. Note that in this case the input element must not be hidden using display: none (nor visibility: hidden),
otherwise the label would not be keyboard-accessible. Use the visually-hidden technique instead. Consider this HTML: <input type="file" id="fileElem" multiple accept="image/*" class="visually-hidden"> <label for="fileElem">Select some files</label> and this CSS: .visually-hidden { position: absolute !important; height: 1px; width: 1px; overflow: hidden; clip: rect(1px, 1px, 1px, 1px); } /* S...
... info.innerHTML = this.files[i].name + ": " + this.files[i].size + " bytes"; li.appendChild(info); } } } This starts by fetching the URL of the <div> with the ID fileList. This is the block into which we'll insert our file list, including thumbnails. If the FileList object passed to handleFiles() is null, we simply set the inner HTML of the block to display "No files selected!".
Otherwise, we start building our file list, as follows: A new unordered list (<ul>) element is created. The new list element is inserted into the <div> block by calling its Node.appendChild() method. For each File in the FileList represented by files: Create a new list item (<li>) element and insert it into the list. Create a new image (<img>) element. Set the image's source to a new objec...
Guide to the Fullscreen API - Web APIs
ence of the requestFullscreen() method before calling it. Presentation differences It's worth noting a key difference here between the Gecko and WebKit implementations at this time: Gecko automatically adds CSS rules to the element to stretch it to fill the screen: "width: 100%; height: 100%". WebKit doesn't do this; instead, it centers the fullscreen element at the same size in a screen that's
otherwise black. To get the same fullscreen behavior in WebKit, you need to add your own "width: 100%; height: 100%;" CSS rules to the element yourself: #myvideo:-webkit-full-screen { width: 100%; height: 100%; } On the other hand, if you're trying to emulate WebKit's behavior on Gecko, you need to place the element you want to present inside another element, which you'll make fullscreen instead, an...
...nt of such an element) won't work. Instead, the element which requested fullscreen will receive a mozfullscreenerror event. When a fullscreen request fails, Firefox will log an error message to the Web Console explaining why the request failed. In Chrome and newer versions of Opera however, no such warning is generated. Note: Fullscreen requests need to be called from within an event handler or
otherwise they will be denied. Getting out of full screen mode The user always has the ability to exit fullscreen mode of their own accord; see Things your users want to know. You can also do so programmatically by calling the Document.exitFullscreen() method. Other information The Document provides some additional information that can be useful when developing fullscreen web applications: Documen...
Fullscreen API - Web APIs
ent has been placed into, or removed from, full-screen mode. Element.onfullscreenerror An event handler for the fullscreenerror event when sent to an element which has encountered an error while transitioning into or out of full-screen mode. Obsolete properties Document.fullscreen A Boolean value which is true if the document has an element currently being displayed in full-screen mode;
otherwise, this returns false. Note: Use the fullscreenElement property on the Document or ShadowRoot instead; if it's not null, then it's an Element currently being displayed in full-screen mode. Events The Fullscreen API defines two events which can be used to detect when full-screen mode is turned on and off, as well as when errors occur during the process of changing between full-screen and windo...
...xitFullscreen(); } } } This starts by looking at the value of the document's fullscreenElement attribute. In a real-world deployment, at this time, you'll want to check for prefixed versions of this (mozFullScreenElement, msFullscreenElement, or webkitFullscreenElement, for example). If the value is null, the document is currently in windowed mode, so we need to switch to full-screen mode;
otherwise, it's the element that's currently in full-screen mode. Switching to full-screen mode is done by calling Element.requestFullscreen() on the <video> element. If full-screen mode is already active (fullscreenElement is not null), we call exitFullscreen() on the document to shut off full-screen mode. Specifications Specification Status Fullscreen API Living Standard ...
HTMLElement.hidden - Web APIs
This is quite different from using the CSS property display to control the visibility of an element. The hidden property applies to all presentation modes and should not be used to hide content that is meant to be directly accessible to the user. ...
...een canvas as a drawing buffer Inappropriate use cases include: Hiding panels in a tabbed dialog box Hiding content in one presentation while intending it to be visible in others Elements that are not hidden must not link to elements which are. Syntax isHidden = HTMLElement.hidden; HTMLElement.hidden = true | false; Value A Boolean which is true if the element is hidden from view;
otherwise, the value is false. Example Here's an example where a hidden block is used to contain a thank you message that is displayed after a user agrees to an unusual request. JavaScript document.getElementById("okButton") .addEventListener("click", function() { document.getElementById("welcome").hidden = true; document.getElementById("awesome").hidden = false; }, false); This code sets ...
HTMLMediaElement - Web APIs
rns a MediaKeys object or null. MediaKeys is a set of keys that an associated HTMLMediaElement can use for decryption of media data during playback. HTMLMediaElement.mozAudioCaptured Read only Returns a Boolean. Related to audio stream capture. HTMLMediaElement.mozFragmentEnd Is a double that provides access to the fragment end time if the media element has a fragment URI for currentSrc,
otherwise it is equal to the media duration. HTMLMediaElement.mozFrameBufferLength Is a unsigned long that indicates the number of samples that will be returned in the framebuffer of each MozAudioAvailable event. This number is a total for all channels, and by default is set to be the number of channels * 1024 (e.g., 2 channels * 1024 samples = 2048 total). The mozFrameBufferLength property can b...
...before the audio has started or MozAudioAvailable events have begun firing. HTMLMediaElement.mozSampleRate Read only Returns a double representing the number of samples per second that will be played. For example, 44100 samples per second is the sample rate used by CD audio. HTMLMediaElement.muted Is a Boolean that determines whether audio is muted. true if the audio is muted and false
otherwise. HTMLMediaElement.networkState Read only Returns a unsigned short (enumeration) indicating the current state of fetching the media over the network. HTMLMediaElement.paused Read only Returns a Boolean that indicates whether the media element is paused. HTMLMediaElement.playbackRate Is a double that indicates the rate at which the media is being played back. HTMLMediaElement.played Read o...
HTMLOutputElement - Web APIs
enting the default value of the element, initially the empty string. HTMLOutputElement.formRead only An HTMLFormElement indicating the form associated with the control, reflecting the form HTML attribute if it is defined. HTMLOutputElement.htmlForRead only A DOMTokenList reflecting the for HTML attribute, containing a list of IDs of other elements in the same document that contribute to (or
otherwise affect) the calculated value. HTMLOutputElement.labelsRead only A NodeList of <label> elements associated with the element. HTMLOutputElement.name A DOMString reflecting the name HTML attribute, containing the name for the control that is submitted with form data. HTMLOutputElement.typeRead only The DOMString "output". HTMLOutputElement.validationMessageRead only A DOMString representi...
...s in default mode when the descendants of the element are changed in any way, the defaultValue property is set to the value of the textContent property. Resetting the form puts the element into default mode, and sets the textContent property to the value of the defaultValue property. Value mode The element goes into value mode when the contents of the value property are set. The value property
otherwise behaves like the textContent property. When the element is in value mode, the default value is accessible only through the defaultValue property. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLOutputElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLOutputElement' in that specificatio...
HTMLSelectElement - Web APIs
llection representing the set of <option> elements that are selected. HTMLSelectElement.size A long reflecting the size HTML attribute, which contains the number of visible items in the control. The default is 1, unless multiple is true, in which case it is 4. HTMLSelectElement.typeRead only A DOMString represeting the form control's type. When multiple is true, it returns "select-multiple";
otherwise, it returns "select-one". HTMLSelectElement.validationMessageRead only A DOMString representing a localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the empty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints. HTMLSelectElement.validityRead only A ...
...pty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints. HTMLSelectElement.validityRead only A ValidityState reflecting the validity state that this control is in. HTMLSelectElement.value A DOMString reflecting the value of the form control. Returns the value property of the first selected option element if there is one,
otherwise the empty string. HTMLSelectElement.willValidateRead only A Boolean that indicates whether the button is a candidate for constraint validation. It is false if any conditions bar it from constraint validation. Methods This interface inherits the methods of HTMLElement, and of Element and Node. HTMLSelectElement.add() Adds an element to the collection of option elements for this select el...
Basic concepts - Web APIs
database A repository of information, typically comprising one or more object stores. Each database must have the following: Name. This identifies the database within a specific origin and stays constant throughout its lifetime. The name can be any string value (including an empty string). Current version. When a database is first created, its version is the integer 1 if not specified
otherwise. Each database can have only one version at any given time. durable In Firefox, IndexedDB used to be durable, meaning that in a readwrite transaction IDBTransaction.oncomplete was fired only when all data was guaranteed to have been flushed to disk. As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see bug 1112702), which is the same...
...ich data is stored in the database. The object store persistently holds records, which are key-value pairs. Records within an object store are sorted according to the keys in an ascending order. Every object store must have a name that is unique within its database. The object store can optionally have a key generator and a key path. If the object store has a key path, it is using in-line keys;
otherwise, it is using out-of-line keys. For the reference documentation on object store, see IDBObjectStore. version When a database is first created, its version is the integer 1. Each database has one version at a time; a database can't exist in multiple versions at once. The only way to change the version is by opening it with a greater version than the current one. This will start a versionchang...
MediaCapabilitiesInfo - Web APIs
er encoding or decoding such media would be smooth and power efficient. Properties The MediaCapabilitiesInfo interface contains three Boolean attribues: supported: Given the properties defined in the MediaConfiguration, can the specified piece of media content be encoded (if MediaEncodingConfiguration is set) or decode (if MediaDecodingConfiguration is set) at all? If yes, supported is true.
Otherwise, it is false. smooth: Given the properties defined in the MediaConfiguration, will the playback of the specified piece of media be high quality? Will it be smooth? If supported is true, and playback will be smooth, smooth is true,
Otherwise, is it false. powerEfficient: Given the properties defined in the MediaConfiguration, will the playback of the specified piece of media be power efficient?
... Browsers will report a supported media configuration as smooth and powerEfficient until stats on this device have been recorded. All supported audio codecs are reported to be power efficient. ...
MediaDevices.getUserMedia() - Web APIs
age loaded using HTTPS or the file:/// URL scheme, or a page loaded from localhost. In addition, user permission is always required to access the user's audio and video inputs. Only a window's top-level document context for a valid origin can even request permission to use getUserMedia(), unless the top-level context expressly grants permission for a given <iframe> to do so using Feature Policy.
Otherwise, the user will never even be asked for permission to use the input devices. For additional details on these requirements and rules, how they are reflected in the context in which your code is running, and about how browsers manage user privacy and security issues, read on. User privacy As an API that may involve significant privacy concerns, getUserMedia() is held by the specification to very ...
... // First get ahold of the legacy getUserMedia, if present var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia; // Some browsers just don't implement it - return a rejected promise with an error // to keep a consistent interface if (!getUserMedia) { return Promise.reject(new Error('getUserMedia is not implemented in this browser')); } //
Otherwise, wrap the call to the old navigator.getUserMedia with a Promise return new Promise(function(resolve, reject) { getUserMedia.call(navigator, constraints, resolve, reject); }); } } navigator.mediaDevices.getUserMedia({ audio: true, video: true }) .then(function(stream) { var video = document.querySelector('video'); // Older browsers may not have srcObject if ("srcObject" in v...
MediaRecorder.onerror - Web APIs
r an error occurs during the recorder's lifetime. In addition to other general errors that might occur, the following errors are specifically possible when using the MediaStream Recording API; to determine which occurred, check the value of MediaRecorderErrorEvent.error.name. InvalidStateError An attempt was made to stop or pause or an inactive recorder, start or resume an active recorder, or
otherwise manipulate the MediaRecorder while in the wrong state. This exception can also occur when a request is made on a source that has been deleted or removed. SecurityError The MediaStream is configured to disallow recording. This may be the case, for example, with sources obtained using getUserMedia() when the user denies permission to use an input device. This also happens when a MediaStreamTrack...
...within the stream is marked as isolated due to the peerIdentity constraint on the source stream. NotSupportedError An attempt was made to instantiate a MediaRecorder using a MIME type that isn't supported on the user's device; one or more of the requested container, codecs, or profiles as well as other information may be invalid. UnknownError An non-security related error occurred that cannot
otherwise be categorized. Recording stops, the MediaRecorder's state becomes inactive, one last dataavailable event is sent to the MediaRecorder with the remaining received data, and finally a stop event is sent. These errors may occur either directly because of a call to a MediaRecorder method, or indirectly due to a problem arising during the recording process. Example This example creates a new Medi...
active - Web APIs
Example In this example, a new stream whose source is the user's local camera and microphone is requested using getUserMedia(). ...
... Example In this example, a new stream whose source is the user's local camera and microphone is requested using getUserMedia(). When that stream becomes available (that is, when the returned Promise is fulfilled, a button on the page is updated based on whether or not the stream is currently active. ...
MediaStreamTrack - Web APIs
her the track is unable to provide media data due to a technical issue. Note: You can implement standard "mute" functionality by setting enabled to false, and unmute the media by setting it back to true again. MediaStreamTrack.readonly Read only Returns a Boolean value with a value of true if the track is readonly (such a video file source or a camera that settings can't be modified), false
otherwise. MediaStreamTrack.readyState Read only Returns an enumerated value giving the status of the track. This will be one of the following values: "live" which indicates that an input is connected and does its best-effort in providing real-time data. In that case, the output of data can be switched on or off using the enabled attribute. "ended" which indicates that the input is not giving any ...
... input is connected and does its best-effort in providing real-time data. In that case, the output of data can be switched on or off using the enabled attribute. "ended" which indicates that the input is not giving any more data and will never provide new data. MediaStreamTrack.remote Read only Returns a Boolean with a value of true if the track is sourced by a RTCPeerConnection, false
otherwise. Methods MediaStreamTrack.applyConstraints() Lets the application specify the ideal and/or ranges of acceptable values for any number of the available constrainable properties of the MediaStreamTrack. MediaStreamTrack.clone() Returns a duplicate of the MediaStreamTrack. MediaStreamTrack.getCapabilities() Returns the a list of constrainable properties available for the MediaStreamTrack. ...
PaymentRequest.canMakePayment() - Web APIs
const details = { total: { label: "Total", amount: { currency: "USD", value: "0.00", }, }, }; const supportsApplePay = new PaymentRequest( [{ supportedMethods: "https://apple.com/apple-pay" }], details ).canMakePayment(); // Supports Apple Pay? ...
... Candidate Recommendation Initial definition. ...
PointerEvent.isPrimary - Web APIs
In a multi-pointer scenario (such as a touch screen that supports more than one touch point), this property is used to identify a master pointer among the set of active pointers for each pointer type. Only a primary pointer will produce compatibility mouse events. ...
...l produce pointers that are both considered primary. If there are multiple primary pointers, these pointers will all produce compatibility mouse events (see Pointer_events for more information about pointer, mouse and touch interaction). Syntax var isPrimary = pointerEvent.isPrimary; Return value isPrimary Returns true if the pointer for this event is the primary pointer and returns false
otherwise. Example This example illustrates using the value of isPrimary to call the appropriate processing function. target.addEventListener('pointerdown', function(event) { if (event.isPrimary) process_primary_pointer(event); else process_secondary_pointer(event); }, false); Specifications Specification Status Comment Pointer Events - Level 2The definition ...
RTCPeerConnection.createDataChannel() - Web APIs
priate. Default: null. maxRetransmits Optional The maximum number of times the user agent should attempt to retransmit a message which fails the first time in unreliable mode. While this value is a16-bit unsigned number, each user agent may clamp it to whatever maximum it deems appropriate. Default: null. protocol Optional The name of the sub-protocol being used on the RTCDataChannel, if any;
otherwise, the empty string (""). Default: empty string, "". This string may not be longer than 65,535 bytes. negotiated Optional By default (false), data channels are negotiated in-band, where one side calls createDataChannel, and the other side listens to the RTCDataChannelEvent event using the ondatachannel EventHandler . Alternatively (true), they can be negotiated out of-band, where both sides call...
...5534. If you don't include this option, the user agent will select an ID for you. The options which can be configured using the RTCDataChannelInit dictionary represent the script-settable subset of the properties on the RTCDataChannel interface. Return value A new RTCDataChannel object with the specified label, configured using the options specified by options if that parameter is included;
otherwise, the defaults listed above are established. Exceptions InvalidStateError The RTCPeerConnection is closed. TypeError This can happen in a couple of situations: The label and/or protocol string is too long; these cannot be longer than 65,535 bytes (bytes, rather than characters). The id is 65535. While this is a valid unsigned 16-bit value, it's not a permitted value for id. Synta...
RTCPeerConnection.createOffer() - Web APIs
peer the opportunity to try to send audio. If this value is false, the remote peer will not be offered to send audio data, even if the local side will be sending audio data. If this value is true, the remote peer will be offered to send audio data, even if the local side will not be sending audio data. The default behavior is to offer to receive audio only if the local side is sending audio, not
otherwise. To emulate this behavior in modern implementations, the presence of this member with a value false, will set the direction of all existing audio transceivers to exclude reception (i.e. set to either "sendonly" or "inactive"). In modern implementations, the presence of this member with a value true, will ensure there is at least one transceiver set to receive audio that has not been stopped, an...
... peer the opportunity to try to send video. If this value is false, the remote peer will not be offered to send video data, even if the local side will be sending video data. If this value is true, the remote peer will be offered to send video data, even if the local side will not be sending video data. The default behavior is to offer to receive video only if the local side is sending video, not
otherwise. To emulate this behavior in modern implementations, the presence of this member with a value false, will set the direction of all existing video transceivers to exclude reception (i.e. set to either "sendonly" or "inactive"). In modern implementations, the presence of this member with a value true, will ensure there is at least one transceiver set to receive video that has not been stopped, an...
Request.cache - Web APIs
equestCache value. The available values are: default -- The browser looks for a matching request in its HTTP cache. If there is a match and it is fresh, it will be returned from the cache. If there is a match but it is stale, the browser will make a conditional request to the remote server. If the server indicates that the resource has not changed, it will be returned from the cache.
Otherwise the resource will be downloaded from the server and the cache will be updated. If there is no match, the browser will make a normal request, and will update the cache with the downloaded resource. no-store -- The browser fetches the resource from the remote server without first looking in the cache, and will not update the cache with the downloaded resource. reload -- The browser fetche...
...ce from the remote server without first looking in the cache, but then will update the cache with the downloaded resource. no-cache -- The browser looks for a matching request in its HTTP cache. If there is a match, fresh or stale, the browser will make a conditional request to the remote server. If the server indicates that the resource has not changed, it will be returned from the cache.
Otherwise the resource will be downloaded from the server and the cache will be updated. If there is no match, the browser will make a normal request, and will update the cache with the downloaded resource. force-cache -- The browser looks for a matching request in its HTTP cache. If there is a match, fresh or stale, it will be returned from the cache. If there is no match, the browser wi...
TextEncoder.prototype.encodeInto() - Web APIs
ircumstance that the optimistic prediction was wrong. If the output is expected to be long-lived, it makes sense to compute minimum allocation roundUpToBucketSize(s.length), the maximum allocation size s.length * 3, and to have a chosen (as a tradeoff between memory usage and speed) threshold t such that if roundUpToBucketSize(s.length) + t >= s.length * 3, you simply allocate for s.length * 3.
Otherwise, first allocate for roundUpToBucketSize(s.length) and convert. If the read item it the return dictionary is s.length, the conversion is done. If not, reallocate the target buffer to written + (s.length - read) * 3 and then convert the rest by taking a substring of s starting from index read and a subbuffer of the target buffer starting from index written. Above roundUpToBucketSize() is a functio...
...then convert the rest by taking a substring of s starting from index read and a subbuffer of the target buffer starting from index written. Above roundUpToBucketSize() is a function that rounds up to the allocator bucket size. For example, if your Wasm allocator is known to use power-of-two buckets, roundUpToBucketSize() should return the argument if it is a power-of-two or the next power-of-two
otherwise. If the behavior of the Wasm allocator is unknown, roundUpToBucketSize() should be an identity function. If the behavior of your allocator is unknown, you might want to have up to two reallocation steps and make the the first reallocation step multiply the remaining unconverted length by two instead of three. However, in that case, it makes sense not to implement the usual multiplying by two of ...
WebRTC connectivity - Web APIs
s currently under consideration following a call to setLocalDescription() or setRemoteDescription(), respectively. When reading the description (returned by RTCPeerConnection.localDescription and RTCPeerConnection.remoteDescription), the returned value is the value of pendingLocalDescription/pendingRemoteDescription if there's a pending description (that is, the pending description isn't null);
otherwise, the current description (currentLocalDescription/currentRemoteDescription) is returned. When changing the description by calling setLocalDescription() or setRemoteDescription(), the specified description is set as the pending description, and the WebRTC layer begins to evaluate whether or not it's acceptable. Once the proposed description has been agreed upon, the value of currentLocalDescripti...
... error might occur that prevents negotiation at all. There may be permissions issues or other problems as well, for that matter. ICE rollbacks When renegotiating a connection that's already active and a situation arises in which the negotiation fails, you don't really want to kill the already-running call. After all, you were most likely just trying to upgrade or downgrade the connection, or to
otherwise make adaptations to an ongoing session. Aborting the call would be an excessive reaction in that situation. Instead, you can initiate an ICE rollback. A rollback restores the SDP offer (and the connection configuration by extension) to the configuration it had the last time the connection's signalingState was stable. To programmatically initiate a rollback, send a description whose type is roll...
Writing WebSocket servers - Web APIs
lly require a secure connection for WebSockets, although they may offer an exception for local devices. The handshake is the "Web" in WebSockets. It's the bridge from HTTP to WebSockets. In the handshake, details of the connection are negotiated, and either party can back out before completion if the terms are unfavorable. The server must be careful to understand everything the client asks for,
otherwise security issues can occur. Tip: The request-uri (/chat here) has no defined meaning in the spec. So, many people use it to let one server handle multiple WebSocket applications. For example, example.com/chat could invoke a multiuser chat app, while /game on the same server might invoke a multiplayer game. Client handshake request Even though you're building a server, a client still has to s...
...ow to interpret the payload data: 0x0 for continuation, 0x1 for text (which is always encoded in UTF-8), 0x2 for binary, and other so-called "control codes" that will be discussed later. In this version of WebSockets, 0x3 to 0x7 and 0xB to 0xF have no meaning. The FIN bit tells whether this is the last message in a series. If it's 0, then the server keeps listening for more parts of the message;
otherwise, the server should consider the message delivered. More on this later. Decoding Payload Length To read the payload data, you must know when to stop reading. That's why the payload length is important to know. Unfortunately, this is somewhat complicated. To read it, follow these steps: Read bits 9-15 (inclusive) and interpret that as an unsigned integer. If it's 125 or less, then that's the l...
Movement, orientation, and motion: A WebXR example - Web APIs
z: axialDistance}, {x: inverseOrientation[0], y: inverseOrientation[1], z: inverseOrientation[2], w: inverseOrientation[3]}); mat4.copy(mouseMatrix, newTransform.matrix); return refSpace.getOffsetReferenceSpace(newTransform); } If all the input offsets are zero, we just return the original reference space.
Otherwise, we create from the orientation changes in mousePitch and mouseYaw a quaternion specifying the inverse of that orientation, so that applying the inverseOrientation to the cube will correctly appear to reflect the viewer's movement. Then it's time to create a new XRRigidTransform object representing the transform that will be used to create the new XRReferenceSpace for the moved and/or re-orient...
...e image's dimensions aren't both powers of two (see the isPowerOf2() function), mipmapping is disabled and wrapping is clamped to the edges. This is because optimized rendering of mipmapped textures only works for textures whose dimensions are powers of two in WebGL 1. WebGL 2 supports arbitratily-sized textures for mipmapping. isPowerOf2() Returns true if the specified value is a power of two;
otherwise returns false. Putting it all together When you take all of this code and add in the HTML and the other JavaScript code not included above, you get what you see when you try out this example on Glitch. Remember: as you wander around, if you get lost, just hit the R key to reset yourself to the beginning. A tip: if you don't have an XR device, you may be able to get some of the 3D effect if yo...
Rendering and the WebXR frame animation callback - Web APIs
revious frame is still being drawn to the screen. As a result, you wind up with the visual effect of the top part of the screen showing the new frame, while the bottom part of the frame shows some combination of the previous frame and possibly even the frame before that one. Your mission, then, is to keep your code tight and lightweight enough that you don't overrrun the time available to you or
otherwise cause dropped frames or excessively abuse the main thread. For these reasons, unless your renderer is fairly small and lightweight, with little to do, you should consider offloading everything you can to a worker so you can be computing the next frame while the browser handles other things. By simply having your computations and data ready before the frame is actually called for, you can make yo...
...mes there may be cars or other vehicles, with moving parts to animate including the wheels. If there's water in the scene, it needs ripples or waves to look realistic. Parts of structures may be moving, such as doors, walls and floors (for some types of games), and so forth. Another common source of motion is the player themself. After interpreting inputs from the controls (both XR-affliated and
otherwise), you need to apply those changes to the scene in order to simulate the user's movement. See the article Movement, orientation, and motion for details and a thorough example of how this works. Next steps Once you've got your renderer written--or at least got something that works, even if it's not finished--you can begin to deal with the camera and its movement through the scene. This is covered...
Window.open() - Web APIs
isting window. In this case the return value of the method is the existing window and windowFeatures is ignored. Providing an empty string for url is a way to get a reference to an open window by its name without changing the window's location. On Firefox and Chrome (at least), this only works from the same parent, ie. if the current window is the opener of the window you try to get an handle on.
Otherwise the call to window.open() will just create a new window. To open a new window on every call of window.open(), use the special value _blank for windowName. Note on the use of window.open() to reopen an existing window with name windowName : This functionality is not valid for all browsers and more with variable conditions. Firefox (50.0.1) functions as described: from the same domain+port reope...
...ill re-use an already opened one" >Firefox FAQ</a></p> FAQ How can I prevent the confirmation message asking the user whether they want to close the window? You cannot. New windows not opened by javascript cannot as a rule be closed by JavaScript. The JavaScript Console in Mozilla-based browsers will report the warning message: "Scripts may not close windows that were not opened by script."
Otherwise the history of URLs visited during the browser session would be lost. More on the window.close() method How can I bring back the window if it is minimized or behind another window? First check for the existence of the window object reference of such window and if it exists and if it has not been closed, then use the focus() method. There is no other reliable way. You can examine an example exp...
Window.showModalDialog() - Web APIs
riant containing values passed to the dialog; these are made available in the window object's window.dialogArguments property. options is an optional string specifying window ornamentation for the dialog, using one or more semicolon delimited values: Syntax Description center: {on | off | yes | no | 1 | 0 } If on, yes, or 1, the dialog window is centered on the desktop;
otherwise it's hidden. Default is yes. dialogheight: height The height of the dialog box in pixels. dialogleft: left Distance of the dialog box from the left edge of the desktop. dialogwidth: width The width of the dialog box in pixels. dialogtop: top Distance of the dialog box from the top edge of the desktop. resizable: {on | off | yes | no | 1 | 0...
...pixels. dialogleft: left Distance of the dialog box from the left edge of the desktop. dialogwidth: width The width of the dialog box in pixels. dialogtop: top Distance of the dialog box from the top edge of the desktop. resizable: {on | off | yes | no | 1 | 0 } If this argument's value is on, yes, or 1, the dialog window can be resized by the user;
otherwise its size is fixed. The default value is no. scroll: {on | off | yes | no | 1 | 0 } If on, yes, or 1, the dialog window has scroll bars;
otherwise its size is fixed. Default is no. Note: Firefox does not implement the dialogHide, edge, status, or unadorned arguments. Examples Try out showModalDialog(). Notes showModalDialog() was briefly standardized as part of HTML5. The th...
XRPermissionDescriptor.optionalFeatures - Web APIs
racking space whose native origin tracks the viewer's position and orientation. This is used for environments in which the user can physically move around, and is supported by all instances of XRSession, both immersive and inline, though it's most useful for inline sessions. It's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces.
Otherwise, typically, one of the other reference space types will be used more often. XRReferenceSpace Usage notes Examples let xrPermissionDesc = { name: "xr", mode: "immersive-vr", optionalFeatures: [ "bounded-floor" ] }; if (navigator.permissions) { navigator.permissions.query(xrPermissionDesc).then(({state}) => { switch(state) { case "granted": setupXR(); ...
... Working Draft Initial definition. ...
XRPermissionDescriptor.requiredFeatures - Web APIs
racking space whose native origin tracks the viewer's position and orientation. This is used for environments in which the user can physically move around, and is supported by all instances of XRSession, both immersive and inline, though it's most useful for inline sessions. It's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces.
Otherwise, typically, one of the other reference space types will be used more often. XRReferenceSpace Usage notes Examples In this example, permissions are checked to ensure that the user has granted permission for the site or app to use immersive augmented reality mode with the local-floor reference space (presumably since the user is unlikely to start to fly). let xrPermissionDesc = { na...
...y to start to fly). let xrPermissionDesc = { name: "xr", mode: "immersive-ar", requiredFeatures: [ "local-floor" ] }; if (navigator.permissions) { navigator.permissions.query(xrPermissionDesc).then(({state}) => { switch(state) { case "granted": setupXR(); break; case "prompt": promptAndSetupXR(); break; default: /* do nothing
otherwise */ break; } .catch(err) { console.log(err); } } else { setupXR(); } Specifications Specification Status Comment WebXR Device APIThe definition of 'XRPermissionDescriptor.requiredFeatures' in that specification. Working Draft Initial definition. ...
XRSystem: isSessionSupported() - Web APIs
If the no devices are available or the browser doesn't have permission to use the XR device, the promise is rejected with an appropriate DOMException. Syntax var isSupportedPromise = xr.isSessionSupported(xrSessionMode) Parameters xrSessionMode A DOMString specifying the WebXR session mode for which support is to be checked. ...
...onSupported(xrSessionMode) Parameters xrSessionMode A DOMString specifying the WebXR session mode for which support is to be checked. This string must be one of inline (to present the WebXR content inline within the context of an HTML document) or immersive-vr for a fully-immersive virtual experience. Return value A Promise that resolves to true if the specified session mode is supported;
otherwise the promise resolves to false. Exceptions Rather than throwing true exceptions, isSessionSupported() rejects the returned promise, passing to the rejection handler a DOMException whose name is one of the following strings. SecurityError The document's origin does not have permission to use the xr-spatial-tracking feature policy. Examples In this example, we see isSessionSupported() used ...
XRView.eye - Web APIs
. For views which represent neither eye, such as monoscopic views, this property's value is none. Syntax let eye = xrView.eye; Value A DOMString whose value is one of the strings enumerated by the XREye type: left The XRView represents the point-of-view of the viewer's left eye. right The view represents the viewer's right eye. none The XRView describes a monoscopic view, or the view
otherwise doesn't represent a particular eye's point-of-view. Usage notes The primary purpose of this property is to allow the correct area of any pre-rendered stereo content to be presented to the correct eye. For dynamically-rendered 3D content, you can usually ignore this and simply render each of the viewer's views, one after another. Examples This code, from the viewer pose's renderer, iterates o...
...function updateInjury() on that eye to do things such as allow a bit of healing to occur, track the progress of a poison effect, or the like, as appropriate for the game's needs. updateInjury() returns true if the eye is still injured or false if the eye has been restored to health by the function,. If the result is false, indicating that the eye is now healthy, we render the scene for that eye.
Otherwise, we don't. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRView.eye' in that specification. Working Draft Initial definition. ...
ARIA: listbox role - Accessibility
ot have the aria-selected attribute. If false or omitted, only the currently selected option, if any option is selected, needs the aria-selected attribute, and it must be set to true. aria-required A Boolean attribute which indicates that an option with a non-empty string value must be selected. aria-readonly The user cannot change which options are selected or unselected, but the listbox is
otherwise operable. aria-label A human-readable string value which identifies the listbox. If there's a visible label, then aria-labelledby should be used instead to refer to that label. aria-labelledby Identifies the visible element or elements in a space-separated list of element IDs which identify the listbox. If there's no visible label, then aria-label should be used instead to include a label. ...
...ed="true" on the option and changing the appearance of the newly selected option to appear selected. Update the aria-activedescendant value on the listbox to the id of the newly selected option Visually handle the blur, focus, and selected states of the option Toggling the state of an option in a multi select listbox When the user clicks on an option, hits Space when focused on an option, or
otherwise toggles the state of an option, the following must occur: Toggle the aria-selected state of the currently focused option, changing the state of the aria-selected to true if it was false or false if it was true. Change the appearance of the option to reflect it's selected state Update the aria-activedescendant value on the listbox to the id of the option the user just interacted with, even if...
Architecture - Accessibility
cessible = QI/QS(object) (B) To get the offset in the parent text for a given embedded object: QI/QA to IAHyperLink If not successful, then it is not embedded in text, so it's position in parent should be determined just by IA2::indexInParent, which will return its child offset within the parent. Examples of objects not embedded in text are the child options in list boxes and combo boxes.
otherwise, use IAHyperLink::getStartIndex() to find the index in parent. In Firefox, the results of getEndIndex will always be the startIndex + 1, because links are always just represented by a single embedded object character (C) To get the next char fom a given offset in an accessible text: If current char is 0 (end of string), then we are on a hard line break: get next node (typical depth first sear...
... embed character If an embed character is found, continue processing with offset = index plus the line start index If an embed character is not found: If the line ending is equal to one less than the length of all text in the accessible, proceed to the next accessible in dept first search order and recurse on the first character until a non-embed is found.
Otherwise, continue processing with offset = the index at the end of the line. If the character at the offset is an embed, proceed to its corresponding accessible and recurse on the first character until a non-embed is found.
Otherwise, the offset marks the start of a new line. Navigating to the next word follows a similar pattern. Navigating previous requires returning...
Perceivable - Accessibility
ge</button>). For more information on other UI controls, see UI controls. Implement decorative (non-content) images, video, etc., in a way that is invisible to assistive technology, so it doesn't confuse users. Decorative images should be implemented using CSS background images (see Backgrounds). If you have to include an image via an <img> element, give it a blank alt (alt="").
Otherwise, screenreaders may try to read out the filepath, etc. If you are including background video or audio that autoplays, make it as unobtrusive as possible. Don't make it look/sound like content, and provide a control to turn it off. Ideally, don't include it at all. Note: Also see the WCAG description for Guideline 1.1: Text alternatives. Guideline 1.2 -- Providing text alternativ...
...n. The main situations in which this is relevant are: Text labels and the form elements they describe. These are associated unambiguously using the <label> element, which can be picked up by screenreaders, etc. Image alt text. Content images should have text available that clearly describes the image's contents, which can be programmatically associated with it (e.g., alt text), or
otherwise is easy to associate (e.g., describes it and is sat right next to it). This should mean that the full meaning can still be inferred even if you can't see the image. Lists. If the order of list items is important, use an ordered list (<ol>). The whole of HTML: A good basis for accessibility is packed with information about this, but you should particularly refer to Good semant...
-webkit-mask-position-x - CSS: Cascading Style Sheets
Percentages are calculated against the horizontal dimension of the box padding area. That means, a value of 0% means the left edge of the image is aligned with the box's left padding edge and a value of 100% means the ri...
...of the image is aligned with the box's left padding edge and a value of 100% means the right edge of the image is aligned with the box's right padding edge. left Equivalent to 0%. center Equivalent to 50%. right Equivalent to 100%. ...
-webkit-mask-position-y - CSS: Cascading Style Sheets
Percentages are calculated against the vertical dimension of the box padding area. A value of 0% means the top edge of the image is aligned with the box's top padding edge and a value of 100% means the bottom edge of the i...
...f the image is aligned with the box's top padding edge and a value of 100% means the bottom edge of the image is aligned with the box's bottom padding edge. top Equivalent to 0%. bottom Equivalent to 100%. center Equivalent to 50%. ...
@supports - CSS: Cascading Style Sheets
rm-style: preserve) or (-o-transform-style: preserve) or (-webkit-transform-style: preserve) {} @supports (transform-style: preserve-3d) or ((-moz-transform-style: preserve-3d) or ((-o-transform-style: preserve-3d) or (-webkit-transform-style: preserve-3d))) {} Note: When using both and and or operators, the parentheses must be used to define the order in which they apply.
Otherwise, the condition is invalid and the whole rule is ignored. Formal syntax @supports <supports-condition> { <group-rule-body> }where <supports-condition> = not <supports-in-parens> | <supports-in-parens> [ and <supports-in-parens> ]* | <supports-in-parens> [ or <supports-in-parens> ]*where <supports-in-parens> = ( <supports-condition> ) | <supports-feature> | <general-enclosed>where <supports-fe...
...ch don't support :is() */ :is(ul, ol) > li { ... /* CSS applied when the :is(...) selector is supported */ } @supports not selector(:is(a, b)) { /* Fallback for when :is() is unsupported */ ul > li, ol > li { ... /* The above expanded for browsers which don't support :is(...) */ } } @supports selector(:nth-child(1n of a, b)) { /* This rule needs to be inside the @supports block,
otherwise it will be partially applied in browsers which don't support the `of` argument of :nth-child(...) is supported */ :is(:nth-child(1n of ul, ol) a, details > summary) { ... /* CSS applied when the :is(...) selector and the `of` argument of :nth-child(...) are both supported */ } } Specifications Specification Status Comment CSS Conditional...
Overview of CSS Shapes - CSS: Cascading Style Sheets
the visual display is enhanced. Basic Shapes The value circle(50%) is an example of a Basic Shape. The specification defines four <basic-shape> values, which are: inset() circle() ellipse() polygon() Using the value inset() wraps text around a rectangular shape however you are able to add offset values, thus pulling the line boxes of any wrapping content closer to the object than would
otherwise happen. We have already seen how circle() creates a circular shape. An ellipse() is essentially a squashed circle. If none of these simple shapes do the trick you can create a polygon() and make the shape as complex as you want. In our Guide to Basic Shapes we explore each of the possible Basic Shapes and how to create them. Shapes from the Box Value Shapes can also be created around the Box ...
...ate your path is to use an image with an alpha channel -- the text will then wrap around the non-transparent parts of the image. This allows the overlay of wrapped content around an image, or the use of an image which is never displayed on the page purely as a method of creating a complex shape without needing to carefully map a polygon. Note that images used in this way must be CORS compatible,
otherwise shape-outside will act as if none had been given as the value, and you will get no shape. In this next example, we have an image with a fully transparent area, and we are using an image as the URL value for shape-outside. The shape is created around the opaque area -- the image of the balloon. shape-image-threshold The shape-image-threshold property is used to set the threshold of image tran...
Privacy and the :visited selector - CSS: Cascading Style Sheets
d links, but there are limits to which styles you can use. Only the following styles can be applied to visited links: color background-color border-color (and its sub-properties) column-rule-color outline-color The color parts of the fill and stroke attributes In addition, even for the above styles, you won't be able to change the transparency between unvisited and visited links, as you
otherwise would be able to using rgba(), hsla(), or the transparent keyword. Here is an example of how to use styles with the aforementioned restrictions: :link { outline: 1px dotted blue; background-color: white; /* The default value of background-color is `transparent`. You need to specify a different value,
otherwise changes on :visited won't apply. */ } :visited { outline-color: orange;...
... ...
clip-path - CSS: Cascading Style Sheets
e No clipping path is created. Note: A computed value other than none results in the creation of a new stacking context the same way that CSS opacity does for values other than 1. ...
...ay that CSS opacity does for values other than 1. ...
clip - CSS: Cascading Style Sheets
s may be either a <length> or auto. If any side's value is auto, the element is clipped to that side's inside border edge. auto The element does not clip (default). This is different from rect(auto, auto, auto, auto), which clips to the element's inside border edges. ...
...ide border edge. auto The element does not clip (default). This is different from rect(auto, auto, auto, auto), which clips to the element's inside border edges. ...
grid-area - CSS: Cascading Style Sheets
.com/mdn/interactive-examples and send us a pull request. If four <grid-line> values are specified, grid-row-start is set to the first value, grid-column-start is set to the second value, grid-row-end is set to the third value, and grid-column-end is set to the fourth value. When grid-column-end is omitted, if grid-column-start is a <custom-ident>, grid-column-end is set to that <custom-ident>;
otherwise, it is set to auto. When grid-row-end is omitted, if grid-row-start is a <custom-ident>, grid-row-end is set to that <custom-ident>;
otherwise, it is set to auto. When grid-column-start is omitted, if grid-row-start is a <custom-ident>, all four longhands are set to that value.
Otherwise, it is set to auto. The grid-area property can also be set to a <custom-ident> which acts as a name for the...
...If there is a named line with the name '<custom-ident>-start'/'<custom-ident>-end', it contributes the first such line to the grid item's placement. Note: Named grid areas automatically generate implicit named lines of this form, so specifying grid-area: foo; will choose the start/end edge of that named grid area (unless another line named foo-start/foo-end was explicitly specified before it).
Otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. <integer> && <custom-ident>? Contributes the nth grid line to the grid item's placement. If a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. If a name is given as a <custom-ident>, only lines with that name are counted. If not enough lines with tha...
margin-inline - CSS: Cascading Style Sheets
or the following CSS properties: margin-inline-end margin-inline-start Syntax Values The margin-inline property takes the same values as the margin-left property. ...
...cification Status Comment CSS Logical Properties and Values Level 1The definition of 'margin-inline' in that specification. Editor's Draft Initial definition. Initial value0Applies tosame as marginInheritednoPercentagesdepends on layout modelComputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value;
otherwise, autoAnimation typediscrete ...
position - CSS: Cascading Style Sheets
on were static. This value creates a new stacking context when the value of z-index is not auto. Its effect on table-*-group, table-row, table-column, table-cell, and table-caption elements is undefined. absolute The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any;
otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left. This value creates a new stacking context when the value of z-index is not auto. The margins of absolutely positioned boxes do not collapse with other margins. fixed The element is removed from the normal document flow, and no space is created for the element ...
...il they are scrolled offscreen. Rather than sliding offscreen with the rest of the content, the "B" heading will then remain fixed to the top of the viewport until all the "B" items have scrolled offscreen, at which point it will be covered up by the "C" heading, and so on. You must specify a threshold with at least one of top, right, bottom, or left for sticky positioning to behave as expected.
Otherwise, it will be indistinguishable from relative positioning. HTML <dl> <div> <dt>A</dt> <dd>Andrew W.K.</dd> <dd>Apparat</dd> <dd>Arcade Fire</dd> <dd>At The Drive-In</dd> <dd>Aziz Ansari</dd> </div> <div> <dt>C</dt> <dd>Chromeo</dd> <dd>Common</dd> <dd>Converge</dd> <dd>Crystal Castles</dd> <dd>Cursive</dd> </div> <div> <dt>E</dt> <...
word-break - CSS: Cascading Style Sheets
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax /* Keyword values */ word-break: normal; word-break: break-all; word-break: keep-all; word-break: break-word; /* deprecated */ /* Global values */ word-break: inherit; word-break: initial; word-break: unset; The word-break property is specified as a single keyword chosen from the list of values below. Values normal Use the default line break rule. ...
...apanese/Korean (CJK) text. Non-CJK text behavior is the same as for normal. break-word Has the same effect as word-break: normal and overflow-wrap: anywhere, regardless of the actual value of the overflow-wrap property. Note: In contrast to word-break: break-word and overflow-wrap: break-word (see overflow-wrap), word-break: break-all will create a break at the exact place where text would
otherwise overflow its container (even if putting an entire word on its own line would negate the need for a break). Formal definition Initial valuenormalApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Formal syntax normal | break-all | keep-all | break-word Examples HTML <p>1. <code>word-break: normal</code></p> <p class="normal narrow">This is a long and Honori...
HTML attribute: multiple - HTML: Hypertext Markup Language
s from the file picker in any way that their chosen platform allows (e.g. by holding down Shift or Control, and then clicking). <input type="file" multiple name="uploads" id="uploads"> When the attribute is omitted, the user can only select a single file per <input>. The multiple attribute on the <select> element represents a control for selecting zero or more options from the list of options.
Otherwise, the <select> element represents a control for selecting a single <option> from the list of options. <select multiple name="drawfs" id="drawfs"> <option>Grumpy</option> <option>Happy</option> <option>Sleepy</option> <option>Bashful</option> <option>Sneezy</option> <option>Dopey</option> <option>Doc</option> </select> When multiple is specified, most browsers will show a scrolling ...
...used method="get" each selected file's name would have been added to URL parameters as?uploads=img1.jpg&uploads=img2.svg. However, since we are sumbitting multipart form data, we much use post. See the <form> element and sending form data for more information. select The multiple attribute on the <select> element represents a control for selecting zero or more options from the list of options.
Otherwise, the <select> element represents a control for selecting a single <option> from the list of options. The control generally has a different appearance based on the presence of the multiple attribute, with most browsers displaying a scrolling list box instead of a single line dropdown when the attribute is present. <form method="get" action="#"> <p> <label for="dwarfs">Select the woodsmen you lik...
<a>: The Anchor element - HTML: Hypertext Markup Language
d content Transparent, containing either flow content (excluding interactive content) or phrasing content. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts phrasing content, or any element that accepts flow content, but not other <a> elements. ...
...empt from this requirement, but it's still a good idea to make sure enough text is hyperlinked to be easily activated. Understanding Success Criterion 2.5.5: Target Size Target Size and 2.5.5 Quick test: Large touch targets Proximity Interactive elements, like links, placed in close visual proximity should have space separating them. Spacing helps people with motor control issues, who may
otherwise accidentally activate the wrong interactive content. Spacing may be created using CSS properties like margin. Hand tremors and the giant-button-problem Specifications Specification Status Comment Referrer PolicyThe definition of 'referrer attribute' in that specification. Candidate Recommendation Added the referrerpolicy attribute. HTML Living Sta...
<area> - HTML: Hypertext Markup Language
es Flow content, phrasing content. Permitted content None, it is an empty element. Tag omission Must have a start tag and must not have an end tag. Permitted parents Any element that accepts phrasing content. The <area> element must have an ancestor <map>, but it need not be a direct parent. Implicit ARIA role link when href attribute is present,
otherwise no corresponding role Permitted ARIA roles No role permitted DOM interface HTMLAreaElement Attributes This element's attributes include the global attributes. alt A text string alternative to display on browsers that do not display images. The text should be phrased so that it presents the user with the same kind of choice as the image would offer when displaye...
... browser (in the background). Typically used for tracking. referrerpolicy A string indicating which referrer to use when fetching the resource: "no-referrer" meaning that the Referer: header will not be sent. "no-referrer-when-downgrade" meaning that no Referer: header will be sent when navigating to an origin without TLS (HTTPS). This is a user agent's default behavior, if no policy is
otherwise specified. "origin" meaning that the referrer will be the origin of the page, that is roughly the scheme, the host and the port. "origin-when-cross-origin" meaning that navigations to other origins will be limited to the scheme, the host and the port, while navigations on the same origin will include the referrer's path. "unsafe-url" meaning that the referrer will include the origin and th...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
butes for additional information. currentTime Reading currentTime returns a double-precision floating-point value indicating the current playback position, in seconds, of the audio. If the audio's metadata isn't available yet--thereby preventing you from knowing the media's start time or duration--currentTime instead indicates, and can be used to change, the time at which playback will begin.
Otherwise, setting currentTime sets the current playback position to the given time and seeks the media to that position if the media is currently loaded. If the audio is being streamed, it's possible that the user agent may not be able to obtain some parts of the resource if that data has expired from the media buffer. Other audio may have a media timeline that doesn't start at 0 seconds, so setting cur...
...is to play your audio using a <video> element, which does support WebVTT. In addition to spoken dialog, subtitles and transcripts should also identify music and sound effects that communicate important information. This includes emotion and tone. For example, in the WebVTT below, note the use of square brackets to provide tone and emotional insight to the viewer; this can help establish the mood
otherwise provided using music, nonverbal sounds and crucial sound effects, and so forth. 1 00:00:00 --> 00:00:45 [Energetic techno music] 2 00:00:46 --> 00:00:51 Welcome to the Time Keeper's podcast! In this episode we're discussing which Swisswatch is a wrist switchwatch? 16 00:00:52 --> 00:01:02 [Laughing] Sorry! I mean, which wristwatch is a Swiss wristwatch? Also it's a good practice to provide s...
<fieldset>: The Field Set element - HTML: Hypertext Markup Language
The name associated with the group. Note: The caption for the fieldset is given by the first <legend> element nested inside it. Styling with CSS There are several special styling considerations for <fieldset>. Its display value is block by default, and it establishes a block formatting context. If the <fieldset> is styled with an inline-level display value, it will behave as inline-block,
otherwise it will behave as block. By default there is a 2px groove border surrounding the contents, and a small amount of default padding. The element has min-inline-size: min-content by default. If a <legend> is present, it is placed over the block-start border. The <legend> shrink-wraps, and also establishes a formatting context. The display value is blockified. (For example, display: inline behaves as...
...s as block.) There will be an anonymous box holding the contents of the <fieldset>, which inherits certain properties from the <fieldset>. If the <fieldset> is styled with display: grid or display: inline-grid, then the anonymous box will be a grid formatting context. If the <fieldset> is styled with display: flex or display: inline-flex, then the anonymous box will be a flex formatting context.
Otherwise, it establishes a block formatting context. You can feel free to style the <fieldset> and <legend> in any way you want to suit your page design. Examples Simple fieldset This example shows a really simple <fieldset> example, with a <legend>, and a single control inside it. <form action="#"> <fieldset> <legend>Simple fieldset</legend> <input type="radio" id="radio"> <label for="...
<img>: The Image Embed element - HTML: Hypertext Markup Language
ategically placing images in a page's markup such that a server can track how many images are requested and when. referrerpolicy A string indicating which referrer to use when fetching the resource: no-referrer: The Referer header will not be sent. no-referrer-when-downgrade: No Referer header is sent when navigating to an origin without HTTPS. This is the default if no policy is
otherwise specified. origin: The Referer header will include the page's origin (scheme, host, and port). origin-when-cross-origin: Navigating to other origins will limit the included referral data to the scheme, host, and port, while navigating from the same origin will include the full path and query string. unsafe-url: The Referer header will always include the origin, path and query string, but no...
... alt="MDN logo" srcset="/static/external/6c/6c98485e5d8acac9fecd7824ce30c9587f0d8548b946ee9fb1293d2eccdb6cf1.png 2x"> Using the srcset and sizes attributes The src attribute is ignored in user agents that support srcset when w descriptors are included. When the (max-width: 600px) media condition matches, the 200 pixel-wide image will load (it is the one that matches 200px most closely),
otherwise the other image will load. <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: 600px) 200px, 50vw"> To see the resizing in action, view the example on a separate page, so you can actually resize the content area. Security and privacy concerns Althoug...
<input type="number"> - HTML: Hypertext Markup Language
Element.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal to the basis for stepping (min if specified, value
otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max). Note: When the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction wh...
...enter a value. The following screenshot is taken from Firefox for Android: A simple number input In its most basic form, a number input can be implemented like this: <label for="ticketNum">Number of tickets you would like to buy:</label> <input id="ticketNum" type="number" name="ticketNum" value="0"> A number input is considered valid when empty and when a single number is entered, but is
otherwise invalid. If the required attribute is used, the input is no longer considered valid when empty. Note: Any number is an acceptable value, as long as it is a valid floating point number (that is, not NaN or Infinity). Placeholders Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer desc...
<input type="time"> - HTML: Hypertext Markup Language
tElement.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal to the basis for stepping (min if specified, value
otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max). Note: When the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction wh...
... HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, of the wrong type, and so forth). Handling browser support As mentioned above, Safari and a few other, less common, browsers don't yet support time inputs natively. In general,
otherwise, support is good -- especially on mobile platforms, which tend to have very nice user interfaces for specifying a time value. For example, the time picker on Chrome for Android looks like this: Browsers that don't support time inputs gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data h...
Standard metadata names - HTML: Hypertext Markup Language
strict-origin Send the origin when the destination is at least as secure as the current page (HTTP(S)->HTTPS), but send no referrer when it's less secure (HTTPS->HTTP). strict-origin-when-cross-origin Send the full URL (stripped of parameters) for same-origin requests. Send the origin when the destination is at least as secure as the current page (HTTP(S)->HTTPS).
Otherwise, send no referrer. unsafe-URL Send the full URL (stripped of parameters) for same-origin or cross-origin requests. Notes: Dynamically inserting <meta name="referrer"> (with document.write() or appendChild()) makes the referrer behaviour unpredictable. When several conflicting policies are defined, the no-referrer policy is applied. theme-color...
...e second specified scheme is acceptable if the user prefers it. only light Indicates that the document only supports light mode, with a light background and dark foreground colors. By specification, only dark is not valid, because forcing a document to render in dark mode when it isn't truly compatible with it can result in unreadable content; all major browsers default to light mode if not
otherwise configured. For example, to indicate that a document prefers dark mode but does render functionally in light mode as well: <meta name="color-scheme" content="dark light"> This works at the document level in the same way that the CSS color-scheme property lets individual elements specify their preferred and accepted color schemes. Your styles can adapt to the current color scheme using...
HTML elements reference - HTML: Hypertext Markup Language
sses, locations in the same page, or anything else a URL can address. <abbr> The HTML Abbreviation element (<abbr>) represents an abbreviation or acronym; the optional title attribute can provide an expansion or description for the abbreviation. <b> The HTML Bring Attention To element (<b>) is used to draw the reader's attention to the element's contents, which are not
otherwise granted special importance. <bdi> The HTML Bidirectional Isolate element (<bdi>) tells the browser's bidirectional algorithm to treat the text it contains in isolation from its surrounding text. <bdo> The HTML Bidirectional Text Override element (<bdo>) overrides the current directionality of text, so that the text within is rendered in a different direction. ...
...red in a way that indicates that it has a non-textual annotation. <var> The HTML Variable element (<var>) represents the name of a variable in a mathematical expression or a programming context. <wbr> The HTML <wbr> element represents a word break opportunity--a position within text where the browser may optionally break a line, though its line-breaking rules would not
otherwise create a break at that location. Image and multimedia HTML supports various multimedia resources such as images, audio, and video. Element Description <area> The HTML <area> element defines a hot-spot region on an image, and optionally associates it with a hypertext link. This element is used only within a <map> element. <audio> The HTML <aud...
Control flow and error handling - JavaScript
ical condition is true. Use the optional else clause to execute a statement if the condition is false. An if statement looks like this: if (condition) { statement_1; } else { statement_2; } Here, the condition can be any expression that evaluates to true or false. (See Boolean for an explanation of what evaluates to true and false.) If condition evaluates to true, statement_1 is executed.
Otherwise, statement_2 is executed. statement_1 and statement_2 can be any statement, including further nested if statements. You can also compound the statements using else if to have multiple conditions tested in sequence, as follows: if (condition_1) { statement_1; } else if (condition_2) { statement_2; } else if (condition_n) { statement_n; } else { statement_last; } In the case of multiple...
... Caution: Do not confuse the primitive boolean values true and false with the true and false values of the Boolean object! For example: var b = new Boolean(false); if (b) // this condition evaluates to true if (b == true) // this condition evaluates to false Example In the following example, the function checkData returns true if the number of characters in a Text object is three.
Otherwise, it displays an alert and returns false. function checkData() { if (document.form1.threeChar.value.length == 3) { return true; } else { alert( 'Enter exactly three characters. ' + `${document.form1.threeChar.value} is not valid.`); return false; } } switch statement A switch statement allows a program to evaluate an expression and attempt to match the express...
Numbers and dates - JavaScript
me is created with the current date and time. Then calls to the getHours, getMinutes, and getSeconds methods assign the value of the current hour, minute, and second to hour, minute, and second. The next four statements build a string value based on the time. The first statement creates a variable temp, assigning it a value using a conditional expression; if hour is greater than 12, (hour - 12),
otherwise simply hour, unless hour is 0, in which case it becomes 12. The next statement appends a minute value to temp. If the value of minute is less than 10, the conditional expression adds a string with a preceding zero;
otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp in the same way. Finally, a conditional expression appends "P.M." to temp if hou...
... hour is 0, in which case it becomes 12. The next statement appends a minute value to temp. If the value of minute is less than 10, the conditional expression adds a string with a preceding zero;
otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp in the same way. Finally, a conditional expression appends "P.M." to temp if hour is 12 or greater;
otherwise, it appends "A.M." to temp. << PreviousNext >> ...
Classes - JavaScript
, you use the class keyword with the name of the class ("Rectangle" here). class Rectangle { constructor(height, width) { this.height = height; this.width = width; } } Hoisting An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. You first need to declare your class and then access it,
otherwise code like the following will throw a ReferenceError: const p = new Rectangle(); // ReferenceError class Rectangle {} Class expressions A class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's body. (it can be retrieved through the class's (not an instance's) name property, though). // u...
...o the same hoisting restrictions as described in the Class declarations section. Class body and method definitions The body of a class is the part that is in curly brackets {}. This is where you define class members, such as methods or constructor. Strict mode The body of a class is executed in strict mode, i.e., code written here is subject to stricter syntax for increased performance, some
otherwise silent errors will be thrown, and certain keywords are reserved for future versions of ECMAScript. Constructor The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method. A ...
Array.prototype.every() - JavaScript
ach element, taking three arguments: element The current element being processed in the array. index Optional The index of the current element being processed in the array. array Optional The array every was called upon. thisArg Optional A value to use as this when executing callback. Return value true if the callback function returns a truthy value for every array element.
Otherwise, false. Description The every method executes the provided callback function once for each element present in the array until it finds the one where callback returns a falsy value. If such an element is found, the every method immediately returns false.
Otherwise, if callback returns a truthy value for all elements, every returns true. Caution: Calling this method on an empty array will retur...
...ndition! callback is invoked only for array indexes which have assigned values. It is not invoked for indexes which have been deleted, or which have never been assigned values. callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. If a thisArg parameter is provided to every, it will be used as callback's this value.
Otherwise, the value undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. every does not mutate the array on which it is called. The range of elements processed by every is set before the first invocation of callback. Therefore, callback will not run on elements that are appended...
Array.prototype.filter() - JavaScript
ample is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax let newArray = arr.filter(callback(element[, index, [array]])[, thisArg]) Parameters callback Function is a predicate, to test each element of the array. Return true to keep the element, false
otherwise. It accepts three arguments: element The current element being processed in the array. indexOptional The index of the current element being processed in the array. arrayOptional The array filter was called upon. thisArgOptional Value to use as this when executing callback. Return value A new array with the elements that pass the test. If no elements pass the test, an emp...
...hich have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array. callback is invoked with three arguments: the value of the element the index of the element the Array object being traversed If a thisArg parameter is provided to filter, it will be used as the callback's this value.
Otherwise, the value undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. filter() does not mutate the array on which it is called. The range of elements processed by filter() is set before the first invocation of callback. Elements which are appended to the array (from callback) ...
Array.prototype.findIndex() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. See also the find() method, which returns the value of an array element, instead of its index. ...
...ound. It takes three arguments: element The current element being processed in the array. index Optional The index of the current element being processed in the array. array Optional The array findIndex() was called upon. thisArg Optional Optional object to use as this when executing callback. Return value The index of the first element in the array that passes the test.
Otherwise, -1. Description The findIndex() method executes the callback function once for every index in the array until it finds the one where callback returns a truthy value. If such an element is found, findIndex() immediately returns the element's index. If callback never returns a truthy value (or the array's length is 0), findIndex() returns -1. Edge case alert: Unlike other array methods such a...
Array.prototype.some() - JavaScript
taking three arguments: element The current element being processed in the array. indexOptional The index of the current element being processed in the array. arrayOptional The array some() was called upon. thisArgOptional A value to use as this when executing callback. Return value true if the callback function returns a truthy value for at least one element in the array.
Otherwise, false. Description The some() method executes the callback function once for each element present in the array until it finds the one where callback returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found, some() immediately returns true.
Otherwise, some() returns false. callback is invoked only for indexes of the array with assigned values. ...
...alse. callback is invoked only for indexes of the array with assigned values. It is not invoked for indexes which have been deleted or which have never been assigned values. callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. If a thisArg parameter is provided to some(), it will be used as the callback's this value.
Otherwise, the value undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. some() does not mutate the array on which it is called. The range of elements processed by some() is set before the first invocation of callback. Elements appended to the array after the call to some() begin...
Promise.prototype.catch() - JavaScript
m/mdn/interactive-examples and send us a pull request. Syntax p.catch(onRejected); p.catch(function(reason) { // rejection }); Parameters onRejected A Function called when the Promise is rejected. This function has one argument: reason The rejection reason. ...
...ise which is itself rejected;
otherwise, it is resolved. Return value Internally calls Promise.prototype.then on the object upon which it was called, passing the parameters undefined and the received onRejected handler. Returns the value of that call, which is a Promise. Note the examples below are throwing instances of Error. This is considered good practice in contrast to throwing Strings;
otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information like stack traces. Demonstration of the internal call: // overriding original Promise.prototype.then/catch just to add some logs (function(Promise){ var originalThen = Promise.prototype.then; var originalCatch = Promise.prototype.catch; ...
Reflect.getOwnPropertyDescriptor() - JavaScript
The static Reflect.getOwnPropertyDescriptor() method is similar to Object.getOwnPropertyDescriptor(). It returns a property descriptor of the given property if it exists on the object, undefined
otherwise. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.getOwnPropertyDescriptor(target, propertyKey) Parameters target The target object in which to look for the property. propertyKey The name of the property to get an own property descriptor for. Return value A property descriptor object if the property exists in target object;
otherwise, undefined. Exceptions A TypeError, if target is not an Obj...
...The only difference to Object.getOwnPropertyDescriptor() is how non-object targets are handled. ...
RegExp.prototype.dotAll - JavaScript
t the "s" flag is used with the regular expression. dotAll is a read-only property of an individual regular expression instance. ...
... Writable no Enumerable no Configurable yes Description The value of dotAll is a Boolean and true if the "s" flag was used;
otherwise, false. The "s" flag indicates that the dot special character (".") should additionally match the 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 exceptio...
String - JavaScript
ditor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this. Method 1 You can use the + operator to append multiple strings together, like this: let longString = "This is a very long string which needs " + "to wrap across multiple lines because " + "
otherwise my code is unreadable." Method 2 You can use the backslash character (\) at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent;
otherwise it will not work. That form looks like this: let longString = "This is a very long string which needs \ to wrap ...
... Constructor String() Creates a new String object. ...
Symbol.for() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Symbol.for(key); Parameters key String, required. The key for the symbol (and also used for the description of the symbol). ...
...ctive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Symbol.for(key); Parameters key String, required. The key for the symbol (and also used for the description of the symbol). Return value An existing symbol with the given key if found;
otherwise, a new symbol is created and returned. Description In contrast to Symbol(), the Symbol.for() function creates a symbol available in a global symbol registry list. Symbol.for() does also not necessarily create a new symbol on every call, but checks first if a symbol with the given key is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is fo...
TypedArray.prototype.every() - JavaScript
element, taking three arguments: currentValue The current element being processed in the typed array. index The index of the current element being processed in the typed array. array The typed array every was called upon. thisArg Optional. Value to use as this when executing callback. Return value true if the callback function returns a truthy value for every array element;
otherwise, false. Description The every method executes the provided callback function once for each element present in the typed array until it finds one where callback returns a falsy value (a value that becomes false when converted to a Boolean). If such an element is found, the every method immediately returns false.
Otherwise, if callback returned a true value for all elements, every will return tru...
... The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. every does not mutate the typed array on which it is called. ...
TypedArray.prototype.filter() - JavaScript
is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax typedarray.filter(callback[, thisArg]) Parameters callback Function to test each element of the typed array. Invoked with arguments (element, index, typedarray). Return true to keep the element, false
otherwise. thisArg Optional Value to use as this when executing callback. Return value A new typed array with the elements that pass the test. Description The filter() method calls a provided callback function once for each element in a typed array, and constructs a new typed array of all the values for which callback returns a true value. callback is invoked only for indexes of the typed array whi...
...een assigned values. Typed array elements which do not pass the callback test are simply skipped, and are not included in the new typed array. callback is invoked with three arguments: the value of the element the index of the element the typed array object being traversed If a thisArg parameter is provided to filter, it will be passed to callback when invoked, for use as its this value.
Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. filter() does not mutate the typed array on which it is called. The range of elements processed by filter() is set before the first invocation of callback. Elements which are appended to the typed ...
TypedArray.prototype.find() - JavaScript
TypedArray is one of the typed array types here. See also the findIndex() method, which returns the index of a found element in the typed array instead of its value. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
... to execute on each value in the typed array, taking three arguments: element The current element being processed in the typed array. index The index of the current element being processed in the typed array. array The array find was called upon. thisArg Optional. Object to use as this when executing callback. Return value A value in the array if an element passes the test;
otherwise, undefined. Description The find method executes the callback function once for each element present in the typed array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element.
Otherwise, find returns undefined. callback is invoked only for indexes of the typed array which have assigned values; it is not invoked for...
TypedArray.prototype.findIndex() - JavaScript
See also the find() method, which returns the value of a found element in the typed array instead of its index. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...on each value in the typed array, taking three arguments: element The current element being processed in the typed array. index The index of the current element being processed in the typed array. array The typed array findIndex was called upon. thisArg Optional. Object to use as this when executing callback. Return value An index in the array if an element passes the test;
otherwise, -1. Description The findIndex method executes the callback function once for each element present in the typed array until it finds one where callback returns a true value. If such an element is found, findIndex immediately returns the index of that element.
Otherwise, findIndex returns -1. callback is invoked only for indexes of the typed array which have assigned values; it is not invoked fo...
TypedArray.prototype.some() - JavaScript
ch element, taking three arguments: currentValue The current element being processed in the typed array. index The index of the current element being processed in the typed array. array The typed array some was called upon. thisArg Optional. Value to use as this when executing callback. Return value true if the callback function returns a truthy value for any array element;
otherwise, false. Description The some method executes the callback function once for each element present in the typed array until it finds one where callback returns a true value. If such an element is found, some immediately returns true.
Otherwise, some returns false. callback is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed. ...
... The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. some does not mutate the typed array on which it is called. ...
eval() - JavaScript
's analyze the benefits of the above efficient method: It allows the code in the string passed to runCodeWithDateFunction() to be minified. Function call overhead is minimal, making the far smaller code size well worth the benefit Function() more easily allows your code to utilize the performance buttering "use strict"; The code does not use eval(), making it orders of magnitude faster than
otherwise. Lastly, let's examine minification. With using Function() as shown above, you can minify the code string passed to runCodeWithDateFunction() far more efficiently because the function arguments names can be minified too as seen in the minified code below. console.log(Function('"use strict";return(function(a){return a(5)})')()(function(a){ return"Monday Tuesday Wednesday Thursday Friday Saturda...
...tes the string "x + y + 1"; the second evaluates the string "42". var x = 2; var y = 39; var z = '42'; eval('x + y + 1'); // returns 42 eval(z); // returns 42 Using eval to evaluate a string of JavaScript statements The following example uses eval() to evaluate the string str. This string consists of JavaScript statements that assigns z a value of 42 if x is five, and assigns 0 to z
otherwise. When the second statement is executed, eval() will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to z. var x = 5; var str = "if (x == 5) {console.log('z is 42'); z = 42;} else z = 0;"; console.log('z is ', eval(str)); If you define multiple values then the last value is returned. var x = 5; var str = "if (x == 5)...
for...in - JavaScript
property will be visited, whether a modified property (other than the current one) will be visited before or after it is modified, or whether a deleted property will be visited before it is deleted. Array iteration and for...in Note: for...in should not be used to iterate over an Array where the index order is important. Array indexes are just enumerable properties with integer names and are
otherwise identical to general object properties. There is no guarantee that for...in will return the indexes in any particular order. The for...in loop statement will return all enumerable properties, including those with non-integer names and those that are inherited. Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. Therefo...
...rototypes with a check method. Why Use for...in? Given that for...in is built for iterating object properties, not recommended for use with arrays, and options like Array.prototype.forEach() and for...of exist, what might be the use of for...in at all? It may be most practically used for debugging purposes, being an easy way to check the properties of an object (by outputting to the console or
otherwise). Although arrays are often more practical for storing data, in situations where a key-value pair is preferred for working with data (with properties acting as the "key"), there may be instances where you want to check if any of those keys hold a particular value. Examples Using for...in The for...in loop below iterates over all of the object's enumerable, non-Symbol properties and logs a stri...
Autoplay guide for media and Web Audio APIs - Web media technologies
et to 0 The user has interacted with the site (by clicking, tapping, pressing keys, etc.) If the site has been whitelisted; this may happen either automatically if the browser determines that the user engages with media frequently, or manually through preferences or other user interface features If the autoplay feature policy is used to grant autoplay support to an <iframe> and its document.
Otherwise, the playback will likely be blocked. The exact situations that result in blocking, and the specifics of how sites become whitelisted vary from browser to browser, but the above are good guidelines to go by. For details, see the auto-play policies for Google Chrome and WebKit. Note: Put another way, playback of any media that includes audio is generally blocked if the playback is programmatica...
...owed by default), this preference being true allows autoplay of media with audio tracks anyway if the page has been activated by user gestures, and media that isn't audible is not restricted at all. media.block-autoplay-until-in-foreground A Boolean preference which indicates whether or not media playback is blocked when started on a background tab. The default value, true, means that even when
otherwise available, autoplay won't take place until after a tab is brought to the foreground. This prevents the distracting situation in which a tab begins playing sound and the user can't find the tab among all their tabs and windows. ...
Web audio codec guide - Web media technologies
e Lossless) is a lossless codec developed by Apple. After initially being a closed format, Apple opened it up under an Apache license. Cross-platform and browser support for ALAC is not very strong, making it a less than ideal choice for general usage. However, if your target is primarily macOS and iOS users, it may be worth considering, as the operating systems have integrated support for ALAC.
Otherwise, FLAC is likely a better choice, if you must use a lossless codec. Keep in mind, however, that lossless codecs require substantially more bandwidth and storage capacity, and may not be a good choice outside very specific use cases. Supported bit rates Based on the sample format and sample rate, as well as the compression level Variable Bit Rate (VBR) support No ...
...[1] Yes[1] No Yes[1] Yes[1] Container support 3GP, AMR-WB RTP / WebRTC compatible Yes Licensing All applicable patents have expired; G.722 is free to use without restriction [1] WebRTC only. MP3 (MPEG-1 Audio Layer III) Of the audio formats specified by the MPEG/MPEG-2 standards, MPEG-1 Audio Layer III--
otherwise known as MP3--is by far the most widely used and best-known. The MP3 codec is defined by MPEG-1 Part 3 and MPEG-2 Part 3, and was introduced in 1991 (and finalized in 1992). When MP3-format audio is stored inside an MPEG container, the resulting file is also referred to as just an "MP3 file" or simply "MP3." Files with the ubiquitous .mp3 extension are stored in what is perhaps the most widely d...
Media container formats (file types) - Web media technologies
Support is also implied only for the container itself, not for any specific codecs. [2] Available only if available on the underlying operating system's media framework. [3] Requires Web Media Extensions to be installed. 3GP The 3GP or 3GPP media container is used to encapsulate audio and/or video...
...le formats are essentially identical. Created by the Moving Picture Experts Group (MPEG), these formats are widely used in physical media, including as the format of the video on DVD media. On the internet, perhaps the most common use of the MPEG file format is to contain Layer_III/MP3 sound data; the resulting files are the wildly popular MP3 file used by digital music devices around the world.
Otherwise, MPEG-1 and MPEG-2 are not widely used in Web content. The main differences between MPEG-1 and MPEG-2 take place in the media data formats rather than the container format. MPEG-1 was introduced in 1992; MPEG-2 was introduced in 1996. MPEG-1 and MPEG-2 media MIME types Audio Video audio/mpeg video/mpeg Video codecs supported by MPEG-1 and MPEG-2 Cod...
Image file type and format guide - Web media technologies
use-cases. Photographs Photographs typically fare well with lossy compression (depending on the encoder's configuration). This makes JPEG and WebP good choices for photographs, with JPEG being more compatible but WebP perhaps offering better compression. To maximize quality and minimize download time, consider providing both using a fallback with WebP as the first choice and JPEG as the second.
Otherwise, JPEG is the safe choice for compatibility. Best choice Fallback WebP or JPEG JPEG Icons For smaller images such as icons, use a lossless format to avoid loss of detail in a size-constrained image. While lossless WebP is ideal for this purpose, support is not widespread yet, so PNG is a better choice unless you offer a fallback. If your image contains fewer th...
...ion. PNG is probably your best bet, but lossless WebP is arguably going to be better compressed. Best choice Fallback Lossless WebP or PNG; JPEG if compression artifacts aren't a concern PNG or JPEG; GIF for screenshots with low color counts Diagrams, drawings, and charts For any image that can be represented using vector graphics, SVG is the best choice.
Otherwise, you should use a lossless format like PNG. If you do choose a lossy format, such as JPEG or lossy WebP, carefully weigh the compression level to avoid causing text or other shapes to become fuzzy or unclear. Best choice Fallback SVG PNG Providing image fallbacks While the standard HTML <img> element doesn't support compatibility fallbacks for images, the <picture...
Critical rendering path - Web Performance
of screen. The layout step determines where and how the elements are positioned on the page, determining the width and height of each element, and where they are in relation to each other. What is the width of an element? Block level elements, by definition, have a default width of 100% of the width of their parent. An element with a width of 50%, will be half of the width of its parent. Unless
otherwise defined, the body has a width of 100%, meaning it will be 100% of the width of the viewport. This width of the device impacts layout. The viewport meta tag defines the width of the layout viewport, impacting the layout. Without it, the browser uses the default viewport width, which on by-default full screen browsers is generally 960px. On by-default full screen browsers, like your phone's browse...
...l screen browsers is generally 960px. On by-default full screen browsers, like your phone's browser, by setting <meta name="viewport" content="width=device-width">, the width will be the width of the device instead of the default viewport width. The device-width changes when a user rotates their phone between landscape and portrait mode. Layout happens every time a device is rotated or browser is
otherwise resized. Layout performance is impacted by the DOM -- the greater the number of nodes, the longer layout takes. Layout can become a bottleneck, leading to jank if required during scrolling or other animations. While a 20ms delay on load or orientation change may be fine, it will lead to jank on animation or scroll. Any time the render tree is modified, such as by added nodes, altered content, or...
dominant-baseline - SVG: Scalable Vector Graphics
auto | text-bottom | alphabetic | ideographic | middle | central | mathematical | hanging | text-top Default value auto Animatable Yes auto If this property occurs on a <text> element, then the computed value depends on the value of the writing-mode attribute. If the writing-mode is horizontal, then the value of the dominant-baseline component is alphabetic.
Otherwise, if the writing-mode is vertical, then the value of the dominant-baseline component is central. If this property occurs on a <tspan>, <tref>, <altGlyph>, or <textPath> element, then the dominant-baseline and the baseline-table components remain the same as those of the parent text content element. If the computed baseline-shift value actually shifts the baseline, then the baseline-table font...
...a <tspan>, <tref>, <altGlyph>, or <textPath> element, then the dominant-baseline and the baseline-table components remain the same as those of the parent text content element. If the computed baseline-shift value actually shifts the baseline, then the baseline-table font-size component is set to the value of the font-size attribute on the element on which the dominant-baseline attribute occurs,
otherwise the baseline-table font-size remains the same as that of the element. If there is no parent text content element, the scaled-baseline-table value is constructed as above for <text> elements. use-script The dominant-baseline and the baseline-table components are set by determining the predominant script of the character data content. The writing-mode, whether horizontal or vertical, is used...
SVG documentation index - SVG: Scalable Vector Graphics
egin or when an element should be discarded. 35 bias Filters, NeedsExample, SVG, SVG Attribute The bias attribute shifts the range of the filter. After applying the kernelMatrix of the <feConvolveMatrix> element to the input image to yield a number and applied the divisor attribute, the bias attribute is added to each component. This allows representation of values that would
otherwise be clamped to 0 or 1. 36 by SVG, SVG Attribute The by attribute specifies a relative offset value for an attribute that will be modified during an animation. 37 calcMode NeedsCompatTable, NeedsExample, SVG, SVG Attribute The calcMode attribute specifies the interpolation mode for the animation. 38 cap-height Deprecated, SVG, SVG Attribute ...
...e total duration for repeating an animation. 177 requiredFeatures SVG, SVG Attribute The requiredFeatures attribute takes a list of feature strings, with the individual strings separated by white space. It determines whether or not all of the named features are supported by the browser; if all of them are supported, the attribute evaluates to true end the element is rendered;
otherwise, the attribute evaluates to false and the current element and its children are skipped and thus will not be rendered. This provides a way to design SVG that gracefully falls back when features aren't available. 178 restart SVG, SVG Attribute The restart attribute specifies whether or not an animation can restart. 179 result NeedsCompatTable, SVG, SVG Attribute ...
XSLT elements reference - XSLT: Extensible Stylesheet Language Transformations
e-alias>, <xsl:number>, <xsl:output>, <xsl:stylesheet>, <xsl:text> and <xsl:value-of> is fully migrated. ...
...ly-imports> <xsl:apply-templates> <xsl:attribute> <xsl:attribute-set> <xsl:call-template> <xsl:choose> <xsl:comment> <xsl:copy> <xsl:copy-of> <xsl:decimal-format> <xsl:element> <xsl:fallback> (not supported) <xsl:for-each> <xsl:if> <xsl:import> (mostly supported) <xsl:include> <xsl:key> <xsl:message> <xsl:namespace-alias> (not supported) <xsl:number> (partially supported) <xsl:
otherwise> <xsl:output> (partially supported) <xsl:param> <xsl:preserve-space> <xsl:processing-instruction> <xsl:sort> <xsl:strip-space> <xsl:stylesheet> (partially supported) <xsl:template> <xsl:text> (partially supported) <xsl:transform> <xsl:value-of> (partially supported) <xsl:variable> <xsl:when> <xsl:with-param> ...
Compiling a New C/C++ Module to WebAssembly - WebAssembly
function, and other functions are eliminated as dead code. Putting EMSCRIPTEN_KEEPALIVE before a function name stops this from happening. You also need to import the emscripten.h library to use EMSCRIPTEN_KEEPALIVE. Note: We are including the #ifdef blocks so that if you are trying to include this in C++ code, the example will still work. Due to C versus C++ name mangling rules, this would
otherwise break, but here we are setting it so that it treats it as an external C function if you are using C++. Now add html_template/shell_minimal.html into this new directory too, just for convenience (you'd obviously put this in a central place in your real dev environment). Now let's run the compilation step again. From inside your latest directory (and while inside your Emscripten comp...
...o this new directory too, just for convenience (you'd obviously put this in a central place in your real dev environment). Now let's run the compilation step again. From inside your latest directory (and while inside your Emscripten compiler environment terminal window), compile your C code with the following command. ...
Classes and Inheritance - Archive of obsolete content
t, we need to understand how instanceof works. Every prototype has a constructor property, which is a reference to the constructor for objects with this prototype. In other words: Circle.prototype.constructor == Circle // => true The instanceof operator compares the constructor property of the prototype of the left hand side with that of the right hand side, and returns true if they are equal.
Otherwise, it repeats the comparison for the prototype of the right hand side, and so on, until either it returns true, or the prototype becomes null, in which case it returns false. The problem is that when we overrode the prototype of Circle with an object whose prototype is the prototype of Shape, we didn't correctly set its constructor property. This property is set automatically for the prototype prop...
Modules - Archive of obsolete content
se those features available to ordinary websites. The Sandbox constructor takes a URL parameter, which is used to determine the set of privileges for the compartment in which the sandbox will be created. Passing an XUL URL will result in a compartment with chrome privileges (note, however, that if you ever actually do this in any of your code, Gabor will be forced to hunt you down and kill you).
Otherwise, the compartment will have content privileges by default. Rewriting the loadScript function using sandboxes, we end up with: function loadScript(url, imports) { let global = Components.utils.Sandbox(url); global.imports = imports; global.exports = {}; loader.loadSubScript(url, global); return global.exports; } Note that the object returned by Sandbox is a wrapper to the sand...
context-menu - Archive of obsolete content
ked on, or null if not set. isEditable true if the menu was invoked in an editable element, and that element isn't disabled or read-only. This includes non-input elements with the contenteditable attribute set to true. selectionText The current selection as a text string, or null. If the menu was invoked in an input text box or area, this is the selection of that element,
otherwise the selection in the contents of the window. srcURL The src URL of the element that the menu was invoked on, or null if it doesn't have one. linkURL The href URL of the element that the menu was invoked on, or null if it doesn't have one. value The current contents of a input text box or area if the menu was invoked in one, null
otherwise. Item A labele...
passwords - Archive of obsolete content
sername The username. password The password. url The URL for the web service which requires the credential. You should omit anything after the hostname and (optional) port. realm The WWW-Authenticate response header sent by the server may include a "realm" field as detailed in RFC 2617. If it does, this property contains the value for the "realm" field.
Otherwise, it is omitted. The realm is displayed in Firefox's Password Manager, under "Site", in brackets after the URL. 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 usern...
ui - Archive of obsolete content
ton standalone or add it to a toolbar. If it's standalone, it appears in the toolbar at the top right of the browser window: ToggleButton A toggle button is a special kind of button that's for representing a binary on/off state, like a checkbox. So they have a checked property which is toggled when the user clicks the button, and the icon gets a "pressed" look when the button is checked. It's
otherwise identical to the action button. Attaching panels to buttons is only supported from Firefox 30 onwards. From Firefox 30 onwards, you can attach panels to toggle buttons, by passing the button into the panel's constructor or its show() method: Frame A frame enables you to create an HTML iframe, using bundled HTML, CSS and JavaScript. This can then be added to a designated area of the Firefo...
High-Level APIs - Archive of obsolete content
addon-page Create a page that does not contain navigational elements. base64 Data encoding and decoding using Base64 algorithms. clipboard Interact with the system clipboard, setting and getting its contents. context-menu Adds items, submenus, and menu separators to the page's context menu. ...
/loader - Archive of obsolete content
let sandbox = Sandbox({ name: 'resource:///modules/foo/bar.js', wantXrays: false, prototype: { console: { log: dump.bind(dump, 'log: '), info: dump.bind(dump, 'info: '), warn: dump.bind(dump, 'warn: '), error: dump.bind(dump, 'error: ') } } }); evaluate() Evaluates code in the supplied sandbox. If options.source is provided then its value is evaluated,
otherwise source is read from the supplied uri. Either way, any exceptions will be reported as from the uri. Optionally more options may be specified: options.encoding: source encoding, defaults to 'UTF-8'. options.line: line number to start count from in stack traces. Defaults to 1. options.version: version of JS used, defaults to '1.8'. // Load script from the given location to a given sandbox: e...
io/file - Archive of obsolete content
a file. Returns string : The last component of the given path. dirname(path) Returns the path of the directory containing the given file. If the file is at the top of the volume, the empty string is returned. Parameters path : string The path of a file. Returns string : The path of the directory containing the file. exists(path) Returns true if a file exists at the given path and false
otherwise. Parameters path : string The path of a file. Returns boolean : True if the file exists and false
otherwise. join(...) Takes a variable number of strings, joins them on the file system's path separator, and returns the result. Parameters ... : strings A variable number of strings to join. The first string must be an absolute path. Returns string : A single string formed by joining the...
tabs/utils - Archive of obsolete content
the new tab, but keep the currently selected tab selected. If false, make the new tab the selected tab. Optional, defaults to false. pinned boolean Pin this tab. Optional, defaults to false. Returns tab : The new tab. isTabOpen(tab) Test whether the specified tab is open. Parameters tab : tab A XUL tab element. Returns boolean : true if the tab is open,
otherwise false. closeTab(tab) Close the specified tab. Parameters tab : tab A XUL tab element. getURI(tab) Get the specified tab's URI. Parameters tab : tab A XUL tab element. Returns String : The current URI. getTabBrowserForTab(tab) Get the specified tab's tabbrowser. Parameters tab : tab A XUL tab element. Returns tabbrowser : getBrowserForTab(tab) Get the specified tab's browser. ...
ui/button/action - Archive of obsolete content
Include this parameter only if you are setting state. It is an object containing all the properties you wish to set. For example: button.state("tab", { "label" : "tab-specific label", "icon": "./tab-specific-icon.ico" }); To reset state, pass null: button.state("tab", null); Returns state : if you have passed the second state argument to make this function a setter, it returns undefined.
Otherwise, it functions as a getter and returns the button's state for the specified object. This logs the state for the button associated with the currently active tab: console.log(button.state("tab")); This object represents a snapshot of the state at the time state() is called. It is not kept up to date with changes made to the button: button.label = "foo"; var state = button.state(button); button.la...
ui/button/toggle - Archive of obsolete content
Include this parameter only if you are setting state. It is an object containing all the properties you wish to set. For example: button.state("tab", { "label" : "tab-specific label", "icon": "./tab-specific-icon.ico" }); To reset state, pass null: button.state("tab", null); Returns state : if you have passed the second state argument to make this function a setter, it returns undefined.
Otherwise, it functions as a getter and returns the button's state for the specified object. This logs the state for the button associated with the currently active tab: console.log(button.state("tab")); This object represents a snapshot of the state at the time state() is called. It is not kept up to date with changes made to the button: button.label = "foo"; var state = button.state(button); button.la...
util/collection - Archive of obsolete content
A simple list-like class and utilities for using it. Usage A collection is ordered, like an array, but its items are unique, like a set. Globals Constructors Collection([array]) Creates a new collection. The collection is backed by an array. Parameters array : array If array is given, it will be used as the backing array. This way the caller can fully control the collection.
Otherwise a new empty array will be used, and no one but the collection will have access to it. Functions addCollectionProperty(object, propName, [backingArray]) Adds a collection property to the given object. Setting the property to a scalar value empties the collection and adds the value. Setting it to an array empties the collection and adds all the items in the array. Parameters object : object The propert...
cfx - Archive of obsolete content
lows: { "configs": { "ff40": ["-b", "/usr/bin/firefox-4.0"] } } You can run: cfx test --use-config=ff40 And it would be equivalent to: cfx test -a firefox -b /usr/bin/firefox-4.0 This method of defining configuration options can be used for all of the run, build, and test tools. If "default" is defined in the local.json cfx will use that configuration unless
otherwise specified. Passing Static Arguments You can use the cfx --static-args option to pass arbitrary data to your program. This may be especially useful if you run cfx from a script. The value of --static-args must be a JSON string. The object encoded by the JSON becomes the staticArgs property of the system module. The default value of --static-args is "{}" (an empty object), so you don't have to ...
Dialogs and Prompts - Archive of obsolete content
ader> You can use the dialogheader element to add "headers" to windows. To get an idea of what it looks like, open Options (or Preferences) dialog in Firefox or Thunderbird (v1.0 and earlier only). The header to the right of the sections buttons is made with <dialogheader>: <dialogheader title="General" description="whatever"/> Note, that you should only use this element in a <dialog>, because
otherwise it may be not styled properly. (Although it seems to work in <window> as well). Programmatic button access If you want to access the accept ("OK") and cancel buttons from script, use this: // Disable the OK and Cancel btns document.documentElement.getButton("accept").disabled = true; document.documentElement.getButton("cancel").disabled = true; Links dialog.xml -- XBL bindings for <dialo...
File I/O - Archive of obsolete content
ntent type hint It's useful to provide a content type hint to prevent the file system from doing a potentially expensive content type look up (which would be synchronous I/O). In this case an nsIChannel object has to be explicitly created from the file: Components.utils.import("resource://gre/modules/NetUtil.jsm"); // Content type hint is useful on mobile platforms where the filesystem // would
otherwise try to determine the content type. var channel = NetUtil.newChannel(file); channel.contentType = "application/json"; NetUtil.asyncFetch(channel, function(inputStream, status) { ... }); Writing to a file Write a string This sample uses NetUtil.jsm and FileUtils.jsm. Components.utils.import("resource://gre/modules/NetUtil.jsm"); Components.utils.import("resource://gre/modules/FileUtils.jsm"...
Miscellaneous - Archive of obsolete content
See How to Build an XPCOM Component in Javascript for details. Now are your certificates installed on every application startup. Unfortunately that seems to be the only working solution, apart from modifying the Mozilla source code and recompiling. Generating Random Bytes Useful snippet for generating random bytes that can, for example be used as a good source for...
StringView - Archive of obsolete content
-like object based upon an ArrayBuffer. Arguments input (required) The argument the stringView is constructed from. It can be: another stringView a string a number an arrayBuffer a typed array of uint8Array, uint16Array, or uint32Array subclass any other kind of ordered object (like arrays, collections, etc.) If it is a number it will become the length of the new stringView;
otherwise it will become its content. The following table shows the behavior of the StringView constructor. input class stringView.buffer stringView.rawData stringView.bufferView StringView A new arrayBuffer will be created. Object reference to stringView.bufferView or a new arrayBufferView of stringView.buffer will be created (depending on startOffset an...
Custom about: URLs - Archive of obsolete content
URL for your extension. Setup for Firefox 4+ This is a simple example of a custom about page for bootstrapped addons. This example creates an about page with url about:myaboutpage which takes a user to a page that writes some text out. Make sure to generate a unique aboutPage_id, see this page to learn more about generating UUID's: UUID. It is imported to QueryInterface the Components.manager
otherwise this will not work. This example can be easily modified, just modify the global const at in the // globals section. In Bug 1254752 things changed for Firefox 48 and up. Services.io.newChannel was deprecated, and the signature of the newChannel method changed. This change is reflected in the code below. This code will work for all versions of Firefox 4 and up. const {classes: Cc, interfaces:...
Extension Packaging - Archive of obsolete content
an extension as part of the application installer, for example), you can install the extension files directly to <appdir>/extensions/<extensionID>. The extension will be found automatically by the extension manager the next time the application is launched. When using this method you must verify that the file system permissions for the directories, and files for the extension, are set properly.
Otherwise, the Extension Manager may not function properly with the extension, or the extension itself may not work properly. Including add-ons in a customized application A customized application can include add-ons, including extensions and themes, by placing the unpacked (that is, not the XPI files, but the packages' contents) in the <appdir>/distribution/extensions directory. This directory containin...
Install Manifests - Archive of obsolete content
tp://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <Description about="urn:mozilla:install-manifest"> <!-- properties --> </Description> </RDF> Some properties are required, some are optional. Some have simple string values, some are complex resources. Required Property Reference Your Install Manifest must specify these properties correctly
otherwise your add-on may not install. id The ID of the extension, which must be one of the following: GUID (Firefox 1.0) A string formatted like so: extensionname@example.org The latter format is significantly easier to generate and manipulate. Firefox 1.5 has checking to ensure that your id falls into one format or the other and will refuse to install add-ons that have malformed ids. You should n...
Appendix: What you should know about open-source software licenses - Archive of obsolete content
idering releasing its own software as open source, it should consider dual-licensing or the CPL. Applying a license to original works If you want to release your own code as open-source, here's what you do next. Insert the license declaration in the top of every file in your source code; Include the full text of the license in your source-code archive; Place the source code on a website or
otherwise make it accessible; Tell all your friends. If you are using the Modified BSD License or MPL, place the full text in the top, not just the license declaration. If you are using the GPL or LGPL, use the declaration at the end of the license's full text as a template and insert that. See below. GPL License Declaration Template If you develop a new program, and you want it to be of the greatest ...
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
er window. This string includes extensive information regarding every open window and tab, the forward/back history for each tab, page scroll position, text zoom, contents of form elements, etc. setWindowState(aWindow, aState, aOverwrite) Restores the browser window indicated by the parameter aWindow to the state indicated by aState. If aOverwrite is true, the currently open tab is overwritten;
otherwise, a new tab is created for the restored content. JavaScript debugging methods alert The easiest way to debug javascvript is using the window.alert method to display variables in a dialog (Listing 29). Except for asynchronous processes, all processing stops while the dialog is up, so this technique is useful when you want to pin down a value that can vary during a process. Listing 29: Check t...
Local Storage - Archive of obsolete content
ent storage. We recommend that you at least keep an error log, so that you can request error data from your users when you encounter problems that are hard to debug. We'll discuss logging in this section, but first let's look at the right (or at least, common and scalable) way of managing local files. It is strongly recommended that you keep your local files inside the Firefox profile directory.
Otherwise you may run into problems if the same extension is installed in multiple profiles. The common practice is to create a directory with the name of your project at the root of the profile folder, and keep your files inside. The structure could be something like this: s435L.default (your profile directory) XULSchool log.txt somedbfile.sqlite The Directory Servi...
Observer Notifications - Archive of obsolete content
Test method is called, all observers registered with xulschoolhello-test-topic will get notified and display two alerts. If there are 2 Firefox windows open, the observer will be notified in both and the alerts will show up on both. You can always listen for multiple notification topics using the same observer. Also, be careful not to add the same observer to a notification topic more than once,
otherwise the same code in the observer will be run several times when a notification is sent. Useful Firefox notifications We have covered sending and receiving custom notification topics using observers and the observer service. In Firefox, there are many built-in observer topics that you can observe as well. The Observer Notifications page lists some useful topics and is definitely worth spending time...
The Essentials of an Extension - Archive of obsolete content
for you to spot it, but this is not a recommended practice. Imagine if all extensions added menus to the top menu; having a few extensions would make it look like an airplane dashboard, full of knobs and switches. In the case of the unified menu, things are a little more difficult due to lack of options. If your menu item fits in the Web Developer section, it is recommended that you add it there.
Otherwise, the root menu might be your only recourse. One recommended location for menus in the classic menu vase is under the Tools menu, so the code should really look like this: <menupopup id="menu_ToolsPopup"> <menu id="xulschoolhello-hello-menu" label="&xulschoolhello.hello.label;" accesskey="&xulschoolhello.helloMenu.accesskey;" insertbefore="devToolsEndSeparator"> <menupopup> ...
XPCOM Objects - Archive of obsolete content
The rest of the code looks long and complicated, but it is pretty much the same for all components, so you shouldn't worry too much about it. All you have to do to use it in other components is copy it and change some names. The purpose of this code is to register the component so that you can get references to it just like all other Firefox components. It is better read ...
Session store API - Archive of obsolete content
ase, a TabOpen event is sent. The tab's persistent XUL attributes (those saved due to calls to persistTabAttribute()) and permissions are restored. The SSTabRestoring event is sent. The tab is told to load the URL it should be displaying. When the page is finished loading, text fields and scroll state are restored. Finally, the SSTabRestored event is sent. If you want to set permissions or
otherwise manipulate a restored tab before the page is loaded into it, you should watch SSTabRestoring. If you want to do something after the page is loaded, you should watch SSTabRestored. Both events are always sent for each tab being restored. You can determine which tab is being restored by looking at the event's originalTarget field. There's not really a way to determine when the last tab has been r...
Updating addons broken by private browsing changes - Archive of obsolete content
private browsing article explains further about the equivalent notifications, which are all backwards compatible through to Firefox 12 (and are sent side-by-side with the global private browsing notifications in older versions). Chrome APIs OpenBrowserWindow: Takes an optional parameter to indicate desired properties of the window. Passing {private: true} will cause a private window to open,
otherwise the window will always be non-private. Use {private: PrivateBrowsingUtils.isWindowPrivate(window)} to open a window that matches the current window's privacy status. openLinkIn: Can receive an extra private boolean property in the parameter object. internalSave: Takes a new required Document argument (prior to the optional boolean and string arguments) indicating the document that originate...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
decide to drop tables as a layout mechanism? It seems like most designers think that you have to have at least some tables for layout. I've been manually writing sample code for my own design prototypes for 4 or 5 years now. I used to pride myself in knowing how to reproduce any interface design down to a pixel-perfect level. A developer would tell me something wasn't possible, and I could prove
otherwise every time. Like other designers and html whizzes, I became a master at manipulating and troubleshooting tables, nesting them in intricate ways to produce any layout or effect that could be imagined. I remember one project for Lycos where we had nested tables 10 levels deep. I counted them myself. It wasn't that every level was absolutely necessary to reproduce the intended design effects. But e...
Case Sensitivity in class and id Names - Archive of obsolete content
Summary: Although CSS is itself case-insensitive, class and ID names are defined to be case-sensitive in HTML 4.01. Find out how this wrinkle can affect your site design and best practices to avoid any problems. In the authoring of both CSS and JavaScript/DOM (
otherwise known as DHTML) routines, it is a near-certainty that class and id names will be used to identify elements. We have discovered, however, that many authors are running into trouble with class and id names because they're used to the bugs of browsers that don't fully support open standards. The most common case is where the name uses different case in the document source than is found in the CSS or JavaScript. For example, there might be this CSS: p.Warning {color: red; background: yellow;} ...coupled with this HTML: <p cla...
Same-origin policy for file: URIs - Archive of obsolete content
tml, the load will succeed only if bar.html is either in the same directory as index.html or in a directory contained within the same directory as index.html. This policy affects anything that does same-origin checks, including XMLHttpRequest, XSLT, and XBL. For cross-window DOM access, each file is treated as a separate origin, with one exception: if a file is loaded from another file that would
otherwise be able to load it following this same-origin policy, they are considered to have the same origin. This load can occur through a subframe, link, location set, call to window.open(), or the like. For example, if the file /home/user/foo.html is a frameset and one of the frames is /home/user/subdir/bar.html, the frame and frameset are considered to share the same origin. On the other hand, if the ...
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
aded from local disk on Windows. Build Create a new project in Visual Studio for a Win32 GUI library (DLL) (in .NET 2003: Win32 template, then switch to DLL in Application Settings in the following dialog, export symbols too?)(in Visual Studio 2008, it is Visualc++|Win32|Win32 Project, then check DLL in the wizard). If a wizard gives you a checkbox to create an empty project, then check it.
Otherwise you'll delete files later. Again note that the resulting DLL filename must start with "np", so either call your project like this or rename the file later Delete the .cpp and .h and 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 (.cp...
Creating a Microsummary - Archive of obsolete content
Then just link to the microsummaries from within the pages themselves using a <link rel="microsummary"> element, f.e.: <head> <link rel="microsummary" href="index.php?view=microsummary"> </head> When Firefox encounters a <link rel="microsummary"> element, it loads the URL in the href attribute. If the URL points to a generator, it uses the generator to generate the microsummary for the page.
Otherwise, if the URL returns plain text content (or HTML content that can be converted to plain text), Firefox uses the content as the microsummary for the page. Beginnings Generators are expressed as XML documents whose root element is the <generator> element in the http://www.mozilla.org/microsummaries/0.1 namespace. To begin building the generator, create a new empty text file and add an XML declarat...
Drag and Drop JavaScript Wrapper - Archive of obsolete content
d as the first argument to onDragStart. We create a TransferData object which can be used to hold all the data to be dragged. We add two pieces of data to the transfer data. The first is a string of HTML text and the second is a string of plain text. If the user drops onto an area which can accept HTML (such as Mozilla's editor window), the HTML flavour will be used and the text will appear bold.
Otherwise, the plain text version will be used instead. Usually you will want to provide a text version of the data so that more applications can accept the data. The order that you define the flavours should be from the best match to the weakest match. In this case above, the HTML flavour (text/html) comes first and then the text flavour (text/unicode). The example below shows how to set the data to be dr...
Block and Line Layout Cheat Sheet - Archive of obsolete content
ze. e.g., because...why? BRS_ISINLINEINCRREFLOW This flag is set in nsBlockFrame::Reflow() if we detect that we're incrementally reflowing a linebox that contains inline frames. In this case, we can avoid some of the work that occurs during reflow. BRS_NOWRAP This flag is set in the nsBlockReflowState constructor when the "white-space" style of the block frame is pre or nowrap. It is cleared,
otherwise. BRS_ISTOPMARGINROOT This flag is set in the nsBlockReflowState constructor when reflowing a "block margin root" frame (i.e., a frame with the NS_BLOCK_MARGIN_ROOT flag set, for which margins apply by default). The flag is also set when reflowing a frame whose computed top border padding is zero. (why?) BRS_ISBOTTOMMARGINROOT This flag is set in the nsBlockReflowState constructor when reflowi...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
l for HTTP channels and drops the load on the floor if warranted (e.g. 204 or 205 responses). Then it calls nsDocumentOpenInfo::DispatchContent nsDocumentOpenInfo::DispatchContent starts doing the real dirty work. First it checks whether the channel has "Content-Disposition: attachment" set. If so, it skips trying to find an internal viewer and goes right over to looking for a stream converter.
Otherwise, DispatchContent goes through a three-step process to try to find the correct listener. The basic idea is that DispatchContent calls nsDocumentOpenInfo::TryContentListener on various content listeners; if that returns true, we have found the right listener and we are done. TryContentListener makes use of the IsPreferred and CanHandleContent functions on nsIURIContentListener and calls DoContent()...
JavaScript Client API - Archive of obsolete content
age for your data supports batch operations. createRecord The createRecord( id, collection ) method gets called by the engine to request a new record for an item with a given GUID. It's your Store's responsibility to instantiate a Record object, assign the given GUID, and return it. itemExists(guid) Should simply return true if an item with the given guid exists in the store, false
otherwise. changeItemID(oldId, newId) Must find the stored item currently associated with the guid oldId and change it to be associated with the guid newId. getAllIDs() Must return an iterable list containing the GUIDs of every item being stored on the local system. This can be a dictionary-type object where the keys are the GUIDs and the values are whatever; or it can simply be a list of G...
JavaScript crypto - Archive of obsolete content
or PKCS11_PUB_READABLE_CERT_FLAG = 0x1<<28; //Stored certs can be read off the token w/o logging in PKCS11_DISABLE_FLAG = 0x1<<30; //tell Mozilla to disable this slot by default Cipher flags Reserved Important for CryptoMechanismFlags 0x1<<11, 0x1<<12, ... , 0x1<<26, 0x1<<29, and 0x1<<31 are reserved for internal use in Mozilla. Therefore, these bits should always be set to 0;
otherwise, Mozilla might exhibit unpredictable behavior. Important for CipherFlags All values are reserved for internal use in Mozilla. Therefore, this flag should always be set to 0;
otherwise, Mozilla might exhibit unpredictable behavior. Example of CryptoMechanismFlags and CipherFlags pkcs11MechanismFlags = PKCS11_MECH_DSA_FLAG | PKCS11_MECH_SKIPJACK_FLAG | PKCS11_MECH_RANDOM_FLAG; pkcs11CipherFlags...
First run - Archive of obsolete content
tpack's manifest. A manifest is simply an object set to a variable named manifest. You may define this variable anywhere in the global namespace of your jetpack. It's the same manifest you use when defining settings for your jetpack. The value of firstRunPage must be either a string or E4X XML. If the value is a both a string and a valid URL, the page at that URL becomes your first-run page.
Otherwise, the value is assumed to be HTML, and it becomes the body of your first-run page. This example sets the first-run page to some HTML: var manifest = { firstRunPage: '<p>Thanks for installing! Visit my <a href="http://example.com/myJetpack">homepage</a>.</p>' }; This does the same but uses E4X XML: var manifest = { firstRunPage: <> <p> Thanks for installing! Visit my <a href="http:...
First Run - Archive of obsolete content
ur jetpack's manifest. A manifest is simply an object set to a variable named manifest. You may define this variable anywhere in the global namespace of your jetpack. It's the same manifest you use when defining settings for your jetpack. The value of firstRunPage must be either a string or E4X XML. If the value is a both a string and a valid URL, the page at that URL becomes your first-run page.
Otherwise, the value is assumed to be HTML, and it becomes the body of your first-run page. This example sets the first-run page to some HTML: var manifest = { firstRunPage: '<p>Thanks for installing! Visit my <a href="http://example.com/myJetpack">homepage</a>.</p>' }; This does the same but uses E4X XML: var manifest = { firstRunPage: <> <p> Thanks for installing! Visit my <a href=//ex...
Simple Storage - Archive of obsolete content
'll show a// disabled "(Empty)" menuitem.function updateJetpackMenu() { jetpack.menu.set({ label: "Notes", menu: new jetpack.Menu(notes.length > 0 ? notes : [{ label: "(Empty)", disabled: true }]) });}// Modify the page's context menu by sneaking in before it's shown. If there's// a selection, add a Note menuitem that makes a new note.
Otherwise, don't// modify the menu at all. We'll limit the number of notes to 20. Old notes// will be forgotten. :(jetpack.menu.context.page.beforeShow = function (menu) { menu.reset(); if (jetpack.selection.text) menu.add({ label: "Note", command: function () { notes.unshift(jetpack.selection.text); if (notes.length > 20) notes.pop(); updateJetpackMenu(); ...
Simple Storage - Archive of obsolete content
/ disabled "(Empty)" menuitem. function updateJetpackMenu() { jetpack.menu.set({ label: "Notes", menu: new jetpack.Menu(notes.length > 0 ? notes : [{ label: "(Empty)", disabled: true }]) }); } // Modify the page's context menu by sneaking in before it's shown. If there's // a selection, add a Note menuitem that makes a new note.
Otherwise, don't // modify the menu at all. We'll limit the number of notes to 20. Old notes // will be forgotten. :( jetpack.menu.context.page.beforeShow = function (menu) { menu.reset(); if (jetpack.selection.text) menu.add({ label: "Note", command: function () { notes.unshift(jetpack.selection.text); if (notes.length > 20) notes.pop(); updateJetpac...
Microsummary topics - Archive of obsolete content
e header to the string microsummary. Thus, to differentiate requests initiated manually by users for the purpose of viewing a web page from those initiated automatically by Firefox for the purpose of summarizing that page, check for the presence and value of the X-Moz request header. If the X-Moz header is present, and its value is microsummary, then the request is a microsummary-related request.
Otherwise, it is a user-initiated request. Controlling the frequency of microsummary requests When Firefox downloads content in order to update a microsummary, it honors cache-related HTTP response headers. Thus, if you would like to control how frequently Firefox initiates microsummary-related requests to your web server, you can do so by including an HTTP Expires or Cache-Control header in your response...
How to Write and Land Nanojit Patches - Archive of obsolete content
he copying process begins by writing a nanojit-central revision ID to the file nanojit-import-rev, held in your target repository. If you are at all confused about this, ask in #nanojit IRC. Scenario 4: if you break something If you land a patch that breaks nanojit-central, and then land a follow-up fix, it's a good idea to ensure the follow-up fix gets merged to TM and TR as soon as possible.
Otherwise, it might be possible that the broken patch gets pulled into TM/TR but the fix doesn't for quite some time, which will cause problems for others in the meantime. See https://bugzilla.mozilla.org/show_bug.cgi?id=529900 for an example. ...
New Security Model for Web Services - Archive of obsolete content
vices behind the firewall. Signed Scripts A certain degree of additional trust may be lent to a script by having the author digitally sign it. But signed scripts have not really caught on as they require certificates do not change the basic problem that some completely-unknown party has written a script that might now have access to internal resources. Asking the User Where the sandbox cannot
otherwise determine whether the executing script should be permitted access to the resource, a dialog box may be raised to ask the user to grant special privileges. This is currently permitted for locally-saved scripts and signed scripts. This could be combined with the other options above such as whitelisting, signed scripts, etc. But the big problem with this is that the typical browser user really does ...
Space Manager High Level Design - Archive of obsolete content
InDamage). During the incremental reflow of dirty lines the block frame may encounter lines that are NOT dirty. In this case the Space Manager is also asked if there is any float damage, and if there is then the block further checks to see if that damage intersects the area of the non-dirty line, marking it dirty if there is intersection. Thus, changes to floats on other lines may cause impact to
otherwise clean lines, and the Space Manager facilitates the detection of this. Data Model Class/Component Diagram nsSpaceManager: The central point of management of the space taken up by floats in a block nsBandData: Provides information about the frames occupying a band of occupied or available space nsBlockBandData: A specialization of nsBandData that is used by nsBlockReflowState to determine...
Merging TraceMonkey Repo - Archive of obsolete content
merge. Merge via hg merge You may see a number of conflicts. Conflicting files can be listed via hg resolve -l. Exercise caution, because leaving off the -l will re-merge and lose all of the resolutions you've already performed. For each unresolved file (with a U next to it), open the file and find the conflict markers that look like <<<<<<. If it's obvious how to fix the conflict, just do it.
Otherwise, you can run hg parents filename to find the changesets which may have contributed to the conflict. Inspecting the files at those two changesets can be helpful: hg cat -c changeset filename Once all the conflict markers are removed, you've performed the manual resolution, which you tell to mercurial by running hg resolve -m filename. Again, exercuse caution. Once you've resolved all the files,...
Actionscript Acceptance Tests - Archive of obsolete content
e is defined, the output from the testcase is matched line by line to the .out file and any difference is considered a failure. May be used in conjunction with a .exitcode file. testname.abc_ For special cases where the .as source is not available (e.g. fuzzed files) it is possible to check in a .abc_ which will let the test harness run compiled files without source. The underscore is necessary
otherwise the buildbot system will delete the .abc before starting up a testrun (not an issue when running locally, but makes it easy to differentiate between binary-only abc files and generated abcs. Support Directories In some cases a test may require additional files to successfully run. There are two kinds of support directories available. Files to be included when compiling the test: If a test requir...
URIs and URLs - Archive of obsolete content
ot known if an authority segment exists or not, less syntax correction can be applied in this case. Noteable Differences Necko does not support certain deprecated forms of relative URLs, based on the following part of RFC 2396: If the scheme component is defined, indicating that the reference starts with a scheme name, then the reference is interpreted as an absolute URI and we are done.
Otherwise, the reference URI's scheme is inherited from the base URI's scheme component. Due to a loophole in prior specifications (RFC1630), some parsers allow the scheme name to be present in a relative URI if it is the same as the base URI scheme. Unfortunately, this can conflict with the correct parsing of non-hierarchical URI. For backwards compatibility, an implementation may work around such referen...
Using cross commit - Archive of obsolete content
ZILLA_1_8_BRANCH layout/base/nsCaret.h # Modify the files (probably by applying the patch) patch -p0 < ~/caret.patch # Commit on all the branches at once # Make sure to use -m "Commit message" when doing so tools/cross-commit --moz18 --branch MOZILLA_1_8_0_BRANCH -m "Fix some sort of security bug" layout/base/nsCaret.h Notes Note that you MUST use a -m option with a CVS checkin message.
Otherwise cross-commit will end up waiting forever for you to type a CVS checkin message in an editor that it never shows you! (Although it works without specifying -m on the command line if you are using X-enabled emacs on Linux.) Also note that if you don't specify any branches to commit on, cross-commit will commit to the trunk and the MOZILLA_1_8_BRANCH by default. Details cross-commit accepts the f...
XML in Mozilla - Archive of obsolete content
le XLinks, and manipulation of XML with scripts via DOM. There is an XML component in Bugzilla. We also have the "xhtml" keyword for XHTML bugs (these tend to be scattered across components). How can I help? If you can code, look for helpwanted keyword in XML bugs. We don't use that always, so if you want to avoid doing duplicate work you could start working on bugs that have Future milestone, or
otherwise have a milestone that is set way into the future. You can always test our XML support. We'd really like to get tests that can be run automatically (this would require knowledge of web development; document.load() and/or XML Extras might be needed), but probably most of the bugs we get have just been found by normal people trying to do something that works in some other browser and does not work i...
compareTo - Archive of obsolete content
. rev Revision number. bld Build number. version An InstallVersion object or a String representing version information in the format "4.1.2.1234". Returns If the versions are the same, this method returns 0. If this version object represents a smaller (earlier) version than that represented by the version parameter, this method returns a negative number.
Otherwise, it returns a positive number. In particular, this method returns one of the following values: -4 This version object has a smaller (earlier) major number than version. -3 This version object has a smaller (earlier) minor number than version. -2 This version object has a smaller (earlier) release number than version. -1 This version obj...
confirm - Archive of obsolete content
n BUTTON_TITLE_NO: A 'No' button BUTTON_TITLE_SAVE: A 'Save' button BUTTON_TITLE_DONT_SAVE: A 'Don't save' button BUTTON_TITLE_REVERT: A 'Revert' button BUTTON_TITLE_IS_STRING: Custom title specified by the corresponding aButtonXTitle parameter Other constants BUTTON_POS_0_DEFAULT: Specifies button 0 as the default button. Unless specified
otherwise, this is the default. BUTTON_POS_1_DEFAULT: Specifies button 1 as the default button. BUTTON_POS_2_DEFAULT: Specifies button 2 as the default button. BUTTON_DELAY_ENABLE: Specifies that the buttons should only become clickable after a certain delay. Note that this only applies to buttons 0 and 2, not button 1 (the "cancel" button). STD_OK_CANCEL_BUTTONS: Use this instead o...
writeString - Archive of obsolete content
ges a value in a .ini file. Method of WinProfile object Syntax Boolean writeString ( String section, String key, String value); Parameters The method has the following parameters: section Section in the file, such as "boot" or "drivers". key The key in that section whose value to change. value The new value. Returns True if successfully scheduled,
otherwise, false. Description The writeString method is similar to the Windows API function WritePrivateProfileString. To delete an existing value, supply null as the value parameter. Unlike the WritePrivateProfileString function, this method does not support using a null key to delete an entire section. Values are not actually written until performInstall is called. Example To set the name of the wallpa...
valueExists - Archive of obsolete content
sts Returns whether a value for the given key exists. Method of WinReg object Syntax boolean valueExists ( string key, string value ); Parameters The method has the following parameters: key A string representing the path to the key. value A string representing the value being queried. Returns Boolean value: true if the key exists and the user has read access to it,
otherwise false. Example winreg = getWinRegistry(); if ( winreg != null ) { winreg.setRootKey( winreg.HKEY_LOCAL_MACHINE); if(winreg.valueExists("SOFTWARE\\mozilla", "value name")) { //valueExists returned true } else { //valueExists returned false } } ...
accesskey - Archive of obsolete content
. On the Macintosh, labels are never underlined, however accesskeys can still be used by pressing the letter combined with the Command key. *(These are the keys corresponding to event.ctrlKey and event.metaKey respectively when listening to key events) Although the value is case insensitive, a letter with the case matching the accesskey attribute will be used if both cases exist in the label.
Otherwise, if the label has two or more characters which are same as its accesskey, the first of those characters in the label will be underlined. If a label doesn't have the specified character, the character will be appended to the label with parentheses. For example, when an accesskey of an 'Open' label is 'A', the generated label will be 'Open (A)'. However, if the last character of the label is an e...
allowevents - Archive of obsolete content
On listitem and titlebar elements, mouse events normally do not get sent to their children; instead they are retargeted to the listitem and titlebar element itself. This means that elements placed inside a listitem do not respond to events, and instead clicking the mouse simply selects that item within the list. By setting the allowevents attribute to true, this special behavior is disabled, and the events are targeted the same as other elements. ...
datasources - Archive of obsolete content
urce is used, either the URL of an XML file or an anchor reference to another element within the same document. For instance, the reference '#data' refers to an element with the id 'data'. If you plan on adding a datasource to an element but don't want one to be added right away, set this attribute to 'rdf:null'. This will make the element so that its contents can be generated from a datasource.
Otherwise, you cannot add one later. When the XUL document is contained on a remote web site, the datasources may only be loaded from the same domain as the document. ...
panel.level - Archive of obsolete content
<< XUL Reference home level Type: one of the values below Specifies whether the panel appears on top of all windows, or just on top of the window the panel is in. If this attribute is not set, the popup window level depends on the platform. On Linux, the default value is top,
otherwise, the default value is parent. If a panel has one or more text fields, this attribute should not be set,
otherwise IME or on-screen keyboard popups will appear incorrectly. For these reasons, you should avoid setting the level if not needed. top The panel is shown in front of all other normal windows, including those of other applications. parent The panel is shown just above the window the panel is in, but behind other windows above it. If anchored, the child window maintains its relative pos...
panel.type - Archive of obsolete content
is for a panel that provides a tree for an autocomplete element. autocomplete-richlistbox Specify this for a panel that provides a richlistbox for an autocomplete element. arrow Specify this for a panel that provides an arrow pointing at its anchor. drag Specify this for a panel that's being used as a drag image for a drag and drop operation.
Otherwise leave this attribute out. For example, the site identity panel that appears when you click on the favicon in the URL bar in Firefox is an arrow panel: Note: The arrow will draw as long as the panel doesn't overlap the anchor. If they overlap, the anchor won't be drawn. The panel may not appear on the side of the anchor that you requested in which case the arrow will automatically adjust. ...
sizetopopup - Archive of obsolete content
<< XUL Reference home sizetopopup Type: one of the values below Indicates how the menu width and the menupopup width are determined. If the sizetopopup attribute is left out or set to none, the menu will be its preferred width and the popup may extend outside of this width, unaffected by the maximum width of the menu itself.
Otherwise, the menu will size itself to at least the size of the popup. If the menu has a maximum width, the popup will also be this width. none The width of the popup will not be constrained to the size of the menu. pref The preferred width of the menu label or button will be the size needed for the popup contents. This is the default value for menulists. always Both the preferred and minimum width of the menu label or button will be the same as th...
treecol.type - Archive of obsolete content
ndow. text The content of the columns is text. If you are using type="checkbox", then the tree and each treecol must be editable. You need to apply CSS to make the checkbox toggle. Here is an example CSS style using the current theme's checkboxes: treechildren::-moz-tree-checkbox { /* unchecked checkbox treecells. This style MUST come before treechildren::-moz-tree-checkbox(checked)
otherwise it won't take effect. */ list-style-image: none; } treechildren::-moz-tree-checkbox(checked) { /* checked checkbox treecells. cbox-check.gif isn't available in Firefox 1, 2, and 3 in Mac OS X so you should specify a URL to an image in your extension or elsewhere. */ list-style-image: url("chrome://global/skin/checkbox/cbox-check.gif"); } treechildren::-moz-tree-checkbox(disabled) ...
wait-cursor - Archive of obsolete content
Reference home wait-cursor Type: boolean Set this attribute to true to have the cursor switch to a waiting cursor while the mouse is hovering over the element. Usually, you would only use this on the window element or other top-level elements. In order to revert to the normal cursor state call the method removeAttribute("wait-cursor") when the process effectively has ended
otherwise the wait cursor might never disappear. See also https://developer.mozilla.org/docs/Talk:XUL/Attribute/Wait-cursor This seems to work instead of trying to set a wait-cursor attribute: window.setCursor('wait') and window.setCursor('auto') ...
command - Archive of obsolete content
ndow of the document) detail Read only long (float) Unused; always zero. sourceEvent Read only Event The activation event that caused this command event to be generated. Currently only set when a command event is redirected though use of the command attribute. ctrlKey Read only boolean true if the control key was down when the event was fired. false
otherwise. shiftKey Read only boolean true if the shift key was down when the event was fired. false
otherwise. altKey Read only boolean true if the alt key was down when the event was fired. false
otherwise. metaKey Read only boolean true if the meta key was down when the event was fired. false
otherwise. Example menuitem.oncommand = function() { c...
Working With Directories - Archive of obsolete content
fies the file object, rather than returning a new one. Both files and directories are represented using the same kind of object so most of the functions available for nsIFile will work for both. You can check if the object refers to a directory or a file by using nsIFile.isDirectory(). This method returns true if a file object returned by nsIScriptableIO.getFile() refers to a directory, and false
otherwise. There is also a corresponding nsIFile.isFile() method to check if an object refers to a file. In both cases, the method fails if the file or directory does not exist, so you should check first using nsIFile.exists(). var dir = IO.getFile("Desktop", "myfiles"); dir.append("pictures"); if (dir.exists() && dir.isDirectory()) alert("This is a directory"); Creating Directories You can create a new...
Getting File Information - Archive of obsolete content
e written to. nsIFile.isExecutable() - returns true if the file can be executed. nsIFile.isHidden() - returns true if the file is hidden. In this example, an exeception will occur if the file cannot be written to. if (!file.isWritable()) throw "File cannot be modified"; If you aren't sure whether a file can be modified, for example, you may wish to check using nsIFile.isWritable() first.
Otherwise, an attempt to write to the file will generate an error. The four methods above are usually sufficient for most purposes. However, you can also use the permissions (nsIFile.Attributes) attribute to get the UNIX-style permission flags for a file. This attribute is also necessary if you need to modify the permissions. file.permissions = 0640; It is common to use an octal number (a number in bas...
International characters in XUL JavaScript - Archive of obsolete content
racters. Earlier versions always interpreted JS files loaded from XUL as ISO-8859-1 (Latin-1), in both local and remote cases. Unicode escapes, as discussed below, have always worked. How the character encoding is determined in Gecko 1.8 and later When the JavaScript file is loaded from a chrome:// URL, a Byte Order Mark (FIXME: )(BOM) is used to determine the character encoding of the script.
Otherwise, the character encoding will be the same as the one used by the XUL file (which can be specified using an encoding attribute in the <?xml?> tag). By default this will use UTF-8, which can represent virtually all characters in the world. If the script file is loaded via HTTP, the HTTP header can contain a character encoding declaration as part of the Content-Type header, for example: Content-Typ...
insertItem - Archive of obsolete content
< XUL Reference home insertItem( id, beforeNode, wrapper, beforePermanent ) Not in SeaMonkey 1.x Return type: element Add an item with the given id to the toolbar. The new item is added just before the item given by the second argument. If the second argument is null, but the beforePermanent argument is true, the item is added to the beginning of the toolbar before the first permanent item.
Otherwise, if the beforePermanent argument is false, the new item is added to the end of the toolbar. The third argument can be used to wrap the new item in another element. Usually, the last argument will be null as it is mainly for the use of the customize dialog. The id should match an element in the toolbar's toolbarpalette. Some special ids may also be used to create special spacing items: separa...
Extensions - Archive of obsolete content
oLink True if the target is a link to an email address (a mailto: link). linkURL The URL of the link that was context clicked. inFrame True if the context click occured from within a frame. isTextSelected True if text is selected. (Note: was removed from Thunderbird 3 - see bug 463003 for a replacement) isContentSelected True if anything, text or
otherwise, is selected. In the following example, the menuitem is hidden unless the target is an image or a link. function ThumbnailsShowHideItems(event) { var show = document.getElementById("thumbnail-show"); show.hidden = !(gContextMenu.onImage || gContextMenu.onLink); } ...
MenuItems - Archive of obsolete content
ner, it will already be in the new state. <script> function changeToolbarState(event) { if (event.target.getAttribute("checked") == "true") showToolbar(); else hideToolbar(); } </script> ... <menuitem label="Show Toolbar" accesskey="T" type="checkbox" oncommand="changeToolbarState();"/> In this example, we show the toolbar when the menuitem is checked and hide the toolbar
otherwise. There may be times when you do not want the checkbox state to be updated automatically when the menuitem is activated. This can be useful if there's a possibility that whatever action is carried out could fail. One possibility is to simply reverse the checkbox state again. As this can be more complicated, it is also possible to use the autocheck attribute to disable this behavior. When the auto...
MenuModification - Archive of obsolete content
ly to the menu. The appendChild method is available for all elements, and is used to add new nodes within another node. The appendItem method is specific to menus, as well as some other specific elements, and is simpler to use to append new menuitem elements to a menu. If we were to use the example above, we would also want to make sure to remove the items again in a popuphiding event listener.
Otherwise, a new submenu would be added every time the menu is opened, which is clearly not desirable. Another possibility is to ensure that the menu is only added once. The following shows how the addSubMenu function above might be rewritten to handle this case. <script> function addSubMenu() { var popup = document.getElementById("file-popup"); if (popup.hasChildNodes()) return; var newmenu = ...
OpenClose - Archive of obsolete content
e popuphiding or popuphidden events may not fire as the element the events would be fired on are no longer available. If you need to perform uninitialization that would be done during these events, this could be done during an unload event. Testing Menu Open State To check if a menu is open, check the state of the menu's open property. If the open property is set to true, then the menu is open,
otherwise the menu is closed. var open = somemenu.open; Opening a Popup For opening menupopups that use the menu tag, the button tag and the toolbarbutton tag, see Opening Menus above. Popups attached using the popup attribute will be opened when the user clicks the mouse with the left mouse button. There isn't a means of replicating this action with the keyboard, so you should always provide an alter...
Additional Template Attributes - Archive of obsolete content
gh you can use either even if you specify the member variable). This may make the code clearer as to its function. We could use the container variable ?start in the action body also. If you are using the simple syntax and want to use the container variable in the content, you must use the container attribute since there is no other way to refer to it. Note also that a rule element is needed here,
otherwise the builder will think the container and member attributes are conditions to check. << PreviousNext >> ...
Filtering - Archive of obsolete content
"); triple.setAttribute("predicate", "http://www.xulplanet.com/rdf/country"); } triple.setAttribute("object", country); cond.appendChild(triple); } else if (triple) { cond.removeChild(triple); } document.getElementById("photosList").builder.rebuild(); } The 'country' argument to the applyFilter function holds the value to filter by. If this is set, we add a filter,
otherwise we remove it. The code is fairly straightforward. A new <triple> element is created and the object attribute is set to the value to filter by. For example, the resulting triple for the Netherlands might be: <triple subject="?photo" predicate="http://www.xulplanet.com/rdf/country" object="http://www.daml.org/2001/09/countries/iso#NL"/> This triple is then appended to the query. T...
Introduction - Archive of obsolete content
t.com/ds/sample.rdf', using the datasource type rdf as indicated by the querytype attribute'. We'll look at RDF datasources first. The template builder loads an RDF datasource using the RDF service in the same way as you would create a datasource through the RDF service directly. The datasource is loaded via its URL. Some RDF datasources are provided with Mozilla -- their URL's start with 'rdf:'.
Otherwise, the datasource is loaded as any other URL is loaded. If the datasource is already loaded and cached, the template builder can begin work right away.
Otherwise, there isn't anything to do until the data is loaded. Actually, this isn't quite true. The RDF service starts the loading of the datasource in the background, and the template builder goes through the process of building content anyway. Na...
XML Templates - Archive of obsolete content
ouspeople" ref="*" querytype="xml"> <template> <query expr="person"/> <action> <listitem uri="?" label="?name"/> </action> </template> </listbox> Here, an anchor reference, starting with a number sign (#) is used for the datasources attribute. It refers to an element with that id (without the number sign) and uses that node as the source XML node instead of a separate file.
Otherwise the data included inline and the template are the same. Note the only change is that the addition of the xmlns attribute on the data; this is used to clear the namespace used for the elements in the data,
otherwise they become XUL elements. You can also specify a namespace. If so, you will need to ensure that prefixes are defined within the template as well, so that they can be used in the XPath ...
Textbox (XPFE autocomplete) - Archive of obsolete content
ner input element. isSearching Type: boolean This property is set to true while a search is occuring. isWaiting Type: boolean This property is set to true during the period while waiting for the timeout between the time when a user has pressed a key and a search is performed. label Type: string Sets the label attribute. Gets the label attribute if it is present and not empty.
Otherwise it returns the value of the associated label element, if applicable.
Otherwise it returns the placeholder or emptyText property. The getter is mostly useful for screen readers. Note: Prior to Firefox 3, and always in Thunderbird and SeaMonkey, the label property of an autocomplete textbox returns its value, for compatibility with the menulist element. maxLength Type: integer The max...
Adding Methods to XBL-defined Elements - Archive of obsolete content
m2) { if (num1 <= num2) return num2; else return num1; } XBL: <method name="getMaximum"> <parameter name="num1"/> <parameter name="num2"/> <body> if (num1 <= num2) return num2; else return num1; </body> </method> This function, getMaximum, returns the largest of the values, each passed as a parameter to the method. Note that the less-than symbol has to be escaped because
otherwise it would look like the start of a tag. You can also use a CDATA section to escape the entire block of code. You can call the method by using code such as element.getMaximum(5, 10) where element is a reference to an element defined by the XBL containing the getMaximum method. (The bound element.) The parameter tag allows you to define parameters for a method. Because Mozilla uses JavaScript as it...
Additional Install Features - Archive of obsolete content
te() files. Thus, you can move files that might conflict with your package out of the way. Handling Errors You will likely want to handle errors gracefully. This will occur if a file or directory cannot be found, there is insufficient disk space or for a number of other reasons. You can use the getLastError() function to determine whether an error occured. If it returns SUCCESS, no error occured.
Otherwise, the number will be an error code which indicates the type of error that occured. You can call this function at any point during the installation script to determine whether an error occured during the last operation. If an error occurs, you will likely want to abort the installation. You may also want to display an error message to the user. For example, you might put the following as the last s...
Grids - Archive of obsolete content
ll be flexible vertically because both rows are flexible, although the first row is more so. The cell in the first column and first row (the Cherry button) will be flexible by a factor of 5 horizontally and flexible by a factor of 10 vertically. The next cell, (Lemon) will only be flexible vertically. The flex attribute has also been added to the grid element so that the entire grid is flexible,
otherwise it would only grow in one direction. Column Spanning There is no means of making a cell span a particular number of multiple columns or rows (See Discussion for a way of achieving the same effect). However, it is possible to make a row or column that spans the entire width or height of the grid. To do this, just add an element inside the rows element that isn't inside a row element. You can us...
Localization - Archive of obsolete content
files, you can just put the DTD file in the same directory as the XUL file. Note: You should encode DTD files as UTF-8 for non-ASCII characters. That is, you should save them in UTF-8 format (without BOM). For more information, see Mozilla Language Packs. Once you have created a DTD file for your XUL, you will need to add a line to the XUL file which indicates that you want to use the DTD file.
Otherwise, errors will occur as it won't be able to find the entities. To do this, add a line of the following form somewhere near the top of the XUL file: <!DOCTYPE window SYSTEM "chrome://findfile/locale/findfile.dtd"> This line specifies that the URL indicated is to be used as a DTD for the file. In this case, we have declared that we want to use the findfile.dtd DTD file. This line is typically plac...
Manifest Files - Archive of obsolete content
f smaller files. The xpcnativewrappers=yes part at the end of the manifest line is a flag that may optionally be used. In JavaScript, it is possible for a web page to override built-in functions with their own code. If the xpcnativewrappers flag is specified, it indicates that scripts running in a privileged context don't call these overridden versions, but the original built-in versions instead.
Otherwise, if an extension attempted to call the modified versions, it would likely not work properly, or worse, create a security hole. This flag was added to prevent this problem and should always be used for newer extensions, but is left out for older extensions that might not be compatible with the change. For more information about this feature, see XPCNativeWrapper. Themes and Locales The themes and ...
Tabboxes - Archive of obsolete content
e tab pages. Note that changing the orientation of the tabpanels element will have no effect, since the tabbed pages are layered on top of each other. You can place the tabs on the right or bottom side by moving the tabs element to after the tabpanels element in your code. Alternatively, you could set the dir attribute to reverse on the tabbox. However, you should probably leave the tabs on top,
otherwise they might not look very good under particular themes. Adding Tabs to our Find Files Dialog Let's add a second panel to the find files dialog. We'll create an Options tab (and select it by default) that will contain some options for searching. This may not be the best interface for doing this, but we'll use it to demonstrate tabs. The label across the top and the search criteria box will need ...
Tree Selection - Archive of obsolete content
<< PreviousNext >> The section will describe how to get and set the selected items in a tree. Getting the Selected Tree Items Each item in a tree (that corresponds to treeitem element, if using content tree view) may be selected individually. If you add the seltype attribute to the tree, set to the value single, the user may only select one row at a time.
Otherwise, the user may select multiple rows, which will not necessarily be contiguous. The tree provides a number of functions which can be used to determine whether an item is selected. Handling the Select Event First, let's see how we can determine when an item is selected. The onselect() event handler may be added to the tree element. When the user selects an item from the tree, the event handler is called. The user may also change the...
Tree View Details - Archive of obsolete content
that it returned true for those elements. getParentIndex: function(idx) { if (this.isContainer(idx)) return -1; for (var t = idx - 1; t >= 0 ; t--) { if (this.isContainer(t)) return t; } } The getParentIndex will need to find the parent of a given index. In our simple example, there are only two levels, so we know that containers don't have parents, so -1 is returned for these items.
Otherwise, we just iterate backwards through the rows looking for one that is a container. Next, the getLevel function: getLevel: function(idx) { if (this.isContainer(idx)) return 0; return 1; } The getLevel function is simple. It just returns 0 for container rows and 1 for non-containers. If we wanted to add an additional level of children, those rows would have a level of 2. hasNextSibling: funct...
Trees - Archive of obsolete content
</treeitem> </treechildren> </tree> As can be seen in the image, the tree has been created with two rows of data. This tree has two columns, the second of which will take up more space than the first. You will usually make the columns flexible. You can also supply widths with the width attribute. You should include the same number of treecol elements as there are columns in the tree.
Otherwise strange things might happen. The header row is created automatically. The button in the upper right corner can be used to hide and show the columns. You can place a hidecolumnpicker attribute on the tree and set it to true if you would like to hide this button. If this button is hidden, the user will not be able to hide columns. Make sure that you set an id attribute on each column or the hidin...
XUL Event Propagation - Archive of obsolete content
ndler function, whether to register a capturing listener); The event handler code argument can be in-line code or a function. The last boolean parameter specifies whether the event listener wants to use event capturing, or be registered to listen for events that bubble up the hiearchy normally. Note: The DOM provides the addEventListener method for creating event listeners on nodes that do not
otherwise supply them. But in XUL, almost every element includes an "oncommand" event listener attribute for getting events. addEventListener is the way to register event listeners for events other than the generalized "command" event, and the way to register a particular element for event capture, which preempts the regular flow of events. Original author: Ian Oeschger Other Documents: W3C DOM Events, M...
assign - Archive of obsolete content
to assign a value to. For more information, see XML_Assignments Attributes expr, var Examples (example needed) Attributes expr Type: string For XML queries, an XPath expression which returns results. Any namespace prefixes declared on the element may be used within the expression. var Type: string For the XUL assign attribute, this is the variable to assign the value to;
otherwise it's a reference to a template variable such as "?name". Inherited from XUL element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ord...
key - Archive of obsolete content
ment doesn't handle any key events. For example: <!-- This element handles all key events --> <key/> <!-- These elements don't handle any key events --> <key key="" modifiers="control"/> <key keycode="" modifiers="control"/> Modifying attributes In case you want to change one of the <key>'s attributes, such as the modifiers attribute, the keyset element has to be re-added to its parent node;
otherwise the new attributes won't be applied. For example: // modify some attributes let key = document.getElementById(KEY_ID); key.setAttribute("modifiers", "alt shift"); // apply the changes let keyset = document.getElementById(KEYSET_ID); keyset.parentNode.appendChild(keyset); ...
menuitem - Archive of obsolete content
des an assigned key set in the key attribute. This attribute does not apply to menus directly on the menubar. accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. allowevents Type: boolean If true, events are passed to children of the element.
Otherwise, events are passed to the element only. autocheck Type: boolean If this attribute is true or left out, the checked state of the button will be switched each time the button is pressed. If this attribute is false, the checked state must be adjusted manually. When autocheck is true, the button type should be "checkbox" or "radio". checked Type: boolean Indicates whether the elem...
menulist - Archive of obsolete content
change the value of the element. However, the value may still be modified by a script. sizetopopup Type: one of the values below Indicates how the menu width and the menupopup width are determined. If the sizetopopup attribute is left out or set to none, the menu will be its preferred width and the popup may extend outside of this width, unaffected by the maximum width of the menu itself.
Otherwise, the menu will size itself to at least the size of the popup. If the menu has a maximum width, the popup will also be this width. none The width of the popup will not be constrained to the size of the menu. pref The preferred width of the menu label or button will be the size needed for the popup contents. This is the default value for menulists. always Both the preferred and mini...
menuseparator - Archive of obsolete content
s an assigned key set in the key attribute. This attribute does not apply to menus directly on the menubar. accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. allowevents Type: boolean If true, events are passed to children of the element.
Otherwise, events are passed to the element only. command Type: id Set to the id of a command element that is being observed by the element. crop Type: one of the values below If the label of the element is too big to fit in its given space, the text will be cropped on the side specified by the crop attribute. An ellipsis will be used in place of the cropped text. I...
prefpane - Archive of obsolete content
ents paneload This event is fired on the pane element when the pane is fully loaded (e.g. after the overlay is merged.) You can put the handler for this event in the onpaneload attribute on the element. Using multiple prefpanes Note that when using multiple prefpanes in the same prefwindow, you must not put the <script> elements above the prefpane elements, but instead below them.
Otherwise the dialog will show erratic behavior and not display correctly. Place the <script> tags as in the following example for preference dialogs to work correctly: <prefwindow> <prefpane id="paneGeneral" label="General"> ... </prefpane> <prefpane id="paneSecurity" label="Security"> ... </prefpane> <script type="application/javascript" src="chrome://myext/content/script0.js"> <scr...
treecol - Archive of obsolete content
systems other than Mac OS X already use these styles by default. If targeting Firefox for Mac OS X, be sure to use these styles but include your own checkbox image. However, chrome://global/skin/checkbox/cbox-check.gif is available in SeaMonkey on Mac OS X.. treechildren::-moz-tree-checkbox { /* unchecked checkbox treecells. This style MUST come before treechildren::-moz-tree-checkbox(checked)
otherwise it won't take effect. */ list-style-image: none; } treechildren::-moz-tree-checkbox(checked){ /* css for checked cells. cbox-check.gif isn't available in Firefox 1, 2, and 3 on Mac OS X, so you should specify a URL to an image in your extension or elsewhere. */ list-style-image: url("chrome://global/skin/checkbox/cbox-check.gif"); } For example: Create a CSS file. Copy and past...
window - Archive of obsolete content
entById() and other DOM functions and to reference the element in style sheets. inactivetitlebarcolor Type: color string Specify background color of the window's titlebar when it is inactive (background). Moreover this hides separator between titlebar and window contents. This affects only on Mac OS X. lightweightthemes Type: boolean true if the window supports lightweight themes,
otherwise false. lightweightthemesfooter Type: id Specifies the ID of an element to which a lightweight theme's footer image will be applied. screenX Type: integer The horizontal position at which the window appears on the screen. screenY Type: integer The vertical position at which the window appears on the screen. sizemode Type: one of the values below The state of the window...
toolkit.singletonWindowType - Archive of obsolete content
ine"); By default, the toolkit.defaultChromeURI preference will cause XULRunner to open a new main application window each time an application is invoked. The toolkit.singletonWindowType preference causes XULRunner to search for a window with the attribute windowtype as specified in this preference (e.g. <window windowtype="xulmine"> in our example). If such a window is found, it will be re-used,
otherwise a new window will be opened. More information on this can be found in bug 317811. See also: XULRunner:Specifying Startup Chrome Window, toolkit.defaultChromeFeatures ...
Mozprocess - Archive of obsolete content
This documentation is no longer maintained. For more information about mozprocess as part of the mozbase project, please see the mozbase project page. mozprocess provides python process management via an operating system and platform transparent interface to Mozilla platforms of interest. Mozprocess aims to provide the ability to robustly terminate a process (by timeout or
otherwise), along with any child processes, on Windows, OS X, and Linux. Mozprocess utilizes and extends subprocess.Popen to these ends. API mozprocess.processhandler:ProcessHandler is the central exposed API for mozprocess. ProcessHandler utilizes a contained subclass of subprocess.Popen, Process, which does the brunt of the process management. Basic usage: process = ProcessHandler(['command', '-line', 'arguments'],...
Archived Mozilla and build documentation - Archive of obsolete content
uld consult an attorney with expertise in the particular laws and regulations that apply in your jurisdiction. Mozprocess mozprocess provides python process management via an operating system and platform transparent interface to Mozilla platforms of interest. Mozprocess aims to provide the ability to robustly terminate a process (by timeout or
otherwise), along with any child processes, on Windows, OS X, and Linux. Mozprocess utilizes and extends subprocess.Popen to these ends. Nanojit Nanojit is a small, cross-platform C++ library that emits machine code. Both the Tamarin JIT and the SpiderMonkey JIT (a.k.a. TraceMonkey) use Nanojit as their back end. New Skin Notes Devmo has a new skin that is ...
The global XML object - Archive of obsolete content
oreProcessingInstructions = false; var element = <foo> <?process x="true"?> <bar/> <?process x="false"?> </foo>; element.toXMLString(); // returns <foo><?process x="true"?><bar/><?process x="false"?></foo> ignoreWhitespace true by default. Ignores whitespace between nodes and leading and trailing whitespace in text nodes, which would
otherwise be interpreted as text nodes or as part of those text nodes, respectively. prettyPrinting true by default. When true, toXMLString() includes newlines and indenting for the serialization of E4X objects. prettyIndent 2 by default. The number of spaces to indent each level in the XML tree. Ignored if prettyPrinting is false. << Previous ...
Iterator - Archive of obsolete content
over enumerable properties of an object. Syntax Iterator(object, [keyOnly]) Parameters object Object to iterate over properties. keyOnly If keyOnly is truthy value, Iterator.prototype.next returns property_name only. Description Returns Iterator instance that iterates over object. Iterator instance returns [property_name, property_value] array for each iteration if keyOnly is falsy,
otherwise, if keyOnly is truthy, it returns property_name for each iteration. If object is the Iterator instance or Generator instance, it returns object itself. Properties Iterator.prototype[@@iterator] Returns a function that returns iterator object. Methods Iterator.prototype.next Returns next item in the [property_name, property_value] format or property_name only. It throws StopIteration i...
Enumerator.atEnd - Archive of obsolete content
ion and is only supported in Internet Explorer. The Enumerator.atEnd method returns a Boolean value indicating if the enumerator is at the end of the collection. Syntax myEnum.atEnd() Remarks The required myEnum reference is any Enumerator object. The atEnd method returns true if the current item is the last one in the collection, the collection is empty, or the current item is undefined.
Otherwise, it returns false. 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.i...
Error.stackTraceLimit - Archive of obsolete content
10. Syntax Error.stackTraceLimit Remarks You can set the stackTraceLimit property to any positive value between 0 and Infinity. If the stackTraceLimit property is set to 0 at the time an error is thrown, no stack trace is shown. If the property is set to a negative value or a non-numeric value, the value is converted to 0. If the stackTraceLimit is set to Infinity, the entire stack is shown.
Otherwise, ToUint32 is used to convert the value. Example The following example shows how to set and then get the stack trace limit. try { var err = new Error("my error"); Error.stackTraceLimit = 7; throw err; } catch(e) { document.write("Error stack trace limit: ") document.write(Error.stackTraceLimit); } Requirements Supported in Internet Explorer 10 and in Windows 8.x Store apps. Applie...
Microsoft JavaScript extensions - Archive of obsolete content
Warning: These APIs will only work in Microsoft applications, and are not on a standards track. Microsoft browsers (Internet Explorer, and in a few cases, Microsoft Edge) support a number of special Microsoft extensions to the
otherwise standard JavaScript APIs. Objects ActiveXObject Debug Enumerator VBArray Functions GetObject ScriptEngine ScriptEngineBuildVersion ScriptEngineMajorVersion ScriptEngineMinorVersion Statements @cc-on @if @set Other Date.getVarDate() Error.description Error.number Error.stackTraceLimit ...
LiveConnect Overview - Archive of obsolete content
yName[index] (where index is an integer), and determine its length with arrayName.length. A Java object of any other class is converted to a JavaScript wrapper, which can be used to access methods and fields of the Java object: Converting this wrapper to a string calls the toString method on the original object. Converting to a number calls the doubleValue method, if possible, and fails
otherwise. Converting to a boolean in JavaScript 1.3 and later versions returns false if the object is null, and true
otherwise. Converting to a boolean in JavaScript 1.2 and earlier versions calls the booleanValue method, if possible, and fails
otherwise. Note that instances of java.lang.Double and java.lang.Integer are converted to JavaScript objects, not to JavaScript numbers. Similarly, ins...
Sharp variables in JavaScript - Archive of obsolete content
#1 = {}; // This doesn't do much since the sharp variable is out of scope immediately after a = #2 = {}; // Slightly more useful since we retain a reference to the new object To reference the sharp variable, simply append another sharp (#) to the end of the variable name. This acts as a reference to initial variable. You can use this to create objects in a single line of code that would
otherwise take multiple lines of code. Examples Multiple references var a = { foo:#1=[], bar:#1# }; a.foo.push("Hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" You can avoid using sharp variables by breaking the declaration up into multiple lines. var a = { foo:[], bar:undefined }; a.bar = a.foo; a.foo.push("Hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" Cycl...
Reference - Archive of obsolete content
e references to using LANGUAGE="JavaScript1.2", and all references are merely presented as information detailing past behavior. The "Backwards compatibility" sections have been renamed to "Behavior in older versions." However, I think this is only appropriate if we are going to document the evolution of everything, or at least note the most significant changes introduced in the various versions.
Otherwise, I think we should just remove the "Behavior in other versions" sections, and rename the "JavaScript 1.2" section headings to something like "Differences with JavaScript 1.2," as well as include a link to the yet-to-be-written JavaScript 1.2 page documenting the various oddities and deviations made in that version, something which I think we should do anyway. Maybe something like Main Article: Ja...
Writing JavaScript for XHTML - Archive of obsolete content
acters which are "special" in XML, which usually means < and &. If your code contains either of these, you can work around this with CDATA sections: <script type="text/javascript"> <![CDATA[ // is the variable a non-negative integer less than 10? if (variable < 10 && variable >= 0) action(); ]]> </script> Note that the CDATA section is only necessary because of the < in the code;
otherwise you could have ignored it. A third solution is to use only external scripts, neatly sidestepping the special-character problem. Alternatively, the CDATA section can be couched within comments so as to be able to work in either application/xhtml+xml or text/html: <script type="text/javascript"> //<![CDATA[ ... //]]> </script> <!-- (For styles, it is different) --> <style type="text/cs...
XForms Select Element - Archive of obsolete content
appearance = 'full' (xhtml/xul) list Displaying a listbox is the default representation (xhtml/xul). Characteristics analogous widgets are <html:select size="5" multiple="true"/> and <xul:listbox seltype="multiple"/> visual grouping by choices element isn't implemented if incremental attribute value is false, the bound node is updated when the select control is blurred (i.e. loses focus),
otherwise it is updated upon item selection check group The select is represented as group of checkboxes (xhtml/xul). Characteristics appearance attribute contains the value full there are no analogue widgets in XHTML or in XUL visual grouping by choices element is supported if incremental attribute value is false then bound node is updated when item is blurred Examples <xf:model> <xf:instance...
Window: devicelight event - Archive of obsolete content
Bubbles No Cancelable No Interface SensorCallback Target DefaultView (window) Other properties Property Type Description value Read only Double (float) The sensor data for ambient light in Lux. min Read only Double (float) The minimum value in the range the sensor detects (if available, 0
otherwise). max Read only Double (float) The maximum value in the range the sensor detects (if available, 0
otherwise). Examples window.addEventListener('devicelight', function(event) { console.log(event.value); }); Specifications Specification Status Comment Ambient Light SensorThe definition of 'Ambient Light Events' in that specification. Candid...
Common causes of memory leaks in extensions - Extensions
All zombie compartments in extensions are caused by a failure to release resources appropriately in certain circumstances, such as when a window is closed, a page unloads, or an extension is disabled or removed. While bug 695480 should prevent most of these compartment leaks, add-ons still need to be aware of the practices that caused these leaks, as the fix causes many add-ons which would have
otherwise caused a leak to instead throw errors when attempting to access nodes from documents which no longer exist. Storing references to window objects and DOM nodes The most common problem is extensions holding onto references to content windows for too long. For example, in XUL overlay code: var contentWindows = []; function inBrowserXulOverlay(contentWindow) { // forgetting or failing to pop th...
Desktop gamepad controls - Game development
{ var press = false; for(var i=0; i<buttonsPressed.length; i++) { if(buttonsPressed[i] == button) { press = true; } } return press; } The function takes a button as a parameter; in the loop it checks if the given button's number is among the currently pressed buttons available in the buttonsPressed array. If it is, then the function returns true; false
otherwise. Next, in the draw() function we do two things -- execute the gamepadUpdateHandler() function to get the current state of pressed buttons on every frame, and use the gamepadButtonPressedHandler() function to check the buttons we are interested to see whether they are pressed, and do something if they are: function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // ... g...
Desktop mouse and keyboard controls - Game development
And then in the update() function whenever C is pressed we'll do this: if(this.keyCheat.isDown) { this.player.health = this.player.maxHealth; } We can set the health of the player to maximum. Remember: it's a secret, so don't tell anyone! How to play We've implemented the controls, and now we should inform the player about their options to control the game -- they wouldn't know about them
otherwise. When showing the how to play screen where the various ways to control the ship in the game are shown, instead of showing them all to everyone, we can detect whether the game is launched on desktop or mobile and just show the appropriate controls for the device: if(this.game.device.desktop) { moveText = 'Arrow keys or WASD to move'; shootText = 'X or Space to shoot'; } else { moveTex...
Visual-js game engine - Game development
other project (even commercial projects) as long as the copyright header is left intact Except for plugins on sale and graphics that come with them (they have special commercial licence). 3) Please read the following terms and conditions before using this application: Disclaimer of warranty 'Visual js' is provided "as-is" and without warranty of any kind, express, implied or
otherwise, including without limitation, any warranty of merchantability or fitness for a particular purpose. In no event shall the author of this software be held liable for data loss, damages, loss of profits or any other kind of loss while using or misusing this software. External licences in this project : Webcam NUI control is under : Created by Romuald Quantin. http://c...
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
Asynchronous communication is a method of exchanging messages between two or more parties in which each party receives and processes messages whenever it's convenient or possible to do so, rather than doing so immediately upon receipt. Additionally, messages may be sent without waiting for acknowledgement, with the understanding that if a problem occurs, the recipient will request corrections or
otherwise handle the situation. For humans, e-mail is an asynchronous communication method; the sender sends an email and the recipient will read and reply to the message when it's convenient to do so, rather than doing so at once. And both sides can continue to send and receive messages whenever they wish, instead of having to schedule them around each other. When software communicates asynchronously,...
CSS pixel - MDN Web Docs Glossary: Definitions of Web-related terms
By definition, this is the physical size of a single pixel at a pixel density of 96 DPI, located an arm's length away from the viewer's eyes. That definition, of course, leaves a lot of wiggle room, as the terms "be comfortably seen" and "an arm's length away" are imprecise, varying from person to person. ...
Conditional - MDN Web Docs Glossary: Definitions of Web-related terms
A condition is a set of rules that can interrupt normal code execution or change it, depending on whether the condition is completed or not. An instruction or a set of instructions is executed if a specific condition is fulfilled.
Otherwise, another instruction is executed. It is also possible to repeat the execution of an instruction, or set of instructions, while a condition is not yet fulfilled. 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 ...
Dynamic programming language - MDN Web Docs Glossary: Definitions of Web-related terms
For example, in JavaScript it is possible to change the type of a variable or add new properties or methods to an object while the program is running. This is opposed to so-called static programming languages, in which such changes are normally not possible. Note that while there is indeed a connection between this dynamic/static property of programming languages and dynamic/static-typing, the two are far from synonymous. ...
Entity - MDN Web Docs Glossary: Definitions of Web-related terms
You can also use them in place of other characters that are difficult to type with a standard keyboard. Many characters have memorable entities. For example, the entity for the copyright symbol ((C)) is ©. For less memorable characters, such as — or —, you can use a reference chart or decoder tool. ...
Fuzz testing - MDN Web Docs Glossary: Definitions of Web-related terms
Fuzzing is a technique for testing software using automated tools to provide invalid or unexpected input to a program or function in a program, then checking the results to see if the program crashes or
otherwise acts inappropriately. This is an important way to ensure that software is stable, reliable, and secure, and we use fuzzing a lot at Mozilla. Jesse's blog posts about fuzzing Wikipedia: Fuzz testing fuzzdb jsfuzz - coverage guided javascript fuzzer ...
Syntax - MDN Web Docs Glossary: Definitions of Web-related terms
and python. This does not mean the two langauges share similarities with syntax. Syntax applies both to programming languages (commands to the computer) and markup languages (document structure information) alike. Syntax only governs ordering and structure; the instructions must also be meaningful, which is the province of semantics. Code must have correct syntax in order to compile correctly,
otherwise a syntax error occurs. Even small errors, like a missing parenthesis, can stop source code from compiling successfully. Frameworks are said to have a "clean" syntax if they produce simple, readable, concise results. If a codebase uses "a lot of syntax", it requires more characters to achieve the same functionality. Learn more General knowledge Syntax (programming languages) on Wikipedia ...
WCAG - MDN Web Docs Glossary: Definitions of Web-related terms
d-resource devices such as mobile phones. WCAG 2.0 which superseded WCAG 1.0 was published as a W3C Recommendation on 11 December 2008. It consists of 12 guidelines organized under 4 principles (perceivable, operable, understandable, and robust) and each guideline has testable success criteria. WCAG uses three levels of conformance: Priority 1: Web developers must satisfy these requirements,
otherwise it will be impossible for one or more groups to access the Web content. Conformance to this level is described as A. Priority 2: Web developers should satisfy these requirements,
otherwise some groups will find it difficult to access the Web content. Conformance to this level is described as AA or Double-A. Priority 3: Web developers may satisfy these requirements, in order to make it easier fo...
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
); var a = []; for(var k = 0; k < xpathResult.snapshotLength; k++) { a[k] = xpathResult.snapshotItem(k); } responseNodes = a; } else { //
Otherwise, the response must be a single well-formed document response responseNodes = [response.documentElement]; // Put in array so can be treated the same way as the above } // PREPEND ANY NODE(S) (AS XML) THEN REMOVE XINCLUDE for (j=0; j < responseNodes.length ; j++) { ...
Application Context - MDN Web Docs Glossary: Definitions of Web-related terms
An application context is a top-level browsing context that has a manifest applied to it. If an application context is created as a result of the user agent being asked to navigate to a deep link, the user agent must immediately navigate to the deep link with replacement enabled.
Otherwise, when the application context is created, the user agent must immediately navigate to the start URL with replacement enabled. Please note that the start URL is not necessarily the value of the start_url member: the user or user agent could have changed it when the application was added to home-screen or
otherwise bookmarked. ...
What is the difference between webpage, website, web server, and search engine? - Learn web development
k into in more detail in other articles). A web page can embed a variety of different types of resources such as: style information -- controlling a page's look-and-feel scripts -- which add interactivity to the page media -- images, sounds, and videos. Note: Browsers can also display other documents such as PDF files or images, but the term web page specifically refers to HTML documents.
Otherwise, we only use the term document. All web pages available on the web are reachable through a unique address. To access a page, just type its address in your browser address bar: Web site A website is a collection of linked web pages (plus their associated resources) that share a unique domain name. Each web page of a given website provides explicit links--most of the time in the form of click...
What is a URL? - Learn web development
being requested. Alternatively, it is possible to directly use an IP address, but because it is less convenient, it is not often used on the Web. :80 is the port. It indicates the technical "gate" used to access the resources on the web server. It is usually omitted if the web server uses the standard ports of the HTTP protocol (80 for HTTP and 443 for HTTPS) to grant access to its resources.
Otherwise it is mandatory. /path/to/myfile.html is the path to the resource on the Web server. In the early days of the Web, a path like this represented a physical file location on the Web server. Nowadays, it is mostly an abstraction handled by Web servers without any physical reality. ?key1=value1&key2=value2 are extra parameters provided to the Web server. Those parameters are a list of key/value...
The HTML5 input types - Learn web development
ribute can be used to enforce constraints, which you'll learn about in Client-side form validation. URL field A special type of field for entering URLs can be created using the value url for the type attribute: <input type="url" id="url" name="url"> It adds special validation constraints to the field. The browser will report an error if no protocol (such as http:) is entered, or if the URL is
otherwise malformed. On devices with dynamic keyboards, the default keyboard will often display some or all of the colon, period, and forward slash as default keys. See below for an example (taken on Firefox for Android): Note: Just because the URL is well-formed doesn't necessarily mean that it refers to a location that actually exists! Numeric field Controls for entering numbers can be created with...
Styling web forms - Learn web development
here, or near the bottom left corner, you need to rely on positioning. Take the following example: To position the legend in this manner, we used the following CSS (other declarations removed for brevity): fieldset { position: relative; } legend { position: absolute; bottom: 0; right: 0; } The <fieldset> needs to be positioned too, so that the <legend> is positioned relative to it (
otherwise the <legend> would be positioned relative to the <body>.) The <legend> element is very important for accessibility -- it will be spoken by assistive technologies as part of the label of each form element inside the fieldset -- but using a technique like the one above is fine. The legend contents will still be spoken in the same way; it is just the visual position that has changed. Note: You co...
CSS basics - Learn web development
eet language. CSS is what you use to selectively style HTML elements. For example, this CSS selects paragraph text, setting the color to red: p { color: red; } Let's try it out! Using a text editor, paste the three lines of CSS (above) into a new file. Save the file as style.css in a directory named styles. To make the code work, we still need to apply this CSS (above) to your HTML document.
Otherwise, the styling won't change the appearance of the HTML. (If you haven't been following our project, pause here to read Dealing with files and HTML basics.) Open your index.html file. Paste the following line in the head (between the <head> and </head> tags): <link href="styles/style.css" rel="stylesheet"> Save index.html and load it in your browser. You should see something like this: If...
Installing basic software - Learn web development
tall a couple of desktop web browsers to test our code in. Choose your operating system below and click the relevant links to download installers for your favorite browsers: Linux: Firefox, Chrome, Opera, Brave. Windows: Firefox, Chrome, Opera, Internet Explorer, Microsoft Edge, Brave (Windows 10 comes with Edge by default; if you have Windows 7 or above, you can install Internet Explorer 11;
otherwise, you should install an alternative browser). macOS: Firefox, Chrome, Opera, Safari, Brave (MacOS and iOS come with Safari by default). Before going on, you should install at least two of these browsers and have them ready for testing. Note: Internet Explorer is not compatible with some modern web features and it may not be able to run your project. You usually don't need to worry about makin...
Tips for authoring fast-loading HTML pages - Learn web development
apply to any user agent, and can be applied to any web page, regardless of browser-support requirements. Use async and defer, if possible Make the JavaScript scripts such that they are compatible with both the async and the defer attributes, and use async whenever possible, especially if you have multiple script tags. With that, the page can stop rendering while JavaScript is still loading.
Otherwise, the browser will not render anything that is after the script tags that do not have these attributes. Note: Even though these attributes do help a lot the first time a page is loaded, you should use them but not assume they will work in all browsers. If you already follow all JavaScript best practices, there is no need to change your code. Example page structure . <html> . <head> ...
Creating hyperlinks - Learn web development
a hyperlink? Hyperlinks are one of the most exciting innovations the Web has to offer. They've been a feature of the Web since the beginning, and are what makes the Web a web. Hyperlinks allow us to link documents to other documents or resources, link to specific parts of documents, or make apps available at a web address. Almost any web content can be converted to a link so that when clicked or
otherwise activated the web browser goes to another web address (URL). Note: A URL can point to HTML files, text files, images, text documents, video and audio files, or anything else that lives on the Web. If the web browser doesn't know how to display or handle the file, it will ask you if you want to open the file (in which case the duty of opening or handling the file is passed to a suitable native a...
Document and website structure - Learn web development
e main content of the page. So a <div> is fine in this case. We've included a heading as a signpost to aid screenreader users in finding it. Warning: Divs are so convenient to use that it's easy to use them too much. As they carry no semantic value, they just clutter your HTML code. Take care to use them only when there is no better semantic solution and try to reduce their usage to the minimum
otherwise you'll have a hard time updating and maintaining your documents. Line breaks and horizontal rules Two elements that you'll use occasionally and will want to know about are <br> and <hr>: <br> creates a line break in a paragraph; it is the only way to force a rigid structure in a situation where you want a series of fixed short lines, such as in a postal address or a poem. For example: <p>Th...
Structuring a page of content - Learn web development
d a suitable wrapper for: The header The navigation menu The main content The welcome text The image sidebar The footer You should also: Apply the provided CSS to the page by adding another <link> element just below the existing one provided at the start. Hints and tips Use the W3C Nu HTML Checker to catch unintended mistakes in your HTML, CSS, and SVG -- mistakes you might have
otherwise missed -- so that you can fix them. You don't need to know any CSS to do this assessment; you just need to put the provided CSS inside an HTML element. The provided CSS is designed so that when the correct structural elements are added to the markup, they will appear green in the rendered page. If you are getting stuck and can't envisage what elements to put where, draw out a simple block diag...
From object to iframe — other embedding technologies - Learn web development
Only embed when necessary Sometimes it makes sense to embed third-party content -- like youtube videos and maps -- but you can save yourself a lot of headaches if you only embed third-party content when completely necessary. A good rule of thumb for web security is "You can never be too cautious. If you made it, double-check it anyway. If someone else made it, assume it's dangerous until proven
otherwise." Besides security, you should also be aware of intellectual property issues. Most content is copyrighted, offline and online, even content you might not expect (for example, most images on Wikimedia Commons). Never display content on your webpage unless you own it or the owners have given you written, unequivocal permission. Penalties for copyright infringement are severe. Again, you can never...
Responsive images - Learn web development
th <img> above, <source> can take a srcset attribute with multiple images referenced, as well as a sizes attribute. So, you could offer multiple images via a <picture> element, but then also offer multiple resolutions of each one. Realistically, you probably won't want to do this kind of thing very often. In all cases, you must provide an <img> element, with src and alt, right before </picture>,
otherwise no images will appear. This provides a default case that will apply when none of the media conditions return true (you could actually remove the second <source> element in this example), and a fallback for browsers that don't support the <picture> element. This code allows us to display a suitable image on both wide screen and narrow screen displays, as shown below: Note: You should use the...
Video and audio content - Learn web development
on cues are: subtitles Translations of foreign material, for people who don't understand the words spoken in the audio. captions Synchronized transcriptions of dialog or descriptions of significant sounds, to let people who can't hear the audio understand what is going on. timed descriptions Text which should be spoken by the media player in order to describe important visuals to blind or
otherwise visually impaired users. A typical WebVTT file will look something like this: WEBVTT 1 00:00:22.230 --> 00:00:24.606 This is the first subtitle. 2 00:00:30.739 --> 00:00:34.074 This is the second. ... To get this displayed along with the HTML media playback, you need to: Save it as a .vtt file in a sensible place. Link to the .vtt file with the <track> element. <track> should be pla...
Fetching data from the server - Learn web development
ut it is a good idea to get into the habit of setting this in case you want to fetch other types of data in the future. Add this next: request.responseType = 'text'; Fetching a resource from the network is an asynchronous operation, meaning that you have to wait for that operation to complete (e.g., the resource is returned from the network) before you can do anything with that response,
otherwise, an error will be thrown. XHR allows you to handle this using its onload event handler -- this is run when the load event fires (when the response has returned). When this has occurred, the response data will be available in the response property of the XHR request object. Add the following below your last addition. You'll see that inside the onload event handler we are setting the textContent...
Manipulating documents - Learn web development
inline styles to the document: <p style="color: white; background-color: black; padding: 10px; width: 250px; text-align: center;">We hope you enjoyed the ride.</p> Note: Notice how the JavaScript property versions of the CSS styles are written in lower camel case whereas the CSS versions are hyphenated (e.g. backgroundColor versus background-color). Make sure you don't get these mixed up,
otherwise it won't work. There is another common way to dynamically manipulate styles on your document, which we'll look at now. Delete the previous five lines you added to the JavaScript. Add the following inside your HTML <head>: <style> .highlight { color: white; background-color: black; padding: 10px; width: 250px; text-align: center; } </style> Now we'll turn to a very useful meth...
Third-party APIs - Learn web development
ywords.length; j++) { ... } ) to loop through all the keywords associated with each article, and insert each one inside its own <span>, inside a <p>. This was done to make it easy to style each one. We used an if() block (if(current.multimedia.length > 0) { ... }) to check whether each article has any images associated with it (some stories don't.) We display the first image only if it exists (
otherwise an error would be thrown). We gave our <div> element a class of "clearfix", so we can easily apply clearing to it. Wiring up the pagination buttons To make the pagination buttons work, we will increment (or decrement) the value of the pageNumber variable, and then re-rerun the fetch request with the new value included in the page URL parameter. This works because the NYTimes API only r...
Handling text — strings in JavaScript - Learn web development
r to a string and concatenates the two strings. You can even do this with two numbers -- you can force a number to become a string by wrapping it in quote marks. Try the following (we are using the typeof operator to check whether the variable is a number or a string): let myDate = '19' + '67'; typeof myDate; If you have a numeric variable that you want to convert to a string but not change
otherwise, or a string variable that you want to convert to a number but not change
otherwise, you can use the following two constructs: The Number object converts anything passed to it into a number, if it can. Try the following: let myString = '123'; let myNum = Number(myString); typeof myNum; Conversely, every number has a method called toString() that converts it to the equivalent stri...
Storing the information you need — Variables - Learn web development
ntegers) or decimal numbers like 2.456 (also called floats or floating point numbers). You don't need to declare variable types in JavaScript, unlike some other programming languages. When you give a variable a number value, you don't include quotes: let myAge = 17; Strings Strings are pieces of text. When you give a variable a string value, you need to wrap it in single or double quote marks;
otherwise, JavaScript tries to interpret it as another variable name. let dolphinGoodbye = 'So long and thanks for all the fish'; Booleans Booleans are true/false values -- they can have two values, true or false. These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be: let iAmAlive = true; Whereas in reality it would be used more li...
JavaScript object basics - Learn web development
}, Here we are effectively creating a sub-namespace. This sounds complex, but really it's not -- to access these items you just need to chain the extra step onto the end with another dot. Try these in the JS console: person.name.first person.name.last Important: At this point you'll also need to go through your method code and change any instances of name[0] name[1] to name.first name.last
Otherwise your methods will no longer work. Bracket notation There is another way to access object properties -- using bracket notation. Instead of using these: person.age person.name.first You can use person['age'] person['name']['first'] This looks very similar to how you access the items in an array, and it is basically the same thing -- instead of using an index number to select an item, you are ...
Object-oriented JavaScript for beginners - Learn web development
ou a simplistic, high-level view of what Object-oriented programming (OOP) is. We say simplistic, because OOP can quickly get very complicated, and giving it a full treatment now would probably confuse more than help. The basic idea of OOP is that we use objects to model real world things that we want to represent inside our programs, and/or provide a simple way to access functionality that would
otherwise be hard or impossible to make use of. Objects can contain related data and code, which represent information about the thing you are trying to model, and functionality or behavior that you want it to have. Object data (and often, functions too) can be stored neatly (the official word is encapsulated) inside an object package (which can be given a specific name to refer to, which is sometimes cal...
Object building practice - Learn web development
the requestAnimationFrame API for animating the whole display -- you don't need to have any previous knowledge of these APIs, and we hope that by the time you've finished this article you'll be interested in exploring them more. Along the way we'll make use of some nifty objects, and show you a couple of nice techniques like bouncing balls off walls, and checking whether they have hit each other (
otherwise known as collision detection). Getting started To begin with, make local copies of our index.html, style.css, and main.js files. These contain the following, respectively: A very simple HTML document featuring an <h1> element, a <canvas> element to draw our balls on, and elements to apply our CSS and JavaScript to our HTML. Some very simple styles, which mainly serve to style and position t...
Multimedia: video - Learn web development
ut offers significant data savings for videos with a low probability of playback. Offering more modest bandwidth savings, setting preload="metadata" may download up to 3% of the video on page load. This is a useful option for some small or moderately sized files. Changing the setting to auto tells the browser to automatically download the entire video. Do this only when playback is very likely.
Otherwise, it wastes a lot of bandwidth. Consider streaming Video streaming allows the proper video size and bandwidth (based on network speed) to be delivered to the end user. Similar to responsive images, the correct size video is delivered to the browser, ensuring fast video startup, low buffering, and optimized playback. Conclusion Optimizing video has the potential to significantly improve web...
Client-Server Overview - Learn web development
, the information from the form is encoded in the body of the request (for example, the new user fullname is set using: &user-fullname=Hamish+Willee). The response The response from the request is shown below. The status code of "302 Found" tells the browser that the post succeeded, and that it must issue a second HTTP request to load the page specified in the Location field. The information is
otherwise similar to that for the response to a GET request. HTTP/1.1 302 FOUND Server: Apache X-Backend-Server: developer3.webapp.scl3.mozilla.com Vary: Cookie Vary: Accept-Encoding Content-Type: text/html; charset=utf-8 Date: Wed, 07 Sep 2016 00:38:13 GMT Location: https://developer.mozilla.org/profiles/hamishwillee Keep-Alive: timeout=5, max=1000 Connection: Keep-Alive X-Frame-Options: DENY X-Cache-Inf...
Introduction to the server side - Learn web development
on problems, speed up development, and simplify the different types of tasks faced in a particular domain. Again, while both client and server-side code use frameworks, the domains are very different, and hence so are the frameworks. Client-side web frameworks simplify layout and presentation tasks while server-side web frameworks provide a lot of "common" web server functionality that you might
otherwise have to implement yourself (e.g. support for sessions, support for users and authentication, easy database access, templating libraries, etc.). Note: Client-side frameworks are often used to help speed up development of client-side code, but you can also choose to write all the code by hand; in fact, writing your code by hand can be quicker and more efficient if you only need a small, simple we...
Website security - Learn web development
able, such as cookie data rendered by the browser, or user files that are uploaded and displayed. The best defense against XSS vulnerabilities is to remove or disable any markup that can potentially contain instructions to run the code. For HTML this includes elements, such as <script>, <object>, <embed>, and <link>. The process of modifying user data so that it can't be used to run scripts or
otherwise affect the execution of server code is known as input sanitization. Many web frameworks automatically sanitize user input from HTML forms by default. SQL injection SQL injection vulnerabilities enable malicious users to execute arbitrary SQL code on a database, allowing data to be accessed, modified, or deleted irrespective of the user's permissions. A successful injection attack might spoof i...
Getting started with Ember - Learn web development
cript technologies and is a thin layer on top of traditional object-oriented programming, while still allowing developers to utilize functional programming techniques. Ember makes use of two main syntaxes: JavaScript (or optionally, TypeScript) Ember's own templating language, which is loosely based on Handlebars. The templating language is used to make build and runtime optimizations that
otherwise wouldn't be possible. Most importantly, it is a superset of HTML -- meaning that anyone who knows HTML can make meaningful contributions to any Ember project with minimal fear of breaking code. Designers and other non-developers can contribute to page templates without any knowledge of JavaScript, and interactivity can be added later. This language also enables lighter asset payloads due to comp...
Ember app structure and componentization - Learn web development
emplate-only components, because in large applications, template-only components end up being the majority of the components. header-test.js is for writing automated tests to ensure that our app continues to work over time as we upgrade, add features, refactor, etc. Testing is outside the scope of this tutorial, although generally testing should be implemented as you develop, rather than after,
otherwise it tends to be forgotten about. If you're curious about testing, or why you would want to have automated tests, check out the official Ember tutorial on testing. Before we start adding any component code, let's create the scaffolding for the other components. Enter the following lines into your terminal, one by one: ember generate component todo-list ember generate component todo ember generate...
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
obj = obj. With this we are defining foo as a dependency, and whenever it changes Svelte will run obj = obj. In our checkAllTodos() function, when we run: todos.forEach(t => t.completed = completed) Svelte will not mark todos as changed because it does not know that when we update our t variable inside the forEach() method, we are also modifying the todos array. And that makes sense, because
otherwise Svelte would be aware of the inner workings of the forEach() method; the same would therefore be true for any method attached to any object or array. Nevertheless, there are different techniques that we can apply to solve this problem, and all of them involve assigning a new value to the variable being watched. Like we already saw, we could just tell Svelte to update the variable with a self-as...
Vue conditional rendering: editing existing todos - Learn web development
The v-if directive will only render a block if the value passed to it is truthy. This is similar to how an if statement works in JavaScript. v-if also has corresponding v-else-if and v-else directives to provide the equivalent of JavaScript else if and else logic inside Vue templates. It's important to note that v-else and v-else-if blocks need to be the first sibling of a v-if/v-else-if block,
otherwise Vue will not recognize them. You can also attach v-if to a <template> tag if you need to conditionally render an entire template. Lastly, you can use a v-if + v-else at the root of your component to display only one block or another, since Vue will only render one of these blocks at a time. We'll do this in our app, as it will allow us to replace the code that displays our to-do item with the ed...
Creating our first Vue component - Learn web development
ever pattern you would like. It's best to keep it consistent though. Because the shorthand syntax is more commonly used, this tutorial will stick to that pattern. So let's do this. Update your <input> element now to replace checked="false" with :checked="isDone". Test out your component by passing :done="true" to the ToDoItem call in App.vue. Note that you need to use the v-bind syntax, because
otherwise true is passed as a string. The displayed checkbox should be checked. <template> <div id="app"> <h1>My To-Do List</h1> <ul> <li> <to-do-item label="My ToDo Item" :done="true"></to-do-item> </li> </ul> </div> </template> Try changing true to false and back again, reloading your app in between to see how the state changes. Giving Todos a unique id Great! We ...
Getting started with Vue - Learn web development
e ESLint into their own, dedicated files. The other option, "In package.json", will put all of your config settings into the app's package.json file. Select "In dedicated config files" and push Enter. Finally, you are asked if you want to save this as a preset for future options. This is entirely up to you. If you like these settings over the existing presets and want to use them again, type y ,
otherwise type n. The CLI will now begin scaffolding out your project, and installing all of your dependencies. If you've never run the Vue CLI before, you'll get one more question -- you'll be asked to choose a package manager. You can use the arrow keys to select which one you prefer. The Vue CLI will default to this package manager from now on. If you need to use a different package manager after thi...
Rendering a list of Vue components - Learn web development
necessary, it makes it easier for us to manage since we already need to create a unique id for each todo item anyway. Add a new prop to your ToDoItem component -- id. Make it required, and make its type a String. To prevent name collisions, remove the id field from your data attribute. You are no longer using uniqueId, so you need to remove the import uniqueId from 'lodash.uniqueid'; line,
otherwise your app will throw an error. The <script> contents in your ToDoItem component should now look something like this: export default { props: { label: {required: true, type: String}, done: {default: false, type: Boolean}, id: {required: true, type: String} }, data() { return { isDone : this.done, } }, } Now, over in your App.vue...
Handling common accessibility problems - Learn web development
ser compatibility for these features is fairly good, but if you want to provide text alternatives for audio or support older browsers, a simple text transcript presented somewhere on the page or on a separate page might be a good idea. Element relationships and context There are certain features and best practices in HTML designed to provide context and relationships between elements where none
otherwise exists. The three most common examples are links, form labels, and data tables. The key to accessible link text is that people using screen readers will often use a common feature whereby they pull up a list of all the links on the page. In this case, the link text needs to make sense out of context. For example, a list of links labeled "click here", "click here", etc. is really bad for accessib...
Setting up your own test automation environment - Learn web development
ing it: driver.sleep(1000).then(function() { driver.findElement(By.name('q')).sendKeys(webdriver.Key.TAB); }); Waiting for something to complete There are times where you'll want to make WebDriver wait for something to complete before carrying on. For example if you load a new page, you'll want to wait for the page's DOM to finish loading before you try to interact with any of its elements,
otherwise the test will likely fail. In our google_test.js test for example, we included this block: driver.sleep(2000).then(function() { driver.getTitle().then(function(title) { if(title === 'webdriver - Google Search') { console.log('Test passed'); } else { console.log('Test failed'); } }); }); The sleep() method accepts a value that specifies the time to wait in millisecon...
Deploying our app - Learn web development
own repository to host this code. Give your repository a short, memorable name, without spaces in it (use hyphens to separate words), and a description, then click Create repository at the bottom of the page. You should now have a "remote" URL that points to your new GitHub repo. This remote location needs to be added to our local git repository before we can push it up there,
otherwise it won't be able to find it. You'll need to run a command with the following structure (use the provided HTTPS option for now -- especially if you are new to GitHub -- not the SSH option): git remote add github https://github.com/yourname/repo-name.git So if your remote URL was https://github.com/remy/super-website.git, as in the screenshot above, your command would be git remote add git...
Client-side tooling overview - Learn web development
place or format. It can therefore be hard to find help with using a tool, or even to choose what tool to use. The knowledge about which are the best tools to use is a bit tribal, meaning that if you aren't already in the web community, it is hard to find out exactly which ones to go for! This is one reason we wrote this series of articles, to hopefully provide that first step that is hard to find
otherwise. You'll probably need a combination of the following things: Experienced teachers, mentors, fellow students, or colleagues that have some experience, have solved such problems before, and can give advice. A useful specific place to search. General web searches for front-end developer tools are generally useless unless you already know the name of the tool you are searching for. If you ...
Package management basics - Learn web development
the command npm install, and npm will look at the dependencies and install them for you. One disadvantage is that Parcel is only available inside our parcel-experiment app; you won't be able to run it in a different directory. But the advantages outweigh the disadvantages. Setting up our example app Anyway, on with the setup. Parcel expects an index.html and an index.js file to work with, but
otherwise it is very unopinionated about how you structure your project. Other tools can be very different, but at least Parcel makes it easy for our initial experiment. So now we need to add an index.html file to our working directory. Create index.html in your test directory, and give it the following contents: <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> <title>My test p...
Mozilla accessibility architecture
hods and create whatever child accessibles we want. When there is no DOM node for each accessible, as is the case for nsHTMLComboboxAccessible and nsXULTreeItemAccessible, we also need to override the Shutdown() method, so that the children get removed from memory when the parent is shutdown. In that case we also override ::GetAccNextSibling(), ::GetAccPreviousSibling() for the DOM-less children;
otherwise they do not know how to find each other. It is also useful to override these the child getters to return nothing, as we do in nsLeafAccessible, nsTextAccessible and other accessible implementations where we want to be sure to avoid children. Returning nothing for leaf and text objects also helps speed up tree construction and traversal. 4. Accessible Events Accessible events are DOM events transl...
Software accessibility: Where are we today?
who cannot speak, in place of their own voice. Finally, this technology could be useful to mainstream users, on portable information appliances, or to access information when the eyes are busy elsewhere. Magnification Enlarges the screen's contents: For those with low vision, it may suffice to use a larger font, a built-in high contrast theme, or even just an an extra large screen.
Otherwise, screen magnification programs may be used, which allow zooming in to portions of the screen, while following the mouse or the current focus. Screen magnifiers also have some built-in text-to-speech and the ability to filter text and images through various color palettes, such as black on yellow for high contrast, or green on blue for low contrast. The Optacon Provides access to pri...
A bird's-eye view of the Mozilla framework
r obtaining the nsIRDFNode for a given resource and property. var link = tocDS.GetTarget(resource, NC_LINK, true); Now that getLink() has the nsIRDFNode for the link, it can call QueryInterface() to check whether the nsIRDFLiteral is supported. link = link.QueryInterface(Components.interfaces.nsIRDFLiteral); If nsIRDFLiteral is supported, getLink() uses it to return the value of the link.
Otherwise it returns null. if (link) return link.Value; else return null; The document page for the link is displayed in theHelp Viewer window. ...
Chrome registration
the extension manager. In order to inform the chrome registry of the available chrome, a text manifest is used: this manifest is "chrome.manifest" in the root of an extension, or theme, or XULRunner application. The plaintext chrome manifests are in a simple line-based format. Each line is parsed individually; if the line is parsable the chrome registry takes the action identified by that line,
otherwise the chrome registry ignores that line (and prints a warning message in the runtime error console). locale packagename localename path/to/files skin packagename skinname path/to/files Note: The characters @ # ; : ? / are not allowed in the packagename. Firefox 2, Thunderbird 2, and SeaMonkey 1.1 will not find the chrome when packagename is mixed case. If the above example had a packagename o...
Creating Sandboxed HTTP Connections
wo for getting and setting request headers, and two for getting and setting response headers. The cookie header for requests is called "Cookie", while for responses it is "Set-Cookie". getRequestHeader(aHeader) - returns the request header value for the requested header. setRequestHeader(aHeader, aValue, aMerge) - sets the request header's value. If aMerge is true, the new value is appened,
otherwise the old value is overwritten. getResponseHeader(aHeader) - returns the response header value for the requested header. setResponseHeader(aHeader, aValue, aMerge) - sets the response header's value. If aMerge is true, the new value is appened,
otherwise the old value is overwritten. These methods provide all the required functionality needed to modify cookies before they are processed/sent, ...
Simple SeaMonkey build
'mk_add_options MOZ_OBJDIR=/path/to/comm-central/obj-sm-release' >> .mozconfig # Specify amount of parallel building. If the below is left out, a best guess will be taken automatically. echo 'mk_add_options MOZ_MAKE_FLAGS="-j4"' >> .mozconfig # ...quickly. # Build! # Note: This requires autoconf 2.13 (at least initially). # On Windows, be sure to use mozmake instead of make,
otherwise parallel building will break. make -f client.mk For a debug build, you need different configuration options in your .mozconfig file. This requires more disk space, about 3 GB, and twice as much available RAM. mk_add_options MOZ_OBJDIR=/path/to/comm-central/obj-sm-debug ac_add_options --enable-application=suite ac_add_options --enable-debug ac_add_options --disable-optimize Normally a s...
mach
i does what you want and even has a GUI? Those makepkg scripts named PKGBUILD are (typically) simple bash scripts that are easy to maintain and modify. Python based mach tends to involve more complexity and potential for breakage. Another possible reason: mach gives you an error, while running, say bootstrap.py directly (that is to type in a bash shell: python2 ./bootstrap.py ENTER-KEY ) in an
otherwise empty ..../subDir/ may work for you! Less may be better! And mach's error messages tend to be cryptic and not utterly helpful. That above bootstrap.py will download and setup everything so you can build a Mozilla app such as Firefox etcetera, so it is a nice starting point. Why should I use mach? You should use mach because it provides a better and more unified developer experience for working...
Multiple Firefox profiles
ts/MacOS/firefox. For example, if Firefox is installed in the recommended location, you would enter /Applications/Firefox.app/Contents/MacOS/firefox. If you have the path to your desired profile handy, enter a space character, followed by -profile followed by another space character, followed by the full path to the profile folder you wish to launch into. This will launch Firefox immediately.
Otherwise, enter a space character followed by --profilemanager. This will present the Profile Manager window in which you can make your selection. Hit return. Here is a complete example Terminal command from steps 2-3: /Applications/Firefox.app/Contents/macOS/firefox -profile /Users/Suzie/Library/Application\ Support/Firefox/Profiles/r99d1z7c.default If the Profile Manager window does not open, Fi...
Cross Process Object Wrappers
on, because the CPOW call is an IPC call instead of a simple property access in the same process. However, the potential impact on responsiveness is much smaller. Also, in this situation, the content process is in a known state. We know it's blocked waiting for the synchronous message to return, and we know that won't change during the CPOW call. This makes the CPOW call much safer than it would
otherwise be. This situation is thus called "safe CPOW usage". All other uses of CPOWs are called "unsafe CPOW usage". See also: https://mikeconley.ca/blog/2015/02/17/on-unsafe-cpow-usage-in-firefox-desktop-and-why-is-my-nightly-so-sluggish-with-e10s-enabled/ http://blog.lassey.us/2015/01/10/unsafe-cpow-usage/ ...
Frame script loading and lifetime
vent, when your frame script is unloaded (due to tab close for instance), you must set the third argument of addMessageListener to true. For example, from bootstrap.js: Services.mm.addMessageListener( 'my-addon-id', { receiveMessage: function() { console.log('incoming message from frame script:', aMsg.data); } }, true // must set this argument to true,
otherwise sending message from framescript will not work during and after the unload event on the ContentMessageManager triggers ); Then in your frame script, listen for the unload event of the message manager (which is the global this), and sending a message. If you did not set the third argument to true in bootstrap.js on Services.mm.addMessageListener, sending this message during, and after, the unload...
Performance best practices for Firefox front-end engineers
one of these // callbacks! return elem.clientWidth; }); requestAnimationFrame(() => { otherElem.style.width = `${width}px`; }); } Please see the section on promiseDocumentFlushed in Detecting and avoiding synchronous style flushes for more information on how to use the API. Note that queries for size and position information are only expensive if the DOM has been written to.
Otherwise, we're doing a cheap look-up of cached information. If we work hard to move all DOM writes into requestAnimationFrame(), then we can be sure that all size and position queries are cheap. It's also possible (though less infallible than promiseDocumentFlushed) to queue JavaScript to run very soon after the frame has been painted, where the likelihood is highest that the DOM has not been written to...
Firefox UI considerations for web developers
d. This list is created by a Mozilla service called Tippy Top. The data store provided by Tippy Top includes an optimized icon for each of the sites in the list; if the site is on this list, that icon is used. If Tippy Top doesn't include the site, Firefox looks in its Places data store for icons specified in the page's <head> element; If an SVG icon is available, that icon is selected.
Otherwise, bitmapped icons which are at least 96 pixels wide are considered. If one is found to have a width of exactly 96 pixels, it is used.
Otherwise, the smallest image larger than 96 pixels wide is selected. If no high-resolution icon is found, a screenshot is taken of the site; this screenshot is then scaled and cropped to fit in the space allotted to the icon. If the site also has a favicon, it m...
Using the Browser API
or value reported is rgb(0, 83, 159). Back to the stop/reload button -- updating the icon is nice, but we also need to update the functionality that is invoked when each icon is displayed. We do this with the following function, which runs the HTMLIFrameElement.stop() method to stop the page loading if the button is displaying a cross, and the HTMLIFrameElement.reload() method to reload the page
otherwise. stopReload.addEventListener('touchend',function() { if(stopReload.textContent === 'x') { browser.stop(); } else { browser.reload(); } }); Implementing the search bar Let's now turn our attention to implementing browser search using the Browser API. Tap the "S" button and try it out. Try searching for "Firefox" on the default page when the app first loads. So how do we do this...
Roll your own browser: An embedding how-to
lla/embedding/base/, a static library (on windows) called baseembed_s.lib is built. Just link this library to your application. There are two functions that are needed: nsresult NS_InitEmbedding(const char *aPath); nsresult NS_TermEmbedding(); Pretty self-explanatory. The aPath parameter will be passed to NS_InitXPCOM. NS_InitEmbedding() must be called from the main thread of your application,
otherwise it won't work. Do you have any simple examples of embedding Mozilla? There are many examples of products already using Gecko for embedding. Here's a partial list. The sections marked 'Mozilla Examples' refer to clients and sample code to be found within the Mozilla source tree. Linux External projects SashXB: IBM uses Mozilla to implement part of their Sash development/desktop environment.
Gecko Keypress Event
dows The charCode is replaced only when Ctrl is down but Alt is not down. If the OS-provided character cannot be entered without using the Ctrl key, then, Gecko does not replace the character. e.g., Ctrl+Shift+'2' on Persian keyboard layout inputs a ZWNJ, though Shift+'2' inputs '@', and so, if Gecko were to replace the charCode in this case, users would not be able to input ZWNJ (bug 414130).
Otherwise, Gecko can replace the charCode with an ASCII character. However, Gecko replaces the charCode only when the key pressed corresponds to a Latin letter (VK_A to VK_Z), numeral (VK_0 to VK_9), Plus sign (VK_OEM_PLUS), or Minus sign key (VK_OEM_MINUS). Note that replacing the original (non-ASCII) characters on these keys means that there are some accessibility issues for non-Latin keyboard layout us...
HTML parser threading
g up a new speculation object at the same moment. The first speculation in the speculation queue is examined. If the last character seen by the document.write() tokenizer was not a carriage return, if the document.write() tokenizer is in the "data" state and if the tree builder state snapshot on the speculation matches the state of the document.write() tree builder, the speculation has succeeded.
Otherwise it has failed. If there is more than one speculation in the queue and if the speculation is successful, we can dequeue the first speculation while holding mSpeculationMutex without bothering the parser thread. In this case, the tree ops from the speculation are flushed into the tree op executor and ContinueAfterScripts() returns early. (nsHtml5TreeOpExecutor::RunFlushLoop is on the call stack alr...
Geckoview-Junit Tests
ests normally run in an Android emulator. Running tests locally If desired, connect an Android device to your computer, or start an emulator, and make sure your device is visible to adb: $ adb devices List of devices attached emulator-5554 device If no device is found, 'mach geckoview-junit' will offer to start an emulator. Before running tests, install the androidTest apk on your device;
otherwise, 'mach geckoview-junit' will offer to install it. mozilla-central$ mach install --app org.mozilla.geckoview.test To run all tests: mozilla-central$ mach geckoview-junit To run just one class of tests: mozilla-central$ mach geckoview-junit <class> Please note that unlike Robocop tests, <class> needs to be specified using the fully qualified class name including the package, e.g. org.mozill...
How to get a stacktrace with WinDbg
ules. You will also want to open a log file to save data you collect. To do this, enter these four commands, pressing enter after each one. .logopen /t c:\temp\firefox-debug.log .childdbg 1 .tlist sxn gp lm If you see firefox.exe listed in the output from .tlist more than once, then you are already running the application and need to close the running instance first before you start debugging,
otherwise you won't get useful results. Now run Firefox by opening the Debug menu and clicking Go. While Firefox is running, you will not be able to type any commands into the debugger. After it starts, try to reproduce the crash or hanging issue that you are seeing. If Firefox fails to start, and you see lines of text followed by a command prompt in the debugger, a "breakpoint" may have been triggered. ...
IPDL Tutorial
thods are PManager* PFoo::Manager() const InfallibleTArray<PManagee*> PFoo::ManagedPManagee(); void PFoo::ManagedPManagee(InfallibleTArray<PManagee*>&); Shutdown and Error Handling The C++ methods which implement IPDL messages return bool: true for success, and false for catastrophic failure. Message implementations should return false from a message implementation if the data is corrupted or
otherwise malformed. Any time a message implementation returns false, IPDL will immediately begin catastrophic error handling: the communication channels for the child process (tab or plugin) will be disconnected, and the process will be terminated. Do not return false from message handlers for "normal" error conditions such as inability to load a network request! Normal errors should be signaled with a me...
Implementing Download Resuming
method with a failure status. (TODO: document what webbrowserpersist/exthandler do). The front-end code can then notify the user of this, and offer to resume the download. Resuming a download In order to resume a download, you should create a channel as usual (using nsIIOService). Then, you can check if it implements nsIResumableChannel. If it does not, the protocol does not support resuming.
Otherwise, call resumeAt with the desired start position, and the previously stored entity ID. (It is possible to pass an empty string as the ID; however, this means that you have no assurance that the file remained unchanged) Now, you can open the channel as usual (using nsIChannel.asyncOpen() in the common case) and write to the file in the onDataAvailable notifications. You may want to use nsISimpleStr...
Addon
in string appVersion, in string platformVersion ) Parameters listener An UpdateListener for the update process reason A reason code for performing the update appVersion An application version to check for updates for platformVersion A platform version to check for updates for Optional Methods uninstall() Uninstalls this add-on. If possible the uninstall will happen immediately,
otherwise it will wait until the next application restart. This method must be defined if an add-on has the permission PERM_CAN_UNINSTALL. void uninstall( ) cancelUninstall() Cancels uninstalling an add-on if it is pending uninstall. This method must be defined if an add-on has the pendingOperation PENDING_UNINSTALL. void cancelUninstall( ) hasResource() Checks whether a file resource is available ...
Add-on Repository
void retrieveRecommendedAddons(in integer maxResults, in SearchCallback callback) void searchAddons(in string searchTerms, in integer maxResults, in SearchCallback callback) Properties Property Type Description homepageURL string The URL of the repository site's home page. isSearching boolean true if a search is currently in progress;
otherwise false. Methods getRecommendedURL() Returns the URL that can be visited to see recommended add-ons. string getRecommendedURL(); Parameters None. Return value An URL indicating the repository's page of recommended add-ons. getSearchURL() Returns an URL of a web page that can be visited to see search results for the specified search terms. string getSearchURL( in string searchTerm...
AsyncShutdown.jsm
istered for the same condition, remove all these blockers. If no blocker has been registered for this condition, this is a noop. boolean removeBlocker( in function|promise|* condition ) Arguments condition A condition blocking the completion of the phase. This must be the same condition as was passed to addBlocker prior. Return Value Returns true if a blocker has been removed, or false
otherwise. Note that a result of false may mean either that the blocker has never been installed or that the phase has completed and the blocker has already been resolved. Examples AsyncShutdown.profileBeforeChange.addBlocker("Module: just a promise", promise); // profileBeforeChange will not complete until // promise is resolved or rejected AsyncShutdown.profileBeforeChange.addBloc...
DeferredTask.jsm
isRunning boolean Indicates whether the task is currently running. This is always true when read from code inside the task function, but can also be true when read from external code, in case the task is an asynchronous generator function. Methods isPending Obsolete since Gecko 28 Check the current task state. bool isPending(); Return value Returns true if pending, false
otherwise. start Obsolete since Gecko 28 Start (or postpone) task. void start(); flush Obsolete since Gecko 28 Perform any postponed task immediately. void flush(); cancel Obsolete since Gecko 28 Cancel any pending task. void cancel(); arm Request the execution of the task after the delay specified on construction. Multiple calls don't introduce further delays. If the task is running, th...
Dict.jsm
ue, undefined is returned for keys that aren't found. Return value The value of the specified key, or undefined if no matching key was found. has() Determines whether or not the specified key exists in the dictionary. boolean has( String aKey ); Parameters aKey The key for which to determine existence in the dictionary. Return value true if the specified key is in the dictionary,
otherwise false. listitems() Returns an array of the key/value pairs in the dictionary. Note: The order in which items are returned is arbitrary. Array listitems(); Parameters None. Return value An array of the key/value pairs in the dictionary. listkeys() Returns an array of the keys in the dictionary. Note: The order in which items are returned is arbitrary. Array listkeys(); Parameters N...
Interfacing with the Add-on Repository
ll object for later use, then creates and displays the pop-up notification box with the text and button label passed into the method. The pop-up callback function that gets called when the user clicks the button looks to see if there's a non-null AddonInstall object reference; if it's null, then the pop-up is displaying an error notification, so clicking the button simply dismisses the pop-up.
Otherwise, the AddonInstall object's install() method is called to install the add-on. This doesn't display any UI showing that the install is taking place; however, if you go to the Add-on Manager panel, you'll see the pending install listed among your add-ons. ...
JavaScript OS.Constants
. getService(Components.interfaces.nsIOSFileConstantsService). init(); From a chrome worker No initialization is required. Module OS.Constants is always available for chrome workers. OS.Constants.Sys Constants related to system configuration. Name The name of the operating system (e.g. "Darwin"). DEBUG Set to true on debug build configurations, non-existent
otherwise. OS.Constants.Path Paths of well-known files and directories. libxul The path to the file containing libxul. Useful, for instance, to access the platform code from JavaScript in conjunction with js-ctypes. profileDir The path to the current profile. homeDir The path to the user's home directory. winAppDataDir The path to the user's roaming ...
OS.File.Error
rror, the functions of OS.File raise instances of OS.File.Error. These exceptions hold both a human-readable error message detailing the I/O error and attributes to help determining the cause of the error. Cross-platform attributes operation The human-readable name of the failed operation. becauseExists true if the operation failed because a file or directory exists, false
otherwise. becauseNoSuchFile true if the operation failed because a file or directory does not exist, false
otherwise. becauseClosed true if the operation failed because a file or directory is closed, false
otherwise. Platform-specific attributes unixErrno (defined under Unix only) The system error number (errno) for the error. For more details, you may compare it ...
OS.File.Info
orm that can be serialized and transmitted between threads or processes. object toMsg( in OS.File.Info value ) Arguments Returns An object with the same fields as value but that may be serialized and transmitted between threads or processes. value An instance of OS.File.Info. Instances of OS.File.Info Cross-platform Attributes isDir true if the file is a directory, false
otherwise. isSymLink true if the false is a symbolic link, false
otherwise. (As of Firefox 38 this is always true on all systems, this is a bug: Bugzilla 1145885) (On Windows this returns false for hard links) size The number of bytes in the file. creationDate Deprecated in Bugzilla :: Bug 807875. Before deprecation, this used to be the date at which the file was created...
PerfMeasurement.jsm
PerfMeasurement.ALL to record all event types. Return value A new PerfMeasurement object configured to record the specified event types. Methods canMeasureSomething() Indicates whether or not the platform on which your code is running supports this code module. static bool canMeasureSomething(); Parameters None. Return value If even one of the event types can be recorded, this will return true.
Otherwise, it returns false. reset() Resets all the enabled counters to zero. void reset(); Parameters None. start() Starts measuring the performance indicators that were specified when the PerfMeasurement object was created. void start(); Parameters None. stop() Stops measuring performance data. For each enabled counter, the number of measured events of that type that occurred are added to the appropria...
PopupNotifications.jsm
eir anchor. This lets you create a notification that will appear when the user clicks the anchor. eventCallback A JavaScript function to be invoked when the notification changes state. The callback's first parameter is a string identifying the state change that occurred. See Notification events below. neverShow Notifications with this parameter set to true will be removed when they would have
otherwise been dismissed (i.e. any time the popup is closed due to user interaction). removeOnDismissal Notifications with this parameter set to true will be removed when they would have
otherwise been dismissed (that is, any time the popup is closed due to user interaction). popupIconURL A string specifying the URL of the image to be displayed in the popup. This is normally specified in CSS using lis...
Examples
console.log(filesContent); }, function onFail() { console.error("Failed to load all files"); } ); See also the ask.m.o topic: Doing multiple promises in function in pareallel, how return when last done? Simple Example User Defined Promise Function 2 Whenever you want to make a function a promise. Always wrap that function in a try catch and make that catch return Promise.reject(ex)
otherwise it will not trigger the rejection function of the promise.then. This way if any error happens it will reject the promise. In the example below we try alerting an undefined variable. Components.utils.import("resource://gre/modules/Promise.jsm"); var myPromise = myUserDefinedPromise(); myPromise.then( function(aSuccessReason) { alert('myPromise was SUCCESFUL and reason was = "' + aSuccessRe...
Promise
Documentation conventions In documentation, the type of the fulfillment value is usually specified between angular brackets. For example, the OS.File.exists function returns a promise that will eventually fulfill with a boolean: Promise<boolean> exists(string path); The rejection reason may be specified separately in the function's documentation, and is considered to be an Error object unless
otherwise specified. Method overview Promise then([optional] Function onFulfill, [optional] Function onReject); Promise catch([optional] Function onReject); Constructor Creates a new promise, initially in the pending state, and provides references to the resolving functions that can be used to change its state. new Promise(executor); Parameters executor This function is...
PromiseWorker.jsm
a message to the main thread, postMessage is typically used. However with PromiseWorker objects this is no longer the case, simply return data or throw from your function depending if you want to resolve or reject the promise. In summary, from a worker file, data can only be sent back as a response to a request from the main thread, it is not possible for a worker to send data to the main thread
otherwise, this is a key difference between PromiseWorker worker file and all other types of workers. Resolving the Promise To resolve the promise from the worker, simply return anything from the worker scope, and the main thread promise will be resolved with the returned value. function func(buffer) { // do something with buffer... return 1; // 1 is sent back to main thread, as a resolved promise.
XPCOMUtils.jsm
is an XPCOM component. generateQI() Generates a QueryInterface() function implementation. You need to assign the returned function to the QueryInterface property of a JavaScript object. When the generated method is invoked on that object, it checks to see if the specified IID is listed in the array specified by the interfaces parameter; if it is, this (that is, the object itself) is returned.
Otherwise, null is returned. function generateQI( interfaces ); Parameters interfaces An array of interfaces implemented by the component. Return value A QueryInterface() function implementation. Remarks When you implement an interface that inherits from another one, you should generally list all the base interfaces explicitly, except for nsISupports. For example, if your component implements...
Localizing with Koala
/l10n-mozilla-1.9.2/x-testing 3.6 New localizations: If you have the BitBucket repository already set up by l10n-drivers, the steps are the same as above. Just hg clone from the right BitBucket URL. For example: C:\Users\stas> cd C:\mozilla\l10n\locale\x-testing C:\mozilla\l10n\locale\x-testing> rmdir 3.6 C:\mozilla\l10n\locale\x-testing> hg clone http://bitbucket.org/mozillal10n/x-testing 3.6
Otherwise, it's a good idea to create your local repository in order to be able to track changes you make to the localization files. To do this, open the console and type: C:\Users\stas> cd C:\mozilla\l10n\locale\x-testing\3.6 C:\mozilla\l10n\locale\x-testing\3.6> hg init You should now see the the Koala's starpage in Komodo. You are ready to start localizing Firefox! Comparing and translating Now th...
QA phase
ew repository is created by the l10n-drivers, please visit the URL for your repo. We'll use x-testing here for our example. You can do this by entering the following URL into your browser: http://hg.mozilla.org/l10n-central/x-testing Now, navigate to your locale's directory on your local machine. If you're using Koala, this should be located at /path/to/your/koala.project/locale/3.6/x-testing,
otherwise, it should be located at /path/to/your/working_dir/l10n_base/x-testing. In this directory, you should have an hg repository. You might have created it yourself by running hg init or hg clone or you might have had it created by Koala when you were setting up a new localization project. Also at this point, you shouldn't have any uncommitted changes (i.e., running the hg status command should show ...
Release phase
ficial release repository Now that your locale has been registered, the localization files will live on Mozilla Mercurial server at hg.mozilla.org. Depending on which branch you work on, the URL of your repository might look like this: http://hg.mozilla.org/releases/l10n-central/x-testing If you followed the Koala or plain text approach, you probably already have a local clone of the repository.
Otherwise, in order to be able to make any changes to the localization files, you will need to clone the repository on your local machine and work in the local clone. There are two different protocols you can use to connet with your Mercurial repository: HTTP and SSH. Be advised that there's an important distinction between them. You can pull using both, but you can only push through SSH. Consequently, if ...
Creating localizable web applications
ame']); Snippet 6. Good: // %1$s is persona name, %2$s is athor's username printf(_("%1$s by %2$s"), $persona['name'], $persona['display_username']); Use printf variables swapping Use printf() ordered variables (%1$s, %2$s, etc.) to allow changes to the order of the sentence. Some languages may require this. Remember to use single quotes around the strings containing the formatting symbols.
Otherwise, PHP will treat $s as a regular variable, instead of parsing the whole %1$s formatting symbol. Snippet 1. Bad: $page_header = $persona['name'] . ' by ' . $persona['display_username']; Snippet 2. Better: printf(_("%s by %s"), $persona['name'], $persona['display_username']); Snippet 3. Good: // %1$s is the persona's name, %2$s is the athor's username printf(_('%1$s by %2$s'), $persona['name']...
Basics
in the main flow of text and respond as you resize the window. You can also make displayed equations, such as the following ones: x -> maps to y = f n ( x ) = ( 1 + 1 x n ) n ? a b f ( x ) d x = b - a 6 [ f ( a ) + 4 f ( a + b 2 ) + f ( b ) ] - ( b - a ) 5 4 ! 5 ! f ( 4 ) ( ? ) , a <= ? <= b | x | = { - x if x < 0 x
otherwise You can also typeset 2D mathematical constructs such as matrices. The following example shows the i-th step of the multiplication of a matrix A by a vector x (notice how ai1 , ... , ain , x1 are on the same baseline, other alignments are possible): i-th row [ a11 a12 a13 ... a1n : : : ... : ai1 ai2 ai3 ... ain : : : : ...
MathML Demo: <mtable> - tables and matrices
m the scriptlevel. ---... ab ? ? abx yab ? ? ab ...--- . Anyway, this is buggy in Mozilla because what you see above is a fallback to the rendering code used for the baseline case (see below). A table with align="baseline -1" to anchor the table externally w.r.t. the baseline of the last row ---... d+p ( ? ? ? ? ) ...--- , neat isn't it? This would be pretty hard to obtain
otherwise. Contrast it with the following which has align="bottom" ---... d+p ( ? ? ? ? ) ...--- , and with this one which has align="center -1" ---... d+p ( ? ? ? ? ) ...--- , but note that setting the baseline relative to a particular row is meaningless if the row doesn't have at least one cell with "rowalign=baseline" where to anchor the baseline (in which case Mozilla will behave ...
Using the viewport meta tag to control layout on mobile browsers
a large variation of screen sizes and orientations. The default pixel ratio depends on the display density. On a display with density less than 200dpi, the ratio is 1.0. On displays with density between 200 and 300dpi, the ratio is 1.5. For displays with density over 300dpi, the ratio is the integer floor(density/150dpi). Note that the default ratio is true only when the viewport scale equals 1.
Otherwise, the relationship between CSS pixels and device pixels depends on the current zoom level. Viewport width and screen width Sites can set their viewport to a specific size. For example, the definition "width=320, initial-scale=1" can be used to fit precisely onto a small phone display in portrait mode. This can cause problems when the browser doesn't render a page at a larger size. To fix this, b...
Mozilla Port Blocking
aused by Port Blocking Port blocking can cause problems if a site or web application requires access to one of the ports which is blocked in Mozilla. If a user attempts to access a URI on a blocked port, Mozilla shows one of the following alerts to the user or in the Error Console. "Access to the port number given has been disabled for security reasons." "Establishing a connection to an unsafe or
otherwise banned port was prohibited" "0x804b0013 (NS_ERROR_PORT_ACCESS_NOT_ALLOWED)" If your product or web site uses a port which is blocked by Mozilla's default port blocking rules, you can either change the port of your service to a unblocked value (recommended if possible) or ask your Mozilla users to enable the port. For details on which ports are blocked and how to override the blocking see below. M...
Mozilla Web Developer FAQ
iate Unicode character instead of trying to apply a dingbat font to an ASCII character. For example, to represent :), you should use WHITE SMILING FACE (U+263A). Why isn't Mozilla rendering my page as I intended? So my page isn't standards-compliant, but good browsers should render pages as the author intended anyway! Authors are supposed to communicate their intentions using the Web standards.
Otherwise, finding out the intentions of each particular author would require psychic abilities which can't be implemented in software. Even in cases where a human could deduce the intention, doing so in software would be very slow, bug-inducing, difficult and complicated. The usual counter argument is that there is no need to guess--Mozilla should do whatever browser x does (where x is the favorite non-M...
Mozilla Web Services Security Model
[Not implemented!] Ability to load documents via XMLHttpRequest or similar mechanisms. soap SOAP requests without verification headers soapv SOAP requests with verification headers The from attribute The from attribute on the allow element says which calling sites the allow element applies to. If there is no from attribute then the allow element applies to all sites. The from attribute
otherwise gives a URL to match, which may contain up to two asterisks (*) that match any characters in the URL. The match is done against a URL from which the directory and file have been removed, so trying to match a specific page will cause the entire match to fail. (Is this correct?) web-scripts-access.xml Examples These examples are untested! Somebody should test them to make sure they do what is cla...
Mozilla Quirks Mode Behavior
n is propagated into floating and absolutely positioned elements. (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) In quirks mode, text-decoration is not propagated into tables (bug 572713). maybe (Firefox 3) When computing the minimum intrinsic width of an inline flow directly in a table cell (no blocks in between), it is assumed that it is not possible to break before and after an image (when
otherwise it would be). Obsolete since Gecko 8.0 Prior to Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5) text-decoration in quirks mode had line thickness and position adjusted on descendant text to match the descendant. Tables TD, TH, TR, THEAD, TBODY, and TFOOT elements have the document background (and color?) applied to them (when the document background is specified in certain ways?) ...
Intel Power Gadget
) also exposes an API from which the same measurements can be extracted programmatically. At one point the Gecko Profiler used this API on Windows to implement experimental package power estimates. Unfortunately, the Gecko profiler takes 1000 samples per second on desktop and is CPU intensive and so is likely to skew the RAPL estimates significantly, so the API integration was removed. The API is
otherwise unlikely to be of interest to Mozilla developers. ...
Refcount tracing and balancing
comes from a smart pointer that is logged in the XPCOM_MEM_COMPTR_LOG, then find-comptr-leakers.pl will find the exact stack for you, and you don't have to look at trees. Ignore balanced trees. The make-tree.pl script accepts an option --ignore-balanced, which tells it not to bother printing out the children of a node whose balance factor is zero. This can help remove some of the clutter from an
otherwise noisy tree. Ignore matched releases from smart pointers. If you've checked (see above) that the leak wasn't from a smart pointer, you can ignore the references that came from smart pointers (where we can use the pointer identity of the smart pointer to match the AddRef and the Release). This requires using an XPCOM_MEM_REFCNT_LOG and an XPCOM_MEM_COMPTR_LOG that were collected at the same time. ...
tools/power/rapl
$OBJDIR/dist/bin/rapl Linux On Linux, rapl can be run as root, as follows. sudo $OBJDIR/dist/bin/rapl Alternatively, it can be run without root privileges by setting the contents of /proc/sys/kernel/perf_event_paranoid to 0. Note that if you do change this file, its contents may reset when the machine is next rebooted. You must be running Linux kernel version 3.14 or later for rapl to work.
Otherwise, it will fail with an error message explaining this requirement. Windows Unfortunately, rapl does not work on Windows, and porting it would be difficult because Windows does not have APIs that allow easy access to the relevant model-specific registers. Output The following is 10 seconds of output from a default invocation of rapl. total W = _pkg_ (cores + _gpu_ + other) + _ram_ W #01 5.
Productization guide
cations installed on their computer. But we also suggest a few web-based clients (like Yahoo! Mail and GMail), so that if the user happens to use one of these in the browser, they don't have to configure them. The second purpose (demonstrate certain features of the product) is equally important: by providing these default services, we demonstrate particular features of the product, the ones which
otherwise wouldn't be as discoverable. For example, putting one sample news feed on the Bookmarks Toolbar in new profiles in Firefox helps in learning about the Live Bookmarks. Including a couple of search engines instead of one in the Search Toolbar can help users understand that they can add as many plug-ins as they wish. This guide will walk you through the steps to successfully productizing your locali...
NSPR Poll Method
calling both PR_Recv and PR_Send on the same file descriptor, make two separate calls to the poll method, one with PR_POLL_READ as in_flags and the other with PR_POLL_WRITE as in_flags, so that you know what events at the network transport layer PR_POLL_READ and PR_POLL_WRITE are mapped to, respectively. On return, if (new_flags & out_flags) is nonzero, you can try PR_Recv or PR_Send immediately.
Otherwise ((new_flags & out_flags) is 0), you should do the following. If new_flags contains PR_POLL_READ, you should try PR_Recv or PR_Send when the underlying network transport is readable If new_flags contains PR_POLL_WRITE, you should try PR_Recv or PR_Send when the underlying network transport is writable Important do not use out_flags in any way other than testing if (new_flags & out_flags) is 0.
PRBool
Boolean value. Syntax #include <prtypes.h> typedef enum { PR_FALSE = 0, PR_TRUE = 1 } PRBool; Description Wherever possible, do not use PRBool in Mozilla C++ code. Use standard C++ bool instead.
Otherwise, use PRBool for variables and parameter types. Use PR_FALSE and PR_TRUE for clarity of target type in assignments and actual arguments. Use if (bool), while (!bool), (bool) ? x : y, and so on to test Boolean values, just as you would C int-valued conditions. ...
PRFileDesc
methods table. See PRIOMethods. secret Layer-dependent implementation data. See PRFilePrivate. lower Pointer to lower layer. higher Pointer to higher layer. dtor A destructor function for the layer. identity Identity of this particular layer. See PRDescIdentity. Description The fields of this structure are significant only if you are implementing a layer on top of NSPR, such as SSL.
Otherwise, you use functions such as PR_Open and PR_NewTCPSocket to obtain a file descriptor, which you should treat as an opaque structure. For more details about the use of PRFileDesc and related structures, see File Descriptor Types. ...
PR_ASSERT
Terminates execution when a given expression is FALSE. Syntax #include <prlog.h> void PR_ASSERT ( expression ); Parameters The macro has this parameter: expression Any valid C language expression that evaluates to TRUE or FALSE. Returns Nothing Description This macro evaluates the specified expression. When the result is zero (FALSE) the application terminates;
otherwise the application continues. The macro converts the expression to a string and passes it to PR_Assert, using file and line parameters from the compile-time environment. This macro compiles to nothing if compile-time options are not specified to enable logging. ...
PR_CLIST_IS_EMPTY
Checks for an empty circular list. Syntax #include <prclist.h> PRIntn PR_CLIST_IS_EMPTY (PRCList *listp); Parameter listp A pointer to the linked list. Description PR_CLIST_IS_EMPTY returns a non-zero value if the specified list is an empty list,
otherwise returns zero. ...
PR_GetErrorTextLength
Gets the length of the error text. Syntax #include <prerror.h> PRInt32 PR_GetErrorTextLength(void) Returns If a zero is returned, no error text is currently set.
Otherwise, the value returned is sufficient to contain the error text currently available. ...
PR_GetSpecialFD
o.h> PRFileDesc* PR_GetSpecialFD(PRSpecialFD id); Parameter The function has the following parameter: id A pointer to an enumerator of type PRSpecialFD, indicating the type of I/O stream desired: PR_StandardInput, PR_StandardOutput, or PR_StandardError. Returns If the id parameter is valid, PR_GetSpecialFD returns a file descriptor that represents the corresponding standard I/O stream.
Otherwise, PR_GetSpecialFD returns NULL and sets the error to PR_INVALID_ARGUMENT_ERROR. Description Type PRSpecialFD is defined as follows: typedef enum PRSpecialFD{ PR_StandardInput, PR_StandardOutput, PR_StandardError } PRSpecialFD; #define PR_STDIN PR_GetSpecialFD(PR_StandardInput) #define PR_STDOUT PR_GetSpecialFD(PR_StandardOutput) #define PR_STDERR PR_GetSpecialFD(PR_StandardError) Fi...
PR_Interrupt
Sets the interrupt request for a target thread. Syntax #include <prthread.h> PRStatus PR_Interrupt(PRThread *thread); Parameter PR_Interrupt has the following parameter: thread The thread whose interrupt request you want to set. Returns The function returns one of the following values: If the specified thread is currently blocked, PR_SUCCESS.
Otherwise, PR_FAILURE. Description The purpose of PR_Interrupt is to request that a thread performing some task stop what it is doing and return to some control point. It is assumed that a control point has been mutually arranged between the thread doing the interrupting and the thread being interrupted. When the interrupted thread reaches the prearranged point, it can communicate with its peer to discover the real reason behind the change...
PR_LOG_TEST
og module structure. _level A level value. Possible values are: PR_LOG_NONE = 0 PR_LOG_ALWAYS = 1 PR_LOG_ERROR = 2 PR_LOG_WARNING = 3 PR_LOG_DEBUG = 4 PR_LOG_NOTICE = PR_LOG_DEBUG PR_LOG_WARN = PR_LOG_WARNING PR_LOG_MIN = PR_LOG_DEBUG PR_LOG_MAX = PR_LOG_DEBUG Returns PR_TRUE when logging is enabled for the given module and level,
otherwise PR_FALSE. Description This macro tests whether logging is enabled for the specified module and level. Use it as an expression in a conditional execution statement to control logging. See also PR_LOG. ...
PR_STATIC_ASSERT
ro has this parameter: expression Any valid expression which evaluates at compile-time to TRUE or FALSE. An expression which cannot be evaluated at compile time will cause a compiler error; see PR_ASSERT for a runtime alternative. Returns Nothing Description This macro evaluates the specified expression. When the result is zero (FALSE) program compilation will fail with a compiler error;
otherwise compilation completes successfully. The compiler error will include the number of the line for which the compile-time assertion failed. This macro may only be used in locations where an extern function declaration may be used. ...
PR_SetErrorText
Sets the text associated with an error. Syntax #include <prerror.h> void PR_SetErrorText(PRIntn textLength, const char *text) Parameters The function has these parameters: textLength The length of the text in the text. May be NULL. If not NULL, and if text is zero, the string is assumed to be a null-terminated C string.
Otherwise the text is assumed to be the length specified and to possibly include NULL characters (as might occur in a multilingual string). text The text to associate with the error. Description The text is copied into the thread structure and remains there until the next call to PR_SetError. If there is error text already present in the thread, the previous value is first deleted. The new value is copied into storage allocated and owned by NSPR and remains there ...
PR_SetLogFile
Sets the name of the log file. Syntax #include <prlog.h> PRBool PR_SetLogFile(const char *name); Parameters The function has this parameter: name The name of the log file. Returns PR_TRUE when successful.
Otherwise, PR_FALSE. Description Creates a log file with the specified file name. Subsequent log messages are written to this file. Ordinarily, a user application need not use this function, as NSPR initializes logging at NSPR startup. The application can use the model provided in Use Example to effect application logging. ...
PR_StringToNetAddr
retrieve the reason for the failure by calling PR_GetError. Description For IPv4 addresses, the input string represents numbers in the Internet standard "." notation. IPv6 addresses are indicated as strings using ":" characters separating octets, with numerous caveats for shortcutting (see RFC #1884). If the NSPR library and the host are configured to support IPv6, both formats are supported.
Otherwise, use of anything other than IPv4 dotted notation results in an error. ...
NSS Code Coverage
Colors Green: 70-100% of blocks tested. Yellow: 40-70% of blocks tested. Orange: 0-40% of blocks tested. Red: file not tested. File is not part of any binary or library used by test suite. ...
NSS 3.34 release notes
word in FIPS mode, a correct explanation of acceptable passwords will be printed. SSLKEYLOGFILE is now supported with TLS 1.3, see Bug 1287711 for details. SSLChannelInfo has two new fields (Bug 1396525) SSLNamedGroup originalKeaGroup holds the key exchange group of the original handshake, when the session was resumed. PRBool resumed is PR_TRUE when the session is resumed, and PR_FALSE
otherwise. RSA-PSS signatures are now supported on certificates. Certificates with RSA-PSS or RSA-PKCS#1v1.5 keys can be used to create an RSA-PSS signature on a certificate, using the --pss-sign argument to certutil. New Functions Bugs fixed in NSS 3.34 This Bugzilla query returns all the bugs fixed in NSS 3.34: https://bugzilla.mozilla.org/buglist.cgi?resolution=FIXED&classification=Component...
NSS API Guidelines
ode in for all constituent objects, unless they're actually being used Our agressive pointer-tracking facility All these are useful, but they don't combine well. Now some of the pointer-tracking pressure has eased off, we can drop its use when it becomes too difficult. Many routines are defined to take an NSSArena *arenaOpt argument. This means if an arena is specified (non-null), it is used,
otherwise (null) the routine uses the heap. You can think of the heap as a default arena you can't destroy. Error Handling NSS 3.0 introduces the concept of an error stack. When something goes wrong, the call stack unwinds, with routines returning an error indication. Each level which flags a problem, adds its own error number to the stack. At the bottom of the stack is the fundamental error, for example...
nss tech note3
_AGREEMENT. Cert Extensions: One vital Certificate extension is the "Basic Constraints" extension. It tells NSS whether the cert is a CA cert, or not, and affects every other aspect of how the cert is interpreted by NSS. The OID for this extension is { 2 5 29 19 }, encoded in hex as 0x55, 0x1d, 0x13. If the extension is present and has the value TRUE, then this cert is taken to be a CA cert.
Otherwise it is not (except that trust flags may override this, see discussion of trust flags farther below). Netscape has its own openly defined Cert Type extension, which can be used to explicitly set the Cert Type in any Cert. The Cert Type extension has bits in it that correspond directly to the cert types named above. The OID for this extension is { 2 16 840 1 113730 1 1 } encoded in hex as 0x60, 0...
NSS PKCS11 Functions
en is available, PR_TRUE. If token is disabled or missing, PR_FALSE. PK11_IsReadOnly Finds out whether a slot is read-only. Syntax #include <pk11pub.h> #include <prtypes.h> PRBool PK11_IsReadOnly(PK11SlotInfo *slot); Parameters This function has the following parameter: slot A pointer to a slot info structure. Returns The function returns one of these values: If slot is read-only, PR_TRUE.
Otherwise, PR_FALSE. PK11_SetPasswordFunc Defines a callback function used by the NSS libraries whenever information protected by a password needs to be retrieved from the key or certificate databases. Syntax #include <pk11pub.h> #include <prtypes.h> void PK11_SetPasswordFunc(PK11PasswordFunc func); Parameter This function has the following parameter: func A pointer to the callback function to set. D...
Build instructions
es. hg clone https://hg.mozilla.org/projects/nspr hg clone https://hg.mozilla.org/projects/nss If you want to build a releases other than the tips of these repositories, then switch to the release tags: cd nspr hg update NSPR_4_9_5_RTM cd ../nss hg update NSS_3_14_2_RTM cd .. Set environment variables: If you want a non-debug optimized build, set BUILD_OPT=1 in your environment.
Otherwise, you get a debug build. On Windows, if you want a debug build with the system's debug RTL libraries, set USE_DEBUG_RTL=1 in your environment. On Unix platforms, except Alpha/OSF1, if you want a build for the system's 64-bit ABI, set USE_64=1 in your environment. By default, NSS builds for the 32-bit environment on all platforms except Alpha/OSF1. To build with gcc on platforms other than Li...
FC_GetSessionInfo
PTR pInfo ); Parameters hSession [in] the open session handle. pInfo [out] pointer to the CK_SESSION_INFO structure to be returned. Description FC_GetSessionInfo obtains information about a session. A user may call FC_GetSessionInfo without logging into the token (to assume the NSS User role). If the NSS cryptographic module is in the error state, FC_GetSessionInfo returns CKR_DEVICE_ERROR.
Otherwise, it fills in the CK_SESSION_INFO structure with the following information: state: the state of the session, i.e., no role is assumed, the User role is assumed, or the Crypto Officer role is assumed flags: bit flags that define the type of session CKF_RW_SESSION (0x00000002): true if the session is read/write; false if the session is read-only. CKF_SERIAL_SESSION (0x00000004): this flag is pr...
FC_GetSlotList
pSlotList [out] Either null or a pointer to an existing array of CK_SLOT_ID objects. ...
NSS tools : certutil
access to this file. -g keysize Set a key size to use when generating new public and private key pairs. The minimum is 512 bits and the maximum is 16384 bits. The default is 2048 bits. Any size between the minimum and maximum is allowed. -h tokenname Specify the name of a token to use or act on. Unless specified
otherwise the default token is an internal slot. -i input_file Pass an input file to the command. Depending on the command option, an input file can be a specific certificate, a certificate request file, or a batch file of commands. -k rsa|dsa|ec|all Specify the type of a key. The valid options are RSA, DSA, ECC, or al...
pkfnc.html
adOnly Finds out whether a slot is read-only. Syntax #include <pk11func.h> #include <prtypes.h> PRBool PK11_IsReadOnly(PK11SlotInfo *slot); Parameters This function has the following parameter: slot A pointer to a slot info structure. Returns The function returns one of these values: If slot is read-only, PR_TRUE.
Otherwise, PR_FALSE. PK11_SetPasswordFunc Defines a callback function used by the NSS libraries whenever information protected by a password needs to be retrieved from the key or certificate databases. Syntax #include <pk11func.h> #include <prtypes.h> void PK11_SetPasswordFunc(PK11PasswordFunc func); Parameter This function has the following parameter: func ...
NSS Tools certutil
ed access to this file. -g keysize Set a key size to use when generating new public and private key pairs. The minimum is 512 bits and the maximum is 8192 bits. The default is 1024 bits. Any size that is a multiple of 8 between the minimum and maximum is allowed. -h tokenname Specify the name of a token to use or act on. Unless specified
otherwise the default token is an internal slot (specifically, internal slot 2). This slot can also be explicitly named with the string "internal". An internal slots is a virtual slot maintained in software, rather than a hardware device. Internal slot 2 is used by key and certificate services. Internal slot 1 is used by cryptographic services. -i cert|cert-request-file Specif...
certutil
authorized access to this file. -g keysize Set a key size to use when generating new public and private key pairs. The minimum is 512 bits and the maximum is 8192 bits. The default is 1024 bits. Any size between the minimum and maximum is allowed. -h tokenname Specify the name of a token to use or act on. Unless specified
otherwise the default token is an internal slot (specifically, internal slot 2). This slot can also be explicitly named with the string "internal". An internal slots is a virtual slot maintained in software, rather than a hardware device. Internal slot 2 is used by key and certificate services. Internal slot 1 is used by cryptographic services. -i ...
Proxies in Necko
its host and its port. nsIIOService The decision whether to use a proxy is made in nsIOService::NewChannelFromURI. It first asks the nsIProtocolProxyService for an nsIProxyInfo. Depending on the type of the proxy info, it either asks the HTTP Protocol Handler or the protocol handler for the requested URI for a new channel with the nsIProxyInfo - if the channel supports nsIProxiedProtocolHandler.
Otherwise, the proxy info is discarded. nsIProtocolProxyService The most important function on nsIProtocolProxyService is resolve. It checks whether the passed-in URI should use a proxy, and returns an nsIProxyInfo if so. This works by examining the protocolFlags of the protocol handler for the given URI. If this protocol handler does not support proxies, resolve returns null. Alternatively, if proxies are...
Rhino Debugger
ou are debugging: Step Into To single step entering any function calls, you may do any of the following: Select the Debug->Step Into menu item on the menu bar Press the Step Into button on the toolbar Press the F11 key on the keyboard Execution will resume. If the current line in the script contains a function call control will return to the debugger upon entry into the function.
Otherwise control will return to the debugger at the next line in the current function. Step Over To single step to the next line in the current function, you may do any of the following: Select the Debug->Step Over menu item on the menu bar Press the Step Over button on the toolbar Press the F7 key on the keyboard Execution will resume but control will return to the debugger at the next ...
Small Footprint
er It is possible to run Rhino with interpreter mode only, allowing you to remove code for classfile generation that include all the classes from <tt>org.mozilla.javascript.optimizer</tt> package. JavaAdapter Implementing the JavaAdapter functionality requires the ability to generate classes on the fly. Removing org.mozilla.javascript.JavaAdapter will disable this functionality, but Rhino will
otherwise run correctly. Class generation library If you do not include Optimizer or JavaAdapter, nor do you use PolicySecurityController then you do not need Rhino library for class file generation and you can remove all the classes from in org.mozilla.classfile package. Regular Expressions The package org.mozilla.javascript.regexp can be removed. Rhino will continue to run, although it will not be ab...
Rhino shell
and with the given argument and options as a separate process and return the exit status of the process. Usage: runCommand(command) runCommand(command, arg1, ..., argN) runCommand(command, arg1, ..., argN, options) All except the last arguments to runCommand are converted to strings and denote command name and its arguments. If the last argument is a JavaScript object, it is an option object.
Otherwise it is converted to string denoting the last argument and options objects assumed to be empty. The following properties of the option object are processed: args - provides an array of additional command arguments env - explicit environment object. All its enumeratable properties define the corresponding environment variable names. input - the process input. If it is not java.io.InputStream, ...
GC Rooting Guide
edefs for local variables on the stack. Use JS::Handle<T> typedefs for function parameters. Use JS::MutableHandle<T> typedefs for function out-parameters. Use an implicit cast from JS::Rooted<T> to get a JS::Handle<T>. Use an explicit address-of-operator on JS::Rooted<T> to get a JS::MutableHandle<T>. Return raw pointers from functions. Use JS::Rooted<T> fields when possible for aggregates,
otherwise use an AutoRooter. Use JS::Heap<T> members for heap data. Note: Heap<T> are not "rooted": they must be traced! Do not use JS::Rooted<T>, JS::Handle<T> or JS::MutableHandle<T> on the heap. Do not use JS::Rooted<T> for function parameters. Use JS::PersistentRooted<T> for things that are alive until the process exits (or until you manually delete the PersistentRooted for a reason not based on GC...
Functions
all functions, if a name definitely refers to a global for which we have seen a var, const, or function declaration, then we emit a JS_DEFVAR instruction in the script prelude and access the global using JSOP_{GET,SET,CALL}GVAR. This is fast if the global either doesn't exist before the script runs (the script creates it) or it's a non-configurable data property (which amounts to the same thing).
Otherwise the GVAR instructions are as slow as NAME instructions. There are also combo instructions JSOP_{INC,DEC}GVAR and JSOP_GVAR{INC,DEC}. NAME instructions. In the worst case we emit JSOP_{,SET,CALL}NAME. These are totally general. They can still be optimized via the property cache; in the worst case we walk the scope chain. In some cases, the JIT can optimize a JSOP_NAME instruction that re...
Statistics API
th some related data. There are several ways to get access to this data: The environment variable MOZ_GCTIMER controls text dumping of GC stats. MOZ_GCTIMER may be none, stderr, stdout, or a filename. If a filename is given, data is appended to that file. When logging to a file is used in combination with multi-process firefox (e10s) it is necessary to set security.sandbox.content.level = 0,
otherwise the content process will crash. The browser preference javascript.options.mem.log controls dumping of human-readable GC stats messages to the developer console. The browser preference javascript.options.mem.notify controls emission of JSON encoded GC stats to an observer interface. JSON API Addons can obtain the complete data in JSON format via an observer. The following adds an observer usi...
SpiderMonkey Internals: Thread Safety
one thread doing GC and all requests suspended. A call to JS_GC() will block until the latter becomes possible. In other words, GC waits until each other thread is either outside JSAPI (in which case we don't care what it's doing) or else in JSAPI, but blocked, waiting for GC to finish. Threads must not do anything that would affect GC while outside a request. And obviously you shouldn't block or
otherwise dilly-dally while in a request; it prohibits GC. As an optimization, each thread has its own size-classified freelists containing chunks of GC-managed memory ready to be allocated. This allows allocation to avoid locking most of the time (a significant speed win). A thread needs to lock on allocation only when the relevant per-thread freelist is empty. When this happens, the thread also refills t...
Self-hosted builtins in SpiderMonkey
ntrast to Function.prototype.call, this syntax makes it impossible for other code to interfere and gets compiled to bytecode that doesn't have any overhead compared to a normal function invocation. OTOH, normal method calls are forbidden in self-hosted code. So instead of receiver.fun(arg1, ..., argN) you have to use callFunction(fun, receiver, arg1, ... argN). This restriction was added because
otherwise it's extremely easy to accidentally call methods that have been changed by content, changing the behavior from what was expected. If the fun can potentially be a content-provided function, callContentFunction has to be used. This is to prevent accidentally calling content functions when assuming that content can't interfere with behavior. E.g., if receiver is an object that content has access to...
SpiderMonkey Internals
by unaligned 16-bit immediate bytecode operands, as unique string descriptors for efficient property name hashing, and as members of the root GC set for exact GC. Standard library The methods for arrays, booleans, dates, functions, numbers, and strings are implemented using the JS API. Most are JSFastNatives. Most string methods are customized to accept a primitive string as the this argument. (
Otherwise, SpiderMonkey converts primitive values to objects before invoking their methods, per ECMA 262-3 ?11.2.1.) Error handling SpiderMonkey has two interdependent error-handling systems: JavaScript exceptions (which are not implemented with, or even compatible with, any kind of native C/C++ exception handling) and error reporting. In general, both functions inside SpiderMonkey and JSAPI callback fun...
JSAPI Cookbook
JavaScript var r = f(); // where f is a local variable /* JSAPI * * Suppose f is a local C variable of type JS::Value. */ JS::AutoValueVector args(cx); // empty argument list JS::RootedValue r(cx); if (!JS_CallFunctionValue(cx, NULL, f, args, &r) return false; Returning an integer // JavaScript return 23; /* JSAPI * * Warning: This only works for integers that fit in 32 bits. *
Otherwise, convert the number to floating point (see the next example). */ JS::CallArgs args = JS::CallArgsFromVp(argc, vp); args.rval().setInt32(23); return true; Returning a floating-point number // JavaScript return 3.14159; /* JSAPI */ JS::CallArgs args = JS::CallArgsFromVp(argc, vp); args.rval().setDouble(3.14159); Exception handling throw The most common idiom is to create a new Error objec...
INT_FITS_IN_JSVAL
fied C integer is safe to pass to INT_TO_JSVAL. Syntax #define INT_FITS_IN_JSVAL(i) /* ... */ Name Type Description i jsint The C integer value to check. Description Determines if a specified C integer value, i, lies within the range allowed for integer jsvals. If so, INT_FITS_IN_JSVAL returns TRUE, and i can be cast to jsval by calling INT_TO_JSVAL(i).
Otherwise, INT_FITS_IN_JSVAL returns FALSE. In this case, the application can still convert i to a jsval using JS_NewNumberValue. Warning: The type of the argument i must be jsint, but the C/C++ compiler does not enforce type safety here. If i is an unsigned or 64-bit value, INT_FITS_IN_JSVAL can silently give the wrong answer. Starting in SpiderMonkey 1.8.5, jsval can store a full 32-bit integer, so thi...
JS::Add*Root
ic string constant, identifying the source location of the call to JS::AddNamed*Root for debugging purposes. Needs the Example for typical usage of the name parameter. All the JS::Add*Root methods are idempotent: multiple calls for the same address will add only one root. Correspondingly, only a single JS::Remove*Root is required to unroot the location. On success, these functions return true.
Otherwise they report an out of memory error and return false. See Also MXR ID Search for JS::AddValueRoot MXR ID Search for JS::AddStringRoot MXR ID Search for JS::AddObjectRoot MXR ID Search for JS::AddNamedValueRoot MXR ID Search for JS::AddNamedValueRootRT MXR ID Search for JS::AddNamedStringRoot MXR ID Search for JS::AddNamedObjectRoot MXR ID Search for JS::AddNamedScriptRoot bug 912581 b...
JS::CallArgs
used! JS::HandleValue thisv() const Returns the this value passed to the function. This method must not be called when the function is being called as a constructor via new. The value may or may not be an object: it is the individual function's responsibility to box the value if needed. JS::Value computeThis(JSContext *cx) const Returns the this value if this is an object,
otherwise calls JS_ComputeThis and returns it. bool isConstructing() const Returns true if the function is called via new. MutableHandleValue rval() const Returns the currently-set return value. The initial contents of this value are unspecified. Once this method has been called, callee() and calleev() can no longer be used. (If you're compiling against a debug build of SpiderM...
JS::Compile
length indicates the size of the text version of the script in characters. file is the filehandle containing the text of the script. filename is the name of the file (or URL) containing the script. This information is included in error messages if an error occurs during compilation.. On success, JS::Compile stores an object representing the newly compiled script into script, and returns true.
Otherwise, it returns false and the value left in script is undefined. See Also The JSAPI User Guide contains example code using compiled scripts. MXR ID Search for JS::Compile JS::Evaluate JS::CompileOffThread JS::CompileFunction JS_DecompileScript bug 771705 bug 1143793 -- removed obj parameter ...
JS::CompileFunction
of an array of names to assign each argument. The number of argument names should match the number of arguments specified in nargs. chars, bytes, or srcBuf is a string containing the source code of the function. length is the length of the source code in characters. On success, JS::CompileFunction stores an function object representing the newly compiled function into fun and and returns true.
Otherwise, it returns false and the value left in fun is undefined. See Also The JSAPI User Guide contains example code using compiled scripts. MXR ID Search for JS::CompileFunction JS::Evaluate JS::Compile JS::CompileOffThread JS_ExecuteScript JS_DecompileScript bug 771705 ...
JS::CreateError
orReport * A pointer to JSErrorReport instance. message JS::HandleString The value of Error.prototype.message. rval JS::MutableHandleValue Out parameter. Receives the created error object. Description JS::CreateError creates an Error object with specified properties. If successful, JS::CreateError stores the created error object to *rval and returns true,
otherwise returns false and the value of *rval is undefined. See Also MXR ID Search for JS::CreateError JSExnType JSErrorReport bug 984048 bug 1038238 -- change stack parameter from JS::HandleString to JS::HandleObject ...
JS::Evaluate
as for the standard eval function. In the common case where the script is just an expression, the result value is simply the value of that expression. More generally, the result value is the value of the last-executed expression statement in the script that isn't in a function. If a script compiles and executes successfully, JS::Evaluate stores the result in *rval, if non-null, and returns true.
Otherwise it returns false and the value left in *rval is undefined. See Also MXR ID Search for JS::Evaluate JS::Compile JS_ExecuteScript bug 771705 bug 1097987 -- remove obj parameter ...
JS::GetFirstArgumentAsTypeHint
CallArgs The arguments of the function call. behavior JSType * Receives the result of conversion. See below. Description JS::GetFirstArgumentAsTypeHint converts first argument of @@toPrimitive method to JSType. If args.get(0) is one of the strings "string", "number", or "default", set *result to JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_VOID accordingly and return true.
Otherwise, return false with a TypeError pending. See Also MXR ID Search for JS::GetFirstArgumentAsTypeHint bug 1054756 - added ...
JS::GetSelfHostedFunction
hosted JavaScript. id JS::Handle<jsid> A pointer to jsid of the name to assign to the new function. nargs unsigned Number of arguments the function expects. Description JS::GetSelfHostedFunction creates a new JavaScript function implemented in self-hosted JavaScript. On success, JS::GetSelfHostedFunction returns a pointer to the newly created function.
Otherwise, it reports an out-of-memory error and returns NULL. See Also MXR ID Search for JS::GetSelfHostedFunction bug 1140573 ...
JS::ToString
Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. Description JS::ToString returns a string representation of a JavaScript value. If v.isString() is true, it calls v.toString().
Otherwise, it converts the value to string. On success, JS::ToString returns a JSString instance. On error or exception, it returns nullptr. See Also MXR ID Search for JS::ToString bug 933834 ...
JSAutoByteString
ng::latin1Chars, and take the ownership of the string. This may fail if str is not linear. char *encodeUtf8(JSContext *cx, JS::HandleString str) Call JS_EncodeStringToUTF8 and take ownership of the returned string, and return the string. void clear() Free the owned string. You should call this before calling encode* methods or initBytes method if a string is already owned,
otherwise the string will never be freed. char *ptr() const Return a pointer to the owned string. This could be NULL if no string is owned. bool operator!() const Return true if no string is owned. size_t length() const Return the length of the owned string. Return 0 if no string is owned. Description JSAutoByteString takes the ownership of string and frees it in...
JSDeletePropertyOp
A JSDeletePropertyOp may be installed on a JSClass to hook property deletes. If a JSDeletePropertyOp does nothing and returns true, then property delete is unaffected. It proceeds as normal. This callback may veto the ongoing property operation by optionally reporting an error or raising an exception and then returning false. The operation then fails, and the error is propagated to the caller.
Otherwise the callback must return true, and the property operation proceeds. JSClass hooks JSClass offers the following hook: JSClass.delProperty is called during most property deletions, even when obj has no property named id. If an error occurred, return false as per normal JSAPI error practice. If no error occurred, but the deletion attempt wasn't allowed (perhaps because the property was...
JSErrorReport
JSErrorReporter might choose to ignore a JSErrorReport that has this flag set, since the exception may be caught and handled by JavaScript code. JSREPORT_STRICT This error is only being reported because the engine is in strict mode. JSREPORT_STRICT_MODE_ERROR This condition is an error in strict mode code, a warning if JS_HAS_STRICT_OPTION(cx), and
otherwise should not be reported at all. We check the strictness of the context's top frame's script; where that isn't appropriate, the caller should do the right checks itself instead of using this flag. The constant JSREPORT_ERROR is 0 and can be used to indicate an error report without any of the above flags. errorNumber unsigned The error number. ucmessage const ...
JSExtendedClass
any of the JSExtendedClass callbacks: Create a JSExtendedClass and populate both the base fields and the extended fields. Ensure that the additional reserved fields at the end of the JSExtendedClass are NULL. JSClass and JSExtendedClass structs should usually be global, and in this case the compiler automatically initializes these fields to NULL. (This is a feature of the C and C++ languages.)
Otherwise, use memset. Set the JSCLASS_IS_EXTENDED flag in myExtendedClass.base.flags. Pass &myExtendedClass.base to functions like JS_InitClass or JS_NewObject that require a JSClass *. See Also bug 571789 ...
JSHasInstanceOp
e type check. v JS::MutableHandleValue The value whose type is being checked. bp bool * Out parameter. On success, the callback stores the result of the type check in *bp. Description JSHasInstanceOp is called to check whether v is an instance of obj. Return false on error or exception, true on success with true in *bp if v is an instance of obj, false in *bp
otherwise. JSClass hooks JSClass offers the following hook: The JSClass.hasInstance callback implements JS_HasInstance and the JavaScript instanceof keyword. See Also MXR ID Search for JSHasInstanceOp JSClass JS_HasInstance ...
JSNative
using a JS::CallArgs structure Added in SpiderMonkey 17. (This structure is now provided in "js/CallArgs.h" Added in SpiderMonkey 24 as well as through "jsapi.h".) This structure encapsulates access to the callee function, this, the function call's arguments, and the eventual return value. On success, the callback must set JS::CallArgs::rval() or call JS_SET_RVAL (at least once) and return true.
Otherwise it should either report an error (using e.g. JS_ReportError or JS_ReportOutOfMemory) or raise an exception (using JS_SetPendingException), and the callback must return false. (Returning false without reporting an error or raising an exception terminates the script with an uncatchable error. This has limited use cases; it's used to implement Firefox's "slow script" dialog, for example.) When a J...
JSObjectOps.dropProperty
property to release. That is, the value that JSObjectOps.lookupProperty hook stored in the *propp out parameter. Description The following contract governs JSObjectOps callers and implementations: Whenever JSObjectOps.lookupProperty returns a JSProperty pointer, the property is locked. While the property is locked, the caller may access it using other JSObjectOps callbacks. It may not
otherwise call into the JSAPI in ways that might trigger other property accesses. (In a JS_THREADSAFE build, that would risk deadlock.) When finished with a locked property, the caller must release it by calling the dropProperty callback. The lifetime of the JSProperty * extends from the successful defineProperty or lookupProperty call to the dropProperty call. As a SpiderMonkey implementation detail, ...
JSObjectOps.enumerate
internals documentation, not API documentation. See bug 408416 for details. The JSObjectOps.enumerate callback implements iteration over object properties. The type of the callback is JSNewEnumerateOp. For native objects, the enumerate callback first checks the JSCLASS_NEW_ENUMERATE flag of the object's class. If the flag is present, enumerate simply delegates the call to JSClass.enumerate.
Otherwise, it invokes the JSClass.enumerate hook as an old-style JSEnumerateOp to give the object an opportunity to define any remaining lazy properties. Then it iterates over obj's defined properties, walking the internal data structure they're stored in. ...
JSObjectOps.setProto
obj JSObject * The object whose prototype or parent is being modified. slot uint32 The index of the slot being modified: JSSLOT_PROTO for the JSObjectOps.setProto callback, and JSSLOT_PARENT for the JSObjectOps.setParent callback. pobj JSObject * The new prototype or parent object. Description These hooks must check for cycles without deadlocking, and
otherwise take special steps. See js_SetPrototype or js_SetParent in js/src/jsobj.cpp for an example. ...
JSPrincipalsTranscoder
allback syntax typedef JSBool (*JSPrincipalsTranscoder)(JSXDRState *xdr, JSPrincipals **principalsp); Name Type Description xdr JSXDRState * The XDR reader/writer. principalsp JSPrincipals ** If xdr->mode == JSXDR_DECODE, this is an out parameter: on success, *principalsp receives the deserialized principals.
Otherwise xdr->mode == JSXDR_ENCODE, and *principalsp points to the JSPrincipals object to be serialized. Description The JavaScript engine uses this callback to serialize and deserialize principals. Each script function is associated with principals, which poses a problem for XDR. The application provides the JSPrincipals objects, so it must also provide a JSPrincipalsTranscoder if it intends to ...
JSPropertyOp
bed in more detail in the sections below. If a JSPropertyOp or JSStrictPropertyOp does nothing and returns true, then property get, set, or add is unaffected. It proceeds as normal. Each of these callbacks may veto the ongoing property operation by optionally reporting an error or raising an exception and then returning false. The operation then fails, and the error is propagated to the caller.
Otherwise the callback must return true, and the property operation proceeds. Getters and setters When a JSAPI application creates a property on an object (for example, using JS_DefineProperty or JS_DefineProperties) it can specify getter and setter callbacks for the new property. Getters. The getter callback is called each time JavaScript code accesses the property's value using the syntax obj.prop or ...
JSVAL_IS_PRIMITIVE
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determine if a given jsval is of a primitive type. Syntax JSVAL_IS_PRIMITIVE(v) Description JSVAL_IS_PRIMITIVE(v) is true if v is undefined, null, a boolean, a number, or a string.
Otherwise it is false, and v is an object. See Also bug 952650 ...
JSVAL_LOCK
roots with JS_AddRoot. JSVAL_LOCK locks a JS value, v, to prevent the value from being garbage collected. v is a JS object, string, or double value. JSVAL_LOCK determines if v is an object, string, or double value, and if it is, it locks the value. If locking is successful, or v already cannot be garbage collected because it is not an object, string, or double value, JSVAL_LOCK evaluates to true.
Otherwise, it evaluates to false. See Also JSVAL_IS_GCTHING JSVAL_TO_GCTHING JSVAL_UNLOCK JS_AddRoot JS_LockGCThing bug 787580 ...
JSVAL_TO_BOOLEAN
since it could be removed at any time. Try to avoid using it. Cast a boolean JavaScript value to a C integer, either 0 or 1, without any type checking or error handling. Syntax JSBool JSVAL_TO_BOOLEAN(jsval v); Description JSVAL_TO_BOOLEAN casts the value v to a C integer, either 0 or 1. As a precondition, JSVAL_IS_BOOLEAN(v) must be true. That is, v must be either JSVAL_TRUE or JSVAL_FALSE.
Otherwise the behavior is undefined. The result is JS_TRUE or JS_FALSE respectively. These are constants of type JSBool, which is an integer type, the SpiderMonkey version of bool. JS_FALSE is 0; JS_TRUE is 1. To convert any value to a boolean, use JS_ValueToBoolean instead. That function has well-defined behavior even when the argument is an object, number, or something else. To convert a JSBool to jsval,...
JSVAL_TO_GCTHING
ce JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Cast a jsval to a raw pointer of type void *. Syntax JSVAL_TO_GCTHING(v) Description JSVAL_TO_GCTHING casts a jsval, v, to a raw pointer. The type of the result is void *. v must be either JSVAL_NULL or a reference to a GC thing.
Otherwise the resulting pointer is undefined. JSVAL_IS_GCTHING may be used to check this. This macro is exposed in jsapi.h because other JSAPI macros make use of it. Applications should not call it directly in most cases. When possible, it is better to use a more specific macro, such as JSVAL_TO_OBJECT or JSVAL_TO_STRING. Another possible alternative is to avoid casting altogether by using an API that oper...
JSVAL_UNLOCK
_RemoveRoot. JSVAL_UNLOCK unlocks a previously locked JS value, v, so it can be garbage collected. v is a JS object, string, or double value. JSVAL_UNLOCK determines if v is an object, string, or double value, and if it is, it unlocks the value. If unlocking is successful, or v not affected by garbage collection because it is not an object, string, or double value, JSVAL_UNLOCK evaluates to true.
Otherwise, it evaluates to false. See Also JSVAL_IS_GCTHING JSVAL_TO_GCTHING JSVAL_LOCK JS_AddRoot JS_LockGCThing bug 787580 ...
JS_AddArgumentFormatter
formatter, or whose handler should be removed. formatter JSArgumentFormatter The function to be used to convert arguments described by the given format. This function is described in more detail below. Description JS_AddArgumentFormatter establishes formatter as the conversion function for format strings beginning with format in the context cx. On success, it returns JS_TRUE.
Otherwise it returns JS_FALSE. (At the moment, JS_AddArgumentFormatter fails only if there is no memory available to record the registration.) JS_AddArgumentFormatter does not copy format, it points at the string storage allocated by the caller, which is typically a string constant. If format is in dynamic storage, the caller must keep the string alive until JS_RemoveArgumentFormatter is called. JS_RemoveA...
JS_Add*Root
stant, identifying the source location of the call to JS_AddNamedRoot for debugging purposes. JS_DumpNamedRoots can be used to access this information from a debugger. All the JS_Add*Root methods are idempotent: multiple calls for the same address will add only one root. Correspondingly, only a single JS_RemoveRoot is required to unroot the location. On success, these functions return JS_TRUE.
Otherwise they report an out of memory error and return JS_FALSE. See Also MXR ID Search for JS_AddValueRoot MXR ID Search for JS_AddStringRoot MXR ID Search for JS_AddObjectRoot MXR ID Search for JS_AddNamedValueRoot MXR ID Search for JS_AddNamedStringRoot MXR ID Search for JS_AddNamedObjectRoot bug 912581 ...
JS_BufferIsCompilableUnit
SAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The global object, or NULL. utf8 const char * String containing the script to compile. length size_t The length of utf8 in characters. Description Given a buffer, return false if the buffer might become a valid JavaScript statement with the addition of more lines.
Otherwise return true. The intent is to support interactive compilation - accumulate lines in a buffer until JS_BufferIsCompilableUnit is true, then pass it to the compiler. See Also MXR ID Search for JS_BufferIsCompilableUnit JS::Evaluate JS::Compile JS::CompileOffThread JS::CompileFunction JS_DecompileScript ...
JS_CallFunction
number of arguments defined for the function. Obsolete since JSAPI 30. In argc, indicate the number of arguments passed to the function. In argv, pass a pointer to the actual argument values to use. rval is a pointer to a variable that will hold the function's return value, if any, on successful function execution. If the called function executes successfully, JS_CallFunction returns true.
Otherwise it returns false, and rval is undefined. Calling JS_CallFunction is safe only if the fun argument could be passed to JS_GetFunctionObject safely: that is, it is a function implemented by a JSNative or JSFastNative or the result of a call to JS_CompileFunction, JS_CompileUCFunction, JS_CompileFunctionForPrincipals, or JS_CompileUCFunctionForPrincipals. Passing any other JSFunction pointer can lea...
JS_CheckAccess
permission to place a watchpoint on the property. JSACC_READ Check for permission to get the property's value. JSACC_WRITE When bitwise-ORed with one of the above values, check for permission to write the property, not read it. The access check proceeds as follows. If obj has custom JSObjectOps, the access check is delegated to the JSObjectOps.checkAccess callback.
Otherwise, if obj's class has a non-null JSClass.checkAccess callback, then it is called to perform the check.
Otherwise, if a runtime-wide check-object-access callback has been installed by calling JS_SetCheckObjectAccessCallback, then that is called to perform the check.
Otherwise, access is granted. On success, JS_CheckAccess returns JS_TRUE, *vp is set to the current value of the specified property, a...
JS_ClearRegExpStatics
Type Description cx JSContext * The context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject A pointer to a global object. Description JS_ClearRegExpStatics clears the pending input string and flags of the built-in RegExp object. On successful, JS_ClearRegExpStatics returns true,
otherwise returns false. See Also MXR ID Search for JS_ClearRegExpStatics JS_NewRegExpObject JS_NewUCRegExpObject JS_SetRegExpInput RegExp ...
JS_CompileScript
ompiles a script, source, for execution. JS_CompileUCScript is the Unicode version of the function. The script is associated with a JS object. ascii and chars are the string containing the text of the script. length indicates the size of the text version of the script in characters. On success, JS_CompileScript and JS_CompileUCScript stores the newly compiled script to *script and returns true.
Otherwise, they report an error, stores NULL to *script, and return false. See Also The JSAPI User Guide contains example code using compiled scripts. MXR ID Search for JS_CompileScript MXR ID Search for JS_CompileUCScript JS::Evaluate JS::CompileOffThread JS::CompileFunction JS_ExecuteScript JS_DecompileScript bug 1143793 -- removed obj parameter ...
JS_CompileUTF8File
h the script is associated. filename const char * Name of file containing the script to compile. Description JS_CompileUTF8File compiles the text of script in an external file location for execution by the JS engine. filename is the name of the file containing the script to compile. On success, JS_CompileUTF8File returns an object that represents the newly compiled script.
Otherwise it returns NULL. JS_CompileUTF8File is deprecated, use FILE, use JS::Compile instead. See Also The JSAPI User Guide contains example code using compiled scripts. MXR ID Search for JS_CompileFile JS::Compile JS_DecompileScript JS::Evaluate JS_ExecuteScript bug 805080 ...
JS_ContextIterator
rp is modified so that repeated calls cycle through all the contexts in rt. Description JS_ContextIterator steps through the set of contexts associated with the runtime rt. Each call to JS_ContextIterator returns the next context in the cycle. iterp must point to a variable of type JSContext *. If *iterp is NULL, JS_ContextIterator modifies it to point to the first JSContext in the list.
Otherwise *iterp must point to an existing context in rt, and JS_ContextIterator modifies it to point to the next context in the list, if any, and NULL
otherwise. JS_ContextIterator returns the new value of *iterp. 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...
JS_ConvertArgumentsVA
ore the converted types. There should be one pointer for each converted value. The type va_list is a standard feature of the C programming language. It is defined in <stdarg.h>. Description JS_ConvertArgumentsVA is to JS_ConvertArguments as vprintf is to printf. See JS_ConvertArguments for further information. If JS_ConvertArgumentsVA successfully converts all arguments, it returns true.
Otherwise it returns false. See Also MXR ID Search for JS_ConvertArgumentsVA JS_ConvertArguments bug 969798 - added args bug 1125784 ...
JS_DecompileFunction
. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. fun JS::Handle<JSFunction*> Function to decompile. Description JS_DecompileFunction generates the complete source code of a function declaration from a function's compiled form, fun. If successful, JS_DecompileFunction returns a string containing the text of the function.
Otherwise, it returns NULL. If you decompile a function that does not make a native C call, then the text created by JS_DecompileFunction is a complete function declaration suitable for re-parsing. If you decompile a function that makes a native C call, the body of the function contains the text "native code'" and cannot be re-parsed. See Also MXR ID Search for JS_DecompileFunction JS_DecompileScript...
JS_DecompileFunctionBody
If it's not JS_DONT_PRETTY_PRINT, JS_DecompileFunction returns pretty printed source code of the function. Description JS_DecompileFunctionBody generates the source code of a function's body, minus the function keyword, name, parameters, and braces, from a function's compiled form, fun. If successful, JS_DecompileFunctionBody returns a string containing the source code of the function body.
Otherwise, it returns NULL. The source code generated by this function is accurate but unadorned and is not suitable for recompilation without providing the function's declaration. If you decompile a function that makes a native C call, the body of the function only contains the text "[native code]". Notes To decompile a complete function, including its body and declaration, call JS_DecompileFunction inste...
JS_DecompileScript
Type Description cx JSContext * The context to use to decompile the script. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. script JS::Handle<JSScript*> Script or function to decompile. Description JS_DecompileScript returns the source code of script. If script is a function, it calls JS_DecompileFunction.
Otherwise, it returns the original source code of the script. If the script is not cached, it tries to load the source from file, and returns nullptr if an error happened while loading. If successful, JS_DecompileScript returns a string containing the source code of the script.
Otherwise, it returns a string containing "[no source]". From SpiderMonkey 17, this does not actually decompile the script, but...
JS_DefineConstDoubles
y element defines a single property name and property value to create. The name field of the last element of the array must contain 0. JS_DefineConstDoubles/JS_DefineConstIntegers create one property for each element in the array what contains a non-zero name field. On success, JS_DefineConstDoubles/JS_DefineConstIntegers returns true, indicating it has created all properties listed in the array.
Otherwise it returns false. See Also MXR ID Search for JS_DefineConstDoubles MXR ID Search for JS_DefineConstIntegers JSConstDoubleSpec JSConstIntegerSpec JS_DefineElement JS_DefineProperties JS_DefineProperty JS_DefinePropertyWithTinyId bug 1066020 - added JS_DefineConstIntegers ...
JS_DefineElement
the property's initial value. getter and setter identify the getProperty and setProperty methods for the property, respectively. If you pass NULL values for these entries, JS_DefineElement assigns the default getProperty and setProperty methods to this element. Obsolete since JSAPI 32 flags contains the property attributes to set for the new property. On success, JS_DefineElement returns true.
Otherwise it returns false. Obsolete since JSAPI 32. While you can assign a setProperty method to a property and set flags to JSPROP_READONLY, the setter method will not be called on this property. See Also MXR ID Search for JS_DefineElement JS_DefineConstDoubles JS_DefineFunction JS_DefineFunctions JS_DefineObject JS_DefineProperties JS_DefineProperty JS_DefinePropertyWithTinyId JS_DeleteElement JS...
JS_DefineProperties
field of the last array element must be NULL. JS_DefineProperties creates one property for each element in the array before the element with a null name field. Each property is defined as though by calling JS_DefineProperties. The initial stored value of each property created is undefined. On success, JS_DefineProperties returns true, indicating it has created all properties listed in the array.
Otherwise it returns false. See Also MXR ID Search for JS_DefineProperties JS_DefineConstDoubles JS_DefineElement JS_DefineFunction JS_DefineFunctions JS_DefineObject JS_DefineProperty JS_InitClass bug 855582 ...
JS_DeleteElement
tOpResult & (out parameter) Receives the result of the operation. Description JS_DeleteElement removes a specified element or numeric property, index, from an object, obj. If an object references an element belonging to a prototype, the element reference is removed from the object, but the prototype's element is not deleted. If deletion is successful, JS_DeleteElement returns true.
Otherwise it returns false. For JavaScript 1.2 and earlier, if failure occurs because you attempt to delete a permanent or read-only element, JS_DeleteElement reports the error before returning false. For JavaScript 1.3 and later, the attempt is silently ignored. To truncate an array, use JS_SetArrayLength. To remove all elements and properties from an object, call JS_ClearScope. See Also MXR ID Sear...
JS_DeleteElement2
ormation. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject Object from which to delete an element. index uint32_t Index number of the element to delete. succeeded bool * Out parameter. On success, *succeeded receives false if the property was not deleted because it is permanent and true
otherwise. Description JS_DeleteElement2 removes a specified element or numeric property, index, from an object, obj. If an object references an element belonging to a prototype, the element reference is removed from the object, but the prototype's element is not deleted. If deletion is successful, JS_DeleteElement2 stores true to *succeeded and returns true.
Otherwise it returns false and the valu...
JS_DeleteProperty
y lookup is performed. Then one of the following cases applies: If obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then obj's JSClass.delProperty hook is called. No property is deleted, but this is not an error. If obj has the specified property but it is permanent, nothing happens. No property is deleted, but this is not an error.
Otherwise obj has a non-permanent own property with the given name or id. In this case, obj's JSClass.delProperty hook is called. If the hook returns false, the error is propagated.
Otherwise, if obj is not configurable, an error is raised.
Otherwise, the property is removed. These functions return true on success, regardless of whether a property was actually deleted, and false on error or exception. (...
JS_EncodeString
JS_THREADSAFE build, the caller must be in a request on this JSContext.. str JSString * / JS::HandleString A string to encode. Description JS_EncodeString and JS_EncodeStringToUTF8 convert the specified JavaScript str to a C string (an array of 8-bit chars). If JS_CStringsAreUTF8 is true, then the returned string of JS_EncodeString is UTF-8, and the conversion is lossless.
Otherwise the high byte is simply dropped from each char16_t. JS_EncodeStringToUTF8 encode the string to UTF-8. The array returned by JS_EncodeString on success is allocated as though by a call to JS_malloc. The caller may modify it and is responsible for freeing it. Note that for non-ASCII strings, if JS_CStringsAreUTF8 is false, these functions can return a corrupted copy of the contents of the string...
JS_EnterCrossCompartmentCall
entifies the compartment to be entered. Description Every JSContext has a current compartment. Any access to an object in a different compartment must be bracketed by calling JS_EnterCrossCompartmentCall and JS_LeaveCrossCompartmentCall. On success, JS_EnterCrossCompartmentCall returns a pointer to a JSCrossCompartmentCall object that must be passed to JS_LeaveCrossCompartmentCall.
Otherwise it returns NULL. See Also JS_LeaveCrossCompartmentCall JS_EnterCompartment JS_LeaveCompartment bug 786068 bug 563099 ...
JS_ErrorFromException
to a JS context whose errors should be reported via your function. Other contexts in the same runtime can have their own error reporting functions. obj JS::HandleObject An exception object. Description If obj is an exception object, the exception will have (or be able to lazily create) an error report struct, and JS_ErrorFromException will return the address of that struct.
Otherwise, it returns nullptr. The lifetime of the error report struct that might be returned is the same as the lifetime of the exception object. See Also MXR ID Search for JS_ErrorFromException JSErrorReport ...
JS_EvaluateScript
on. In the common case where the script is just an expression, the result value is simply the value of that expression. More generally, the result value is the value of the last-executed expression statement in the script that isn't in a function. If a script compiles and executes successfully, JS_EvaluateScript or JS_EvaluateUCScript stores the result in *rval, if non-null, and returns JS_TRUE.
Otherwise it returns JS_FALSE and the value left in *rval is undefined. See Also MXR ID Search for JS_EvaluateScript MXR ID Search for JS_EvaluateUCScript JS_CompileFile JS_CompileScript JS_DecompileScript JS_DestroyScript JS_EvaluateScriptForPrincipals bug 1100579 ...
JS_EvaluateScriptForPrincipals
messages if an error occurs during compilation. Similarly, lineno is used to report the line number of the script or file where an error occurred during compilation. If the script compiles and executes successfully, *rval receives the value from the last-executed expression statement processed in the script, and JS_EvaluateScriptForPrincipals or JS_EvaluateUCScriptForPrincipals returns JS_TRUE.
Otherwise it returns JS_FALSE, and the value left in *rval is undefined. See Also JS::Evaluate JS_CompileFile JS_CompileScriptForPrincipals JS_EvaluateScript bug 980180 ...
JS_ExecuteScriptPart
e script. Description JS_ExecuteScriptPart executes part of a previously compiled script, script. The part parameter must be either JSEXEC_PROLOG to execute the script prolog or JSEXEC_MAIN to execute the main section of the script. If the script executes successfully, JS_ExecuteScriptPart stores the value of the last-executed expression statement in the script in *rval and returns JS_TRUE.
Otherwise it returns JS_FALSE, and the value left in *rval is undefined. To execute both parts of a script, use JS_ExecuteScript instead. See Also MXR ID Search for JS_ExecuteScriptPart JS_ExecuteScript bug 555104 ...
JS_FileEscapedString
te into. str JSString * A string to write into the file. quote char One of 0, single quote, and double quote. Description JS_FileEscapedString writes str into file fp escaping any non-printable or non-ASCII character. If quote is not 0, it must be a single or double quote character that will quote the output. If successful, JS_FileEscapedString returns true,
otherwise false. See Also MXR ID Search for JS_FileEscapedString bug 609440 ...
JS_GetClassObject
in a request on this JSContext. key JSProtoKey The key of the prototype. objp JS::MutableHandle<JSObject*> Out parameter. If successful, receive the class constructor. Description JS_GetClassObject gets the builtin class costructor for the specified prototype key. If successful, JS_GetClassObject stores the class constructor to *objp and returns true,
otherwise returns false and the value of *objp is undefined. See Also MXR ID Search for JS_GetClassObject JS_GetClassPrototype JSProtoKey ...
JS_GetClassPrototype
this JSContext. key JSProtoKey The key of the prototype. objp JS::MutableHandle<JSObject*> Out parameter. If successful, receive the class prototype object. Description JS_GetClassPrototype gets the builtin class costructor for the specified prototype key. If successful, JS_GetClassPrototype stores the class prototype object to *objp and returns true,
otherwise returns false and the value of *objp is undefined. See Also MXR ID Search for JS_GetClassPrototype JS_GetClassObject JSProtoKey ...
JS_GetConstructor
JSContext * A context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::Handle<JSObject*> The object whose constructor is to be returned. Description JS_GetConstructor retrieves the constructor property of a given object, obj. If the result is a Function object, JS_GetConstructor returns a pointer to that object.
Otherwise, it reports an error and returns NULL. To get an object's prototype, use JS_GetPrototype. To get an object's parent, use JS_GetParent. See Also MXR ID Search for JS_GetConstructor ...
JS_GetElement
orm the property lookup. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The object to search for the element. index uint32_t Index of the element to look up. vp JS::MutableHandleValue Out parameter. On success, *vp receives the current value of the element, if it exists, and undefined
otherwise. Description JS_GetElement examines a specified JS object, obj, and its prototype chain, for an element or numeric property numbered index. If the element exists, JS_GetElement sets *vp to the element's current value. If not, it sets *vp to undefined and returns true (to indicate no error occurred). If the search fails with an error or exception, JS_GetElement returns false, and the value l...
JS_GetFunctionArity
Description fun JSFunction * A JavaScript function. Description JS_GetFunctionArity returns the number of formal parameters of a function, fun. This is the same as the function object's arity property, if that property has not been overwritten. Specifically, if fun is a native function, the result is the value that was passed to the nargs parameter of JS_DefineFunction.
Otherwise fun is implemented in JavaScript, and the result is the number of identifiers in its formal parameter list (see ECMA 262-3 ?13). Note that it is not an error per se to call a JavaScript function with more or fewer actual arguments than its arity. See Also MXR ID Search for JS_GetFunctionArity JS_DefineFunction ...
JS_GetInstancePrivate
an argv pointer created by the JavaScript engine and passed to a JSNative callback; JS_ARGV(cx, vp) where vp is a pointer created by the engine and passed to a JSFastNative callback; or NULL. Description JS_GetInstancePrivate determines if a JavaScript object, obj, is an instance of a given JSClass, clasp, and if it is, returns a pointer to the object's private data.
Otherwise it returns NULL. Note that if obj is an instance of clasp, but there is no private data currently associated with the object, or the object cannot have private data, JS_GetInstancePrivate also returns NULL. If you pass a non-null argument vector, argv, to JS_GetInstancePrivate, and obj is not an instance of clasp, this function reports a class mismatch error before returning NULL. In this case, J...
JS_GetLatin1InternedStringChars
ntext.. nogc JS::AutoCheckCannotGC & A reference to JS::AutoCheckCannotGC. str JSString * A string to get characters. Description JS_GetLatin1InternedStringChars and JS_GetTwoByteInternedStringChars gets the characters of the string, str. If successful, JS_GetLatin1StringCharsAndLength and JS_GetTwoByteStringCharsAndLength return a pointer to the string,
otherwise return NULL. See Also MXR ID Search for JS_GetLatin1InternedStringChars MXR ID Search for JS_GetTwoByteInternedStringChars JS_GetLatin1FlatStringChars JS_GetTwoByteFlatStringChars JS_GetLatin1StringCharsAndLength JS_GetTwoByteStringCharsAndLength bug 1037869 ...
JS_GetLatin1StringCharsAndLength
ng to get characters. length size_t * Out parameter. Receives the length of the string. Description JS_GetLatin1StringCharsAndLength and JS_GetTwoByteStringCharsAndLength get the characters and the length of the string, str. If successful, JS_GetLatin1StringCharsAndLength and JS_GetTwoByteStringCharsAndLength return a pointer to the string, and store the length to *length,
otherwise return NULL. See Also MXR ID Search for JS_GetLatin1StringCharsAndLength MXR ID Search for JS_GetTwoByteStringCharsAndLength JS_GetLatin1FlatStringChars JS_GetTwoByteFlatStringChars JS_GetLatin1InternedStringChars JS_GetTwoByteInternedStringChars bug 1032726 ...
JS_GetPendingException
own. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. vp JS::MutableHandleValue Out parameter. On success, *vp receives the current pending exception. Description If an exception has been thrown in the context cx, and it has not yet been caught or cleared, JS_GetPendingException stores the exception object in *vp and returns true.
Otherwise, it returns false, and the value left in *vp is undefined. See examples in the JSAPI Phrasebook. See Also MXR ID Search for JS_GetPendingException JS_IsExceptionPending JS_ClearPendingException JS_ReportPendingException JS_SetPendingException ...
JS_GetProperty
k of obj's class is called with the arguments (cx, obj, id, vp). For many objects, including objects of standard classes such as Object and Array, this hook does nothing and returns true, so the property get succeeds and undefined is left in *vp. If the property is found on a non-native object, get handler of Proxy (only if the object is a Proxy) or its JSObjectOps.getProperty method is called.
Otherwise the property is found on a native object. If the property has a JavaScript getter, it is called.
Otherwise *vp is set to the property's stored value, or undefined if the property does not have a stored value, and then the property's getter is called with the arguments (cx, obj, id, vp). For many properties, the getter does nothing and returns true, so the property get succeeds and the property's ...
JS_GetPrototype
Object Out parameter. If successful, Receives prototype object of obj. Description JS_GetPrototype retrieves the prototype of a specified object, obj. A prototype object provides properties inherited by similar JS objects. This is the equivalent of Object.getPrototypeOf(obj) from javascript. If JS_GetPrototype returns false, that signals an exception, which should be handled as usual.
Otherwise, it stores a pointer to the prototype or null to *protop and returns true. To set an object's prototype, use JS_SetPrototype. See Also MXR ID Search for JS_GetPrototype JS_SetPrototype ...
JS_GetRegExpFlags
y 17 Get the flags of the given RegExp object. Syntax unsigned JS_GetRegExpFlags(JSContext *cx, HandleObject obj) Name Type Description cx JSContext * A context. obj JS::HandleObject The object to get the flags. Description JS_GetRegExpFlags returns flags of the specified object, obj. If successful, JS_GetRegExpFlags returns the flags,
otherwise returns false. See Also MXR ID Search for JS_GetRegExpFlags JS_NewRegExpObject JS_NewUCRegExpObject flags RegExp bug 655641 ...
JS_GetRegExpSource
See Also MXR ID Search for JS_GetRegExpSource JS_NewRegExpObject JS_NewUCRegExpObject RegExp bug 655641 ...
JS_GetScopeChain
in the current scope chain. If the context is currently executing a script, and not in any function, it's running in a scope that was passed to JS_ExecuteScript or a similar function by the application. This scope chain may or may not contain cx's current global object. If any code is currently executing in cx, JS_GetScopeChain returns a pointer to the first JSObject on the current scope chain.
Otherwise, if cx has a global object, JS_GetScopeChain returns that.
Otherwise, an error is reported and JS_GetScopeChain returns NULL. To walk the scope chain, use JS_GetParent. See Also MXR ID Search for JS_GetScopeChain JS_GetGlobalForScopeChain bug 632064 ...
JS_GetStringBytes
ription cx JSContext * (JS_GetStringBytesZ and JS_EncodeString only) A context. str JSString * String to retrieve bytes from. Description JS_GetStringBytes and JS_GetStringBytesZ convert the specified JavaScript string, str, to a C string (an array of 8-bit chars). If JS_CStringsAreUTF8 is true, then the returned string is UTF-8, and the conversion is lossless.
Otherwise the high byte is simply dropped from each jschar. On success, the return value is a pointer to the char array, which is null-terminated. On failure, JS_GetStringBytes returns a pointer to a null-terminated empty string; JS_GetStringBytesZ returns NULL. Note: JS_GetStringBytes() and JS_GetStringBytesZ() have both been removed as of JavaScript 1.8.5 (Firefox 4). Instead, you should use JS_EncodeS...
JS_GetStringCharAt
ndex size_t An integer between 0 and 1-less-than the length of the string. res char16_t * (JS_GetStringCharAt only) Out parameter. On successful, receives the character code. Description JS_GetStringCharAt and JS_GetFlatStringCharAt get the specified character from the string str. On successful, JS_GetStringCharAt returns true and stores the character code into *res,
otherwise returns false. JS_GetFlatStringCharAt always succeeds, and returns the character code. index should not be greater than or equal to the length of str. See Also MXR ID Search for JS_GetStringCharAt MXR ID Search for JS_GetFlatStringCharAt bug 1034627 ...
JS_HasElement
cx JSContext * The context in which to perform the property lookup. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The object to search for the element. index uint32_t Index of the element to look up. foundp bool * Out parameter. On success, it stores true to *foundp, false
otherwise. Description JS_HasElement examines a specified JS object, obj, and its prototype chain, for an element or numeric property numbered index. If the element exists, JS_HasElement sets *foundp to true. If not, it sets *foundp to false and returns true (to indicate no error occurred). If the search fails with an error or exception, JS_HasElement returns false, and the value left in *foundp i...
JS_HasInstance
a specified JS value, v, is an instance of JS object, obj. This function is equivalent to v instanceof obj test in JavaScript. On success, JS_HasInstance stores the result of the instanceof test in *bp and returns true. On error or exception, it returns false, and the value left in *bp is undefined. When providing a prototype as obj, the prototype's JSClass must have its hasInstance method set.
Otherwise JS_HasInstance returns false. See Also MXR ID Search for JS_HasInstance JS_InstanceOf ...
JS_IdToProtoKey
ion cx JSContext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. id JS::HandleId The property identifier to convert. Description JS_IdToProtoKey converts a specified JS ID, id, to a prototype key. On success, JS_IdToProtoKey returns a JSProtoKey.
Otherwise it returns JSProto_Null. See Also MXR ID Search for JS_IdToProtoKey JS::ProtoKeyToId bug 933681 ...
JS_IdToValue
_THREADSAFE build, the caller must be in a request on this JSContext. id jsid The property identifier to convert. vp JS::MutableHandle<JS::Value> Out parameter. On success, *vp receives the converted value. Description JS_IdToValue converts a specified JS ID, id, to a JS value. On success, JS_IdToValue stores the converted value in *vp and returns true.
Otherwise it returns false. The inverse of JS_IdToValue is JS_ValueToId. See Also MXR ID Search for JS_IdToValue JS_ValueToId ...
JS_InstanceOf
rror if obj is not of type clasp. argv must be the argv argument passed from the engine to a JSNative callback, JS_ARGV(cx, rv) in a JSFastNative callback, or NULL. Obsolete since JSAPI 32 Description JS_InstanceOf can be used to check whether an object obj is of a particular JSClass. To use it this way, pass NULL for argv. JS_InstanceOf returns true if obj is of the given class and false
otherwise. That is, it returns JS_GetClass(obj) == clasp. JS_InstanceOf can also be used in native functions to check the class of an argument when a particular class is required. To use it this way, pass the arguments provided by the engine for args with JS::CallArgsFromVp(argc, vp). When args is non-null, JS_InstanceOf behaves as follows. If obj is of the given class, it returns true.
Otherwise, it retu...
JS_InternString
he length of s in characters. Description JS_InternString and JS_InternStringN return an interned JavaScript string with a specified value, s. JS_InternUCString and JS_InternUCStringN are the Unicode versions of the function. Each JSRuntime keeps a table of all existing interned strings. If an interned string already exists with the desired value, these functions return the existing string.
Otherwise a new string is created and added to the table. Strings created with these functions are protected from garbage collection for the lifetime of the JSRuntime. On success, these functions return a pointer to the interned string.
Otherwise they report an error and return NULL. See Also MXR ID Search for JS_InternString MXR ID Search for JS_InternStringN MXR ID Search for JS_InternUCString MXR ID Se...
JS_IsArrayObject
value JS::HandleValue The value to examine. obj JS::HandleObject The object to examine. isArray bool Whether the value/object is an array. Description JS_IsArrayObject determines if a specified object, obj or value, is an Array object. On success, returns true and sets isArray indicating whether obj is an Array object or a wrapper around one.
Otherwise returns false on failure. See Also MXR ID Search for JS_IsArrayObject bug 959787 - added value bug 1179003 - added isArray ...
JS_IsConstructing
called from the engine. cx and vp must be the arguments that the engine passed to that JSNative. JS_IsConstructing returns JS_TRUE if the native was defined with JSFUN_CONSTRUCTOR (JS_InitClass automatically sets that flag when defining a constructor) and it was called as a constructor, either from JavaScript, using the new keyword, or from C/C++ using a JSAPI function such as JS_ConstructObject.
Otherwise it returns JS_FALSE. Ordinary non-constructor JSNatives have no need to call this; it always returns JS_FALSE for such functions. Many constructors do not need to call it either. In the common case where a constructor should have the same behavior (creating a new object) whether it is called with the new keyword or not, it does not need to call JS_IsConstructing. MXR ID Search for JS_IsConstruc...
JS_IsConstructor
covers features introduced in SpiderMonkey 24 Return whether the given function is a valid constructor. Syntax bool JS_IsConstructor(JSFunction *fun); Name Type Description fun JSFunction * The function to examine. Description JS_IsConstructor determines if a specified function, fun is a valid constructor object. If so, JS_IsConstructor returns true.
Otherwise it returns false. See Also MXR ID Search for JS_IsConstructor JS::IsConstructor bug 807228 ...
JS_IsExceptionPending
Determine whether an exception is pending in the JS engine. Syntax bool JS_IsExceptionPending(JSContext *cx); Name Type Description cx JSContext * Pointer to a JS context to check for pending exceptions. Description JS_IsExceptionPending returns true if an exception has been thrown in the context cx and the exception has not yet been caught or cleared.
Otherwise, it returns false This can be used from JSNative functions which call JS code to determine if the called JS code threw an exception or not. Example /* JSAPI */ bool pending; JS::RootedValue exception(cx); /* If an exception is pending, save and clear it. */ pending = JS_IsExceptionPending(cx); if (pending) { if (!JS_GetPendingException(cx, &exception)) return false; JS_ClearPendingEx...
JS_IsExtensible
ntax bool JS_IsExtensible(JSContext *cx, JS::HandleObject obj, bool *extensible); Name Type Description cx JSContext * The context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The object to examine. extensible bool * Out parameter. Receives true if extensible, false
otherwise. Description JS_IsExtensible queries [[Extensible]] property of the specified object, obj. If successful, JS_IsExtensible stores [[Extensible]] property to *extensible and returns true,
otherwise returns false and the value of *extensible is undefined. See also MXR ID Search for JS_PreventExtensions JS_PreventExtensions bug 492845 ...
JS_IsGlobalObject
See also MXR ID Search for JS_IsGlobalObject JS_NewGlobalObject bug 797821 ...
JS_IsIdentifier
_t * The pointer of the string to test. length size_t The length of chars. isIdentifier bool * Out parameter. On success, *isIdentifier receives whether str is an identifier or not. Description JS_IsIdentifier tests if the given string is a valid ECMAScript identifier. On successful, JS_IsIdentifier stores the test result to *isIdentifier and returns true,
otherwise returns false and the value of *isIdentifier is undefined. JS_IsIdentifier which takes chars and length is infallible, so just returns whether the chars are an identifier. See Also MXR ID Search for JS_IsIdentifier JS_ValueToId bug 692627 bug 990484 ...
JS_IsStopIteration
oduced in SpiderMonkey 31 Determine whether the value is a StopIteration exception or not. Syntax // Added in SpiderMonkey 42 bool JS_IsStopIteration(JS::Value v); // Obsolete since SpiderMonkey 42 bool JS_IsStopIteration(jsval v); Name Type Description v JS::Value The value to check. Description JS_IsStopIteration returns true if v is StopIteration,
otherwise false. See Also MXR ID Search for JS_IsStopIteration JS_ThrowStopIteration bug 918170 bug 1184564 -- Changed jsval to JS::Value ...
JS_LeaveLocalRootScopeWithResult
equest. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. rval jsval The result value that should remain protected from garbage collection. Description See JS_EnterLocalRootScope for an explanation of local root scopes. The protection this function affords to rval is tenuous. If there is an enclosing local root scope, then rval is transferred to it.
Otherwise, the value is stored in an internal per-JSContext slot. This slot is rooted, but the value will eventually be overwritten by some other operation, and it is very difficult to figure out exactly when this will happen--or more to the point, guarantee that it won't happen in the time it takes some specific chunk of code to run. In any case, all other newborn values protected by the local root scope,...
JS_LookupProperty
ly different rules depending on the syntactic context in which the property name appears. (The JavaScript engine simply passes these flags through to the object when it calls the object's JSClass.resolve callback, so objects of a custom JSClass may interpret these flags however they like.) If flags is 0, JS_LookupPropertyWithFlags uses the default lookup rules, the ones used by JS_LookupProperty.
Otherwise, flags must be the logical OR of one or more of the following bits: JSRESOLVE_QUALIFIED Behave as though the property name appeared to the right of a dot, as in alert(obj.name). JSRESOLVE_ASSIGNING Behave as though the property name appeared on the left-hand side of an assignment. JSRESOLVE_DETECTING Behave as though the name appeared in an idiom like "if (obj.name) ..." ...
JS_LooselyEqual
ext. v1, v2 JS::Handle<JS::Value> The value to compare. equal bool * Out parameter. Receives the comparison result. Description JS_LooselyEqual determines if v1 is loosely equal to v2 under the JavaScript == operator, as specified in ECMA 262-3 ?11.9.3. If the comparison attempt was successful, the method returns JS_TRUE and stores the result in *equal;
otherwise it returns JS_FALSE. Comparing jsvals directly in C++, as in v1 == v2, does not produce a meaningful result, since it is possible for two distinct JSStrings or jsdoubles to represent the same string or number. See Also MXR ID Search for JS_LooselyEqual JS_StrictlyEqual JS_SameValue ...
JS_NewArrayObject
ments. JS_NewArrayObject defines an enumerable array element with the value contents[i] on the new array. JS_NewArrayObject with length parameter creates a new array object with the specified length; the result is like the JavaScript expression new Array(length). The new array has the specified length, but it doesn't have any elements. On success, JS_NewArrayObject returns the new array object.
Otherwise it reports an error as though by calling JS_ReportOutOfMemory and returns NULL. Obsolete since JSAPI 30. JS_NewArrayObject with length parameter creates a new array object with the specified length. If vector is non-null, then for each index i from 0 to length - 1, JS_NewArrayObject defines an enumerable array element with the value vector[i] on the new array. (This means that if length is non...
JS_NewCompartmentAndGlobalObject
this is to make JSClasses global or static. principals JSPrincipals * The security information to associate with this compartment. Description JS_NewCompartmentAndGlobalObject creates a new compartment, and then creates a new global object as the first object in that compartment. On success, JS_NewCompartmentAndGlobalObject returns a pointer to the new global object.
Otherwise it returns NULL. See Also JS_NewGlobalObject bug 755186 bug 563099 ...
JS_NewContext
mong the contexts in a JSRuntime, but they cannot be shared across JSRuntimes. stackchunksize size_t The size, in bytes, of each "stack chunk". This is a memory management tuning parameter which most users should not adjust. 8192 is a good default value. Description JS_NewContext creates a new JSContext in the runtime rt. On success, it returns a pointer to the new context.
Otherwise it returns NULL. For more details about contexts, see JSContext. For sample code that creates and initializes a JSContext, see JSAPI User Guide. The stackchunksize parameter does not control the JavaScript stack size. (The JSAPI does not provide a way to adjust the stack depth limit.) Passing a large number for stackchunksize is a mistake. In a DEBUG build, large chunk sizes can degrade performa...
JS_NewDouble
nstead. Warning: The argument d must not be a value that could fit in an integer jsval. If it is, JS_NewDouble creates a bad jsdouble that might behave as desired in some cases but not others. The new jsdouble is subject to garbage collection until you protect it using a local root, an object property, or the JS_AddRoot function. On success, JS_NewDouble returns a pointer to the new number.
Otherwise it returns NULL. The application must treat the returned pointer as read-only. Modifying a jsdouble allocated with this function can cause undefined behavior. See Also JS_NumberValue bug 549143 ...
JS_NewDoubleValue
it is, JS_NewDoubleValue creates a bad jsval that might behave as desired in some cases but not others. The result is subject to garbage collection until you protect against it using a local root, an object property, or the JS_AddRoot function. This can be avoided by using the address of a rooted variable as rval. On success, JS_NewDoubleValue stores a numeric jsval in *rval and returns JS_TRUE.
Otherwise it returns JS_FALSE and the value left in *rval is unspecified. See Also JS_NumberValue bug 549143 ...
JS_NewObjectForConstructor
ty, this function will return NULL and set an exception on cx. The standard object creation API, JS_NewObject, takes explicit arguments for the class, prototype, and parent of the new object. With JS_NewObjectForConstructor, the prototype and parent are determined by the constructor, and class is still determined by the caller. The prototype is the prototype of the constructor if it is an object,
otherwise NULL. The parent is the constructor's parent. See Also MXR ID Search for JS_NewObjectForConstructor JS_NewObject OBJECT_TO_JSVAL bug 581263 - added bug 738075 - added clasp parameter bug 959787 - added args parameter ...
JS_NewPlainObject
Name Type Description cx JSContext * The context in which to create the new object. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. Description JS_NewPlainObject creates a new plain object, like new Object(), with Object.prototype as [[Prototype]]. On success, JS_NewPlainObject returns a pointer to the new object.
Otherwise it returns nullptr. See Also MXR ID Search for JS_NewPlainObject JS_NewObject bug 1125356 ...
JS_NewRuntime
(the self-hosting and initial atoms compartments). It is recommended to make use of this for every runtime in a process after the first one. The returned JSRuntime can be used from the calling thread only. (The engine may use helper threads internally, though.) On success, JS_NewRuntime returns a pointer to the newly created runtime, which the caller must later destroy using JS_DestroyRuntime.
Otherwise it returns NULL. Notes Ordinarily, JS_NewRuntime should be the first JSAPI call in an application, and JS_DestroyRuntime and JS_ShutDown should be the last ones. See Also MXR ID Search for JS_NewRuntime JS_Init JS_DestroyRuntime JS_ShutDown bug 714050 - added useHelperThreads parameter bug 964059 - added parentRuntime parameter bug 941805 - removed useHelperThreads parameter bug 1034...
JS_NewScriptObject
script, you should immediately ensure that its script object is reachable (perhaps by using JS_AddRoot or JS_EnterLocalRootScope). A script object has no properties, and its prototype is Object.prototype. So a script object can be used to expose a JSScript to JavaScript code, but the code can't do much of anything with it. On success, JS_NewScriptObject returns a pointer to the script's object.
Otherwise it returns NULL. (The name "JS_NewScriptObject" suggests that the script object is freshly allocated; this was the case in older versions of the API, but now the script object is allocated along with the JSScript itself.) (Some temporary scripts used internally by SpiderMonkey do not have script objects allocated for them; such scripts are not accessible via JSAPI.) See Also The JSAPI User ...
JS_NewStringCopyN
ters, the new string contains a truncated version of the original string. The string may contain null characters ('\0'). They are copied into the new string like any other character. You can use JS_NewStringCopyN to copy binary data or to copy only a certain portion of a C string into a JavaScript string. On success, JS_NewStringCopyN and JS_NewUCStringCopyN return a pointer to the new JS string.
Otherwise they return NULL. See Also MXR ID Search for JS_NewStringCopyN MXR ID Search for JS_NewUCStringCopyN JS_GetEmptyStringValue JS_NewStringCopyZ JS_NewUCStringCopyZ JS_ValueToString ...
JS_NumberValue
See Also MXR ID Search for JS_NumberValue bug 752223 bug 1184564 -- Changed jsval to JS::Value ...
JS_ObjectIsFunction
is must not be NULL. Description JS_ObjectIsFunction tests whether obj is a function object (faster than comparing obj's class name to Function, but equivalent unless someone has overwritten the Function identifier with a different constructor and then created instances using that constructor that might be passed in as obj). JS_ObjectIsFunction returns true if obj is a Function and false
otherwise. If JS_ObjectIsFunction returns true, JS_ValueToFunction will always return non-null. JS_ObjectIsFunction always succeeds. Note that the result may be false even for some callable objects, such as regular expression objects or proxy objects See Also MXR ID Search for JS_ObjectIsFunction JS_ValueToFunction JS_ObjectIsFunction ...
JS_ObjectIsRegExp
ey 17 Determine if a specified object is a RegExp. Syntax bool JS_ObjectIsRegExp(JSContext *cx, JS::HandleObject obj); Name Type Description cx JSContext * A context. obj JS::HandleObject The object to examine. Description JS_ObjectIsRegExp determines if a specified object, obj, is a RegExp object. If so, JS_ObjectIsRegExp returns true.
Otherwise it returns false. See Also MXR ID Search for JS_ObjectIsRegExp JS_NewRegExpObject JS_NewUCRegExpObject RegExp bug 650931 ...
JS_RemoveExternalStringFinalizer
type code if found, -1 if not found. As with JS_AddExternalStringFinalizer, there is a threading restriction if you compile the engine JS_THREADSAFE: this function may be called for a given finalizer pointer on only one thread; different threads may call to remove distinct finalizers safely. You must ensure that all strings with finalizer's type have been collected before calling this function.
Otherwise, string data will be leaked by the GC, for want of a finalizer to call. See Also JS_AddExternalStringFinalizer bug 724810 ...
JS_ResolveStandardClass
quires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject An object to resolve id to a standard class. id JS::HandleId An id of a standard class name, which must contain either a string or an int. resolved bool * Out parameter. If the id is resolved, true is stored into *resolved if success. false
otherwise. Description JS_ResolveStandardClass resolves id, which must contain either a string or an int, to a standard class name in obj if possible, defining the class's constructor and/or prototype and storing true in *resolved. If id does not name a standard class or a top-level property induced by initializing a standard class, store false in *resolved and just return true. Return false on err...
JS_ScheduleGC
frequency uint32_t The value of nextScheduled parameter of GC. Description JS_ScheduleGC sets the nextScheduled parameter of GC. At every allocation nextScheduled is decremented. When it reaches zero, we do either a full or a compartmental GC. At this point, if zeal is one of the types that trigger periodic collection, then nextScheduled is reset to the value of frequency.
Otherwise, no additional GCs take place. See Also MXR ID Search for JS_ScheduleGC JS_SetGCZeal bug 650978 ...
JS_SetArrayLength
in the array are destroyed. Setting the number of array elements does not initialize those elements. To initialize an element call JS_DefineElement. If you call JS_SetArrayLength on an existing array, and length is less than the highest index number for previously defined elements, all elements greater than or equal to length are automatically deleted. On success, JS_SetArrayLength returns true.
Otherwise it returns false. See Also MXR ID Search for JS_SetArrayLength JS_DefineElement JS_DeleteElement JS_GetArrayLength JS_GetElement JS_IsArrayObject JS_LookupElement JS_NewArrayObject JS_SetElement ...
JS_SetInterruptCallback
ck The callback function to install. Callback syntax bool (* JSInterruptCallback)(JSContext *cx); Name Type Description cx JSContext * Pointer to a JSContext in which this callback was installed. The callback may use this context to call JSAPI functions, but it should first use JS_SetInterruptCallback to set the context's interrupt callback to NULL.
Otherwise the engine may call the interrupt callback again, reentering it. Provides request. In JS_THREADSAFE builds, the JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest()). Description These functions allow setting an interrupt callback that will be called from the JS thread some time after any thread trig...
JS_SetOperationCallback
ck) The callback function to install. Callback syntax JSBool (*JSOperationCallback)(JSContext *cx); Name Type Description cx JSContext * Pointer to a JSContext in which this callback was installed. The callback may use this context to call JSAPI functions, but it should first use JS_SetOperationCallback to set the context's operation callback to NULL.
Otherwise the engine may call the operation callback again, reentering it. Provides request. In JS_THREADSAFE builds, the JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest()). Applications must not use both the operation callback API and the older branch callback API. Description These functions allow sett...
JS_SetParent
n fact, once an object is exposed to a script, the object's parent must not change. The JavaScript engine relies on this invariant. JS_SetParent has no way to check that this is the case, but nonetheless, applications must not call JS_SetParent on an object that has already been exposed to a script. If an application does this, the behavior is undefined. On success, JS_SetParent returns JS_TRUE.
Otherwise, it reports an error or sets an exception and returns JS_FALSE. See Also MXR ID Search for JS_SetParent bug 1136980 - removed ...
JS_SetPropertyAttributes
rties, and is cast to a const char *. If JS_SetPropertyAttributes cannot locate an object with the specified property, it returns JS_FALSE, and the value left in *foundp is undefined. If the specified property or the specified object does not exist, foundp is set to JS_FALSE. Then, if the property exists, but is associated with a different object, JS_SetPropertyAttributes returns JS_TRUE.
Otherwise, it sets foundp to JS_TRUE, and attempts to set the attributes as specified. If the attributes can be set, JS_SetPropertyAttributes returns JS_TRUE. If not, it returns JS_FALSE. To get the attributes of a property, use JS_GetPropertyAttributes. Property attributes bug 893186 ...
JS_SetPrototype
hared by similar JS object instances. Ordinarily you set a prototype for an object when you create the object with JS_NewObject, but if you do not set a prototype at that time, you can later call JS_SetPrototype to do so. obj is a pointer to an existing JS object, and proto is a pointer to second existing object upon which the first object is to be based. On success, JS_SetPrototype returns true.
Otherwise it returns false. Take care not to create a circularly-linked list of prototypes using this function, because such a set of prototypes cannot be resolved by the JavaScript engine and can easily lead to an infinite loop. To get an object's prototype, use JS_GetPrototype. See Also LXR ID Search JS_GetPrototype ...
JS_SetRegExpInput
lobal object. input JS::HandleString A pointer to the input string. multiline bool true if input is multiline. Description JS_SetRegExpInput sets the pending input string of the built-in RegExp object to the specified input string. The JSREG_MULTILINE is set to multiline parameter, and other flags are all reset. On successful, JS_SetRegExpInput returns true,
otherwise returns false. See Also MXR ID Search for JS_SetRegExpInput JS_NewRegExpObject JS_NewUCRegExpObject JSREG_MULTILINE JS_ClearRegExpStatics RegExp ...
JS_StrictlyEqual
v1, v2 JS::Handle<JS::Value> / jsval The value to compare. equal bool * Out parameter. Receives the comparison result. Description JS_StrictlyEqual determines if v1 is strictly equal to v2 under the JavaScript === operator, as specified in ECMA 262-3 ?11.9.6. If the comparison attempt was successful, the method returns true and stores the result in *equal;
otherwise it returns false. Comparing jsvals directly in C++, as in v1 == v2, does not produce a meaningful result, since it is possible for two distinct JSStrings or jsdoubles to represent the same string or number. See Also MXR ID Search for JS_StrictlyEqual JS_LooselyEqual JS_SameValue bug 1132045 -- use handle ...
JS_StringEqualsAscii
g to compare. asciiBytes const char * ASCII string to compare with. match bool * (JS_StringEqualsAscii only) Out parameter. Received the comparison result. Description JS_StringEqualsAscii and JS_FlatStringEqualsAscii compare string str and ASCII string asciiBytes. On successful, JS_StringEqualsAscii stores the comparison result into *match and returns true,
otherwise returns false. JS_FlatStringEqualsAscii always succeeds, and returns the comparison result. See Also MXR ID Search for JS_StringEqualsAscii MXR ID Search for JS_FlatStringEqualsAscii bug 609440 ...
JS_THREADSAFE
o trigger GC, especially if the calling thread has not been using up a lot of memory. In a multithreaded program, even if the calling thread has been idle, other threads may be active or may call JS_GC(). The above rules mean that at any given moment, there can be either (a) multiple threads in active requests, or (b) one thread doing GC and all requests suspended. When one thread calls JS_GC or
otherwise finds that garbage collection is necessary, it must wait for all other threads that are in requests to pause before garbage collection can occur. To keep this wait time to a minimum, applications must avoid long-running requests. The recommended technique in SpiderMonkey 1.8 and later is to periodically call JS_YieldRequest from an operation callback. Sharing data among threads "Data can be mar...
JS_ValueToFunction
be treated like a real function. Instead, use JSVAL_IS_OBJECT and JS_ObjectIsFunction() to check whether a value is already a function, or use JS_ConvertValue() to convert a value to JSTYPE_FUNCTION safely. If v is a Function object, this returns the associated JSFunction. If v is null, undefined, a boolean, a number, or a string, a TypeError is reported and JS_ValueToFunction returns NULL.
Otherwise, v is an object. The JavaScript engine attempts to convert it to a function. (Implementation note: The actual conversion is performed by the object itself. The object's JSObjectOps.defaultValue method is called with hint=JSTYPE_FUNCTION.) JS_ValueToFunction returns a pointer to the converted function. If conversion fails with an error or exception, JS_ValueToFunction returns NULL. See Also ...
JS_ValueToInt32
ut parameter. On success, *ip receives the converted integer value. Description JS_ValueToInt32 converts a specified JS value, v, to a 32-bit signed integer (-2147483648 to 2147483647). First it converts v to a floating-point number as if by calling JS::ToNumber. If the result is NaN, an infinity, or a number outside the 32-bit range, JS_ValueToInt32 reports an error and conversion fails.
Otherwise, the floating-point number is rounded to the nearest integer value. On success, JS_ValueToInt32 stores the converted value in *ip and returns JS_TRUE. On error or exception, it returns JS_FALSE, and the value left in *ip is undefined. JS_ValueToInt32 is pre-ECMA-262 Edition 1, and rounds differently than JS_ValueToECMAInt32 and JS::ToInt32. This routine was added for layers-based graphics progr...
JS_ValueToObject
this JSContext. v JS::HandleValue The value to convert. objp JS::MutableHandleObject Out parameter. On success, *objp receives NULL or a pointer to the resulting object. Description JS_ValueToObject converts a specified JavaScript value, v, to an object. On success, this function stores either NULL or a pointer to the resulting object in *objp and returns true.
Otherwise it returns false and the value left in *objp is unspecified. If v is JSVAL_NULL or JSVAL_VOID, the result is NULL. If v is a boolean value, a number, or a string, the result is a new wrapper object of type Boolean, Number, or String.
Otherwise v is an object, and the result depends on the object. If v is a native JavaScript Object, this calls the object's valueOf method, if any. In any case, ...
JSAPI reference
otScope Obsolete since JavaScript 1.8.5 JS_LeaveLocalRootScopeWithResult Obsolete since JavaScript 1.8.5 JS_ForgetLocalRoot Obsolete since JavaScript 1.8.5 Added in SpiderMonkey 1.8 If an object contains references to other GC things that are not stored in SpiderMonkey data structures ("slots"), it must implement the JSTraceOp hook to enable the garbage collector to traverse those references.
Otherwise the garbage collector will not find all reachable objects and may collect objects that are still reachable, leading to a crash. (In SpiderMonkey 1.7 and earlier, the JSMarkOp hook was used instead. This has since been removed.) The tracing APIs are used by the garbage collector and JSTraceOp hooks. JSAPI applications may also use them to examine the object graph. (For example, these APIs support...
Parser API
ocation | null; } The type field is a string representing the AST variant type. Each subtype of Node is documented below with the specific string of its type field. You can use this field to determine which interface a node implements. The loc field represents the source location information of the node. ...
SpiderMonkey 1.8.8
t variable MOZ_CUSTOM_STDINT_H is set, that file will be included to provide definitions for these types. The file must conform to the standard C99 <stdint.h> header interface in all respects, providing all that header's types and macro definitions. (The msstdint project includes an implementation of this header for Microsoft Visual Studio which demonstrates what the C99 interface looks like.)
Otherwise, if the compiler doesn't provide a usable <stdint.h> header, a custom implementation shipped with the SpiderMonkey source is used. Currently only versions of Visual Studio prior to 2010 (also known as version 10) are known to be deficient in this manner, so the custom implementation (which is compatible with the one shipped in Visual Studio 2010 and later) is only invoked for those compilers. O...
SpiderMonkey 17
t variable MOZ_CUSTOM_STDINT_H is set, that file will be included to provide definitions for these types. The file must conform to the standard C99 <stdint.h> header interface in all respects, providing all that header's types and macro definitions. (The msstdint project includes an implementation of this header for Microsoft Visual Studio which demonstrates what the C99 interface looks like.)
Otherwise, if the compiler doesn't provide a usable <stdint.h> header, a custom implementation shipped with the SpiderMonkey source is used. Currently only versions of Visual Studio prior to 2010 (also known as version 10) are known to be deficient in this manner, so the custom implementation (which is compatible with the one shipped in Visual Studio 2010 and later) is only invoked for those compilers. O...
SpiderMonkey 24
t variable MOZ_CUSTOM_STDINT_H is set, that file will be included to provide definitions for these types. The file must conform to the standard C99 <stdint.h> header interface in all respects, providing all that header's types and macro definitions. (The msstdint project includes an implementation of this header for Microsoft Visual Studio which demonstrates what the C99 interface looks like.)
Otherwise, if the compiler doesn't provide a usable <stdint.h> header, a custom implementation shipped with the SpiderMonkey source is used. Currently only versions of Visual Studio prior to 2010 (also known as version 10) are known to be deficient in this manner, so the custom implementation (which is compatible with the one shipped in Visual Studio 2010 and later) is only invoked for those compilers. O...
Setting up CDT to work on SpiderMonkey
red because CDT needs detailed information about which directories make operates on, which using -w causes make to provide). Change the "Build location" to the build directory configured in Step 1. For me, that means changing "Build directory" to read ${workspace_loc:/SpiderMonkey/_DBG.OBJ}. Under "Behavior", make sure that "Enable parallel build" is deactivated, as CDT's indexer will freak out
otherwise. Remove "all" from "Build (Incremental build)". Deactivate "Clean" so that your builds do not take ages. If you want to use ccache: Select "C/C++ General", then "Preprocessor Include Patterns". Under the "Providers" group tab, select "CDT GCC Build Output Parser" and add the string |(ccache) to the end of the "Compiler command pattern" text input. Start the build by selecting "Build All" from...
Thread Sanitizer
The default way of symbolizing the traces is much slower than using llvm-symbolizer for that purpose: LLVM ships with a symbolizer binary that TSan will readily use to immediately output symbolized traces much faster. Furthermore, additional debug information is included in traces when llvm-symbolizer is used. To use it, either make sure the llvm-symb...
Using RAII classes in Mozilla
Blocker(); } private: MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER }; MOZ_GUARD_OBJECT_NOTIFIER_PARAM is added to the end of the constructor's parameter list. MOZ_GUARD_OBJECT_NOTIFIER_INIT is added as a statement in the constructor. MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER is added where private members should be declared. However, there are some variations for special cases: First, if the constructor (
otherwise) takes no arguments, then you have to use the MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM macro instead. (This is needed because the macro adds a parameter only when DEBUG is defined, and in this case, it can't add the leading comma.) class MOZ_RAII nsAutoScriptBlocker { public: explicit nsAutoScriptBlocker(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) { MOZ_GUARD_OBJECT_NOTIFIER_INIT; nsContentUtils...
Secure Development Guidelines
-related registers (ESP, EBP) Mark top and bottom of current stack frame Status register (EFLAGS) Contains various state information Instruction pointer (EIP) Points to register being executed; can't be modified directly Introduction: Gaining Control (2) EIP is modified using call or jump instructions Attacks usually rely on obtaining control over the EIP
Otherwise the attacker can try to control memory pointed to by an existing function pointer A vulnerability is required to modify the EIP or sensitive memory Saved return addr or function pointer get altered Introduction: Gaining Control (3) Common issues used to gain control Buffer overflows Format string bugs Integer overflows/underflows Writing Secure Code: Input Validation In...
Setting up an update server
t): ac_add_options --disable-verify-mar Several files contain a line that must be uncommented. Open them and find this line: #DEFINES['DISABLE_UPDATER_AUTHENTICODE_CHECK'] = True. Delete the # at the beginning of the line to uncomment it. These are the files that must be changed: toolkit/components/maintenanceservice/moz.build toolkit/mozapps/update/tests/moz.build Firefox should
otherwise be built normally. After building, you may want to copy the installation of Firefox elsewhere. If you update the installation without moving it, attempts at further incremental builds will not work properly, and a clobber will be needed when building next. To move the installation, first call ./mach package, then you can either copy <obj dir>/dist/firefox to a new "install directory" elsewhere, o...
Signing Mozilla apps for Mac OS X
you're signing Mozilla applications with v1 signatures, you'll need to specify a custom CodeResources file here. -f Forces codesign to overwrite an existing signature on the application. -v Increases the verbosity of the codesign tool's output. --deep For v2 signing, sign all nested executables with the same settings. Note that you cannot specify an identifier requirement if you do this, or
otherwise you need to sign the outer application again with the identifier requirement. --requirement 'designated requirement' Adds additional requirements for verifying the signature and application metadata. At a minimum you'll need to provide: identifier: This must be the same as the value of the CFBundleIdentifier specified in your application's info.plist file. leaf[subject.OU]: This needs to b...
Animated PNG graphics
r in the stream before any 'IDAT' chunks. The 'acTL' structure is described below. Conceptually, at the beginning of each play the output buffer must be completely initialized to a fully transparent black rectangle, with width and height dimensions from the 'IHDR' chunk. The default image may be included as the first frame of the animation by the presence of a single 'fcTL' chunk before 'IDAT'.
Otherwise, the default image is not part of the animation. Subsequent frames are encoded in 'fdAT' chunks, which have the same structure as 'IDAT' chunks, except preceded by a sequence number. Information for each frame about placement and rendering is stored in 'fcTL' chunks. The full layout of 'fdAT' and 'fcTL' chunks is described below. The boundaries of the entire animation are specified by the width...
Places Expiration
tabase size at a reasonable (and performant) value. All of expiration uses the Storage async API, that ensures I/O is in a separate thread, plus it won't block any read thanks to the use of the WAL journaling system. Common expiration runs on a timer, every 3 minutes and uses a simple adaptive algorithm: if the last step was unable to expire enough entries the next one will expire more entries,
otherwise if the previous step completed the cleanup the next step will be delayed. This ensures expiration doesn't lag behind without hitting performances when there is no need for it. Apart this periodic expiration, there are other steps on idle, on shutdown on clear history. On Idle On idle it expires a larger chunk of pages, then timed expiration is stopped. This ensures to not interfere with standb...
Retrieving part of the bookmarks tree
r folder. If you have a complex query the root will be a nsINavHistoryQueryResultNode. Before accessing the children of any result container, you must first open it, and then you can iterate the children. As long as the container is open, it will listen for notifications from the bookmarks system to keep itself up-to-date. When you're done, be sure to close the container to free up the resources.
Otherwise, it will continue to get observer notifications and update itself, slowing down the whole browser. var rootNode = result.root; rootNode.containerOpen = true; // iterate over the immediate children of this folder and dump to console for (var i = 0; i < rootNode.childCount; i ++) { var node = rootNode.getChild(i); dump("Child: " + node.title + "\n"); } // close a container after using it! roo...
Using the Places favicon service
con-service;1"] .getService(Components.interfaces.nsIFaviconService); Caching The favicon service stores an expiration time for each favicon. This time is used by nsIFaviconService.setAndLoadFaviconForPage() to determine if the data is fresh or needs reloading from the server. If you are manually loading favicon data, you can specify the expiration time yourself.
Otherwise, nsIFaviconService.setAndLoadFaviconForPage() will use the default expiration time. Currently, the default expiration time is set to one day in the future. This makes sure that we aren't obsessively reloading favicons into the database for every page viewed, but also that changes in the favicon will be picked up quickly. Most of the time, the favicon will be served from the browser's cache and wi...
Using the Places history service
bookmark titles.This function may be removed if the bookmark service is changed. nsINavHistoryService.setPageDetails: Used to set all of the global bits associated with a URL. It is designed for synchronizing or backup services. Basic querying of the history system nsIGlobalHistory2.isVisited: Called by Gecko when rendering links. When isVisited returns true, the link gets the "visited" style.
Otherwise, the link is colored as unvisited. nsIGlobalHistory3.getGeckoFlags: Retrieves information previously set using setGeckoFlags. It is not yet implemented in the Places history system. nsIBrowserHistory.lastPageVisited: Contains the URI of the last page visited. This is used when the preference is set that causes the last page in new windows. nsIBrowserHistory.count: The number of pages in histor...
extISessionStorage
DefaultValue) Attributes Attribute Type Description events readonly attribute extIEvents The events object for the storage supports: "change" Methods has() Determines if a storage item exists with the given name. boolean has(in AString aName) Parameters aName The name of an item Return value true if an item exists with the given name, false
otherwise. set() Sets the value of a storage item with the given name. void set(in AString aName, in nsIVariant aValue) Parameters aName The name of an item Return value get() Gets the value of a storage item with the given name. Returns a default value if the item does not exist. nsIVariant get(in AString aName, in nsIVariant aDefaultValue) Parameters aName The name of an item Retu...
XPCOM array guide
ill your array store non-refcounted objects and be a fixed size? If so, just use a native C++ array unless you need the enumeration options on nsTArray<T>. Example: an array of error message static const char* pointers. Are all the things you are storing interface pointers to instances of the same interface? If so, use nsCOMArray. Example: a content node's list of nsIContent children.
Otherwise use nsIArray and make liberal use of QueryElementAt(). The point of nsCOMArray is that it's a template, and all the pointers in it must be pointers to the same type; it's nice to be able to use it because you get type-safety and don't have to spend time and code QIing (like you have to with nsIArray). Array Guidelines Here are a few simple rules which will keep your code clean and your develo...
Creating the Component Code
and the extra user interface. Web Lock User Interface Most of the actual work in the WebLock component is preparing the component itself, finding the XPCOM interfaces the component needs to use, and hooking into existing functionality within the Gecko Browser. Component Registration All XPCOM components - whether they're stored in shared libraries (DLLs, DSOs, dylibs), JavaScript files, or
otherwise - need to be registered before they can be used. Registration is a process that happens in all XPCOM applications, whether they're embedded Gecko clients, Mozilla, Netscape 7, Compuserve, or any other software that uses XPCOM. Registration provides the information that applications need in order to use components properly. The WebLock component must do a number of things to register itself. Spec...
Mozilla internal string guide
There are a number of additional string classes: Classes which exist primarily as constructors for the other types, particularly nsDependent[C]String and nsDependent[C]Substring. These types are really just convenient notation for constructing an ns[C]S[ubs]tring with a non-default ownership mode; they should not be thought of as differ...
Interfacing with the XPCOM cycle collector
not suspect any pointers by default; objects must suspect themselves, typically by using an nsCycleCollectingAutoRefCnt rather than a nsAutoRefCnt. It only traverses objects that return a helper object when QI'ed to nsICycleCollectionParticipant. If it encounters an unknown edge during its traversal, it gives up on that edge; this means that every edge involved in a cycle must be participating,
otherwise the cycle will not be found. The Traverse and Unlink methods on the helper object are not magic; they are programmer-supplied and must be correct, or else the collector will fail. The collector does not know how to find temporary owning pointers that exist on the stack, so it is important that it only run from near the top-loop of the program. It will not crash if there are extra owning pointer...
Components.utils.evalInWindow
x() constructor. Syntax var result = Components.utils.evalInWindow(script, window); Parameters script : string The script to evaluate in the other window. window : object The window in which to evaluate the script. Returns The result of evaluating the script. If this is just native (for example, a DOM node), then the function relies on XrayWrappers to wrap the returned content,
otherwise the result is structured-cloned. This does impose some restrictions on the sorts of things that can be returned: in particular, the result can't contain any functions, because functions can't be structured-cloned. Example Suppose a page script defines a variable: // page-script.js var someLocalVariable = { name: "selection1", node: document.documentElement }; An add-on script or other privil...
Components.utils.isXrayWrapper
a DOM object sees only the original, native version of the DOM object. Any expando properties are not visible, and if any native properties have been redefined, this has no effect. Use this function to determine whether a given object is an Xray or not. Syntax boolean Components.utils.isXrayWrapper(obj); Parameters obj The object to check. Returns true if the object is an Xray: false
otherwise. Example var isXray = Components.utils.isXrayWrapper(gBrowser.contentWindow); // true var waived = Components.utils.waiveXrays(gBrowser.contentWindow); isXray = Components.utils.isXrayWrapper(waived); // false ...
NS_GetComponentManager
XPCOM API Reference Summary The NS_GetComponentManager function returns a reference to the XPCOM Component Manager. #include "nsXPCOM.h" #include "nsIComponentManager.h" nsresult NS_GetComponentManager( nsIComponentManager** aResult ); Parameters aResult [out] A reference to the XPCOM Component Manager. Return Values The NS_GetComponentManager function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks The object returned is a singleton that is valid until NS_ShutdownXPCOM is called. The interface pointer should be Release'd when it is no longer needed. History This function was finalized for Mozilla 0.9.6. See bug 99147 for details. See Also nsIComponentManager ...
NS_GetComponentRegistrar
eference Summary The NS_GetComponentRegistrar function returns a reference to the XPCOM Component Registrar. #include "nsXPCOM.h" #include "nsIComponentRegistrar.h" nsresult NS_GetComponentRegistrar( nsIComponentManager** aResult ); Parameters aResult [out] A reference to the XPCOM Component Registrar. Return Values The NS_GetComponentRegistrar function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks The object returned is a singleton that is valid until NS_ShutdownXPCOM is called. The interface pointer should be Release'd when it is no longer needed. History This function was finalized for Mozilla 0.9.6. See bug 99147 for details. See Also nsIComponentRegistrar ...
NS_GetMemoryManager
<< XPCOM API Reference Summary The NS_GetMemoryManager function returns a reference to the XPCOM Memory Manager. #include "nsXPCOM.h" #include "nsIMemory.h" nsresult NS_GetMemoryManager( nsIMemory** aResult ); Parameters aResult [out] A reference to the XPCOM Memory Manager. Return Values The NS_GetMemoryManager function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks The object returned is a singleton that is valid until NS_ShutdownXPCOM is called. The interface pointer should be Release'd when it is no longer needed. Any code, intended to be used exclusively with Mozilla 1.8 and above, may use NS_Alloc, NS_Realloc, and NS_Free instead to access the XPCOM Memory Manager's methods. History This function was finalized for Mozilla 0.9.7. See bu...
NS_GetServiceManager
<< XPCOM API Reference Summary The NS_GetServiceManager function returns a reference to the XPCOM service manager. #include "nsXPCOM.h" #include "nsIServiceManager.h" nsresult NS_GetServiceManager( nsIServiceManager** aResult ); Parameters aResult [out] A reference to the XPCOM service manager. Return Values The NS_GetServiceManager function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks The object returned is a singleton that is valid until NS_ShutdownXPCOM is called. The interface pointer should be Release'd when it is no longer needed. History This function was finalized for Mozilla 0.9.6. See bug 99147 for details. See Also nsIServiceManager ...
NS_InitXPCOM2
ining the component registry and runtime libraries. Pass null to specify that the current working directory should be used. aAppFileLocationProvider [in] The object to be used by XPCOM to locate application specific directories and files (e.g., the user profile, the component registry, etc.). This parameter may be nsnull. Return Values The NS_InitXPCOM2 function returns NS_OK if successful.
Otherwise, it returns an error code. Some of the possible errors are documented below: NS_ERROR_NOT_INITIALIZED Indicates that static globals were not yet initialized, which may happen if this method is called before XPCOM's static initialization code executes. This error may also occur if XPCOM is being initialized after NS_ShutdownXPCOM has been called. Remarks You must call NS_InitXPCOM2 (or NS_In...
NS_InitXPCOM3
irectories and files (e.g., the user profile, the component registry, etc.). This parameter may be nsnull. aStaticModules [in] An array of nsStaticModuleInfo objects. Passing null causes the default (built-in) static modules to be registered, if present. aStaticModuleCount [in] The number of elements in aStaticModules. Return Values The NS_InitXPCOM3 function returns NS_OK if successful.
Otherwise, it returns an error code. Some of the possible errors are documented below: NS_ERROR_NOT_INITIALIZED Indicates that static globals were not yet initialized, which may happen if this method is called before XPCOM's static initialization code executes. This error may also occur if XPCOM is being initialized after NS_ShutdownXPCOM has been called. Remarks You must call NS_InitXPCOM3 (or NS_In...
NS_NewLocalFile
le instance will automatically resolve symbolic links. This parameter has no effect on UNIX systems. On Windows, passing true causes shortcuts to be automatically resolved, and on MacOS, passing true causes finder aliases to be automatically resolved. aResult [out] A reference to the newly created nsILocalFile instance. Return Values The NS_NewLocalFile function returns NS_OK if successful.
Otherwise, it returns an error code. NS_ERROR_FILE_UNRECOGNIZED_PATH Indicates that the specified path is invalid. This error is returned if a relative file path is passed to NS_NewLocalFile. Remarks On UNIX systems, the prefix "~/" is supported as a shorthand for the user's home directory. Example Code // Create a local file that references c:\foo.txt nsresult rv; nsCOMPtr<nsILocalFile> file; rv ...
NS_NewNativeLocalFile
tance will automatically resolve symbolic links. This parameter has no effect on UNIX systems. On Windows, passing true causes shortcuts to be automatically resolved, and on MacOS, passing true causes finder aliases to be automatically resolved. aResult [out] A reference to the newly created nsILocalFile instance. Return Values The NS_NewNativeLocalFile function returns NS_OK if successful.
Otherwise, it returns an error code. NS_ERROR_FILE_UNRECOGNIZED_PATH Indicates that the specified path is invalid. This error is returned if a relative file path is passed to NS_NewNativeLocalFile. Remarks On UNIX systems, the prefix "~/" is supported as a shorthand for the user's home directory. If you use this function on Windows 2000 or later, you would not be able to handle file names containing ...
NS_ShutdownXPCOM
XPCOM API Reference Summary The NS_ShutdownXPCOM function terminates use of XPCOM in the calling process. #include "nsXPCOM.h" nsresult NS_ShutdownXPCOM( nsIServiceManager* aSvcManager ); Parameters aSvcManager [in] The nsIServiceManager instance that was returned by NS_InitXPCOM2 (or NS_InitXPCOM3) or null. Return Values The NS_ShutdownXPCOM function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks You must call this method once you are finished using XPCOM. Calling this method triggers the "xpcom-shutdown" notification to be dispatched to observers. Once this function has been called, the nsIComponentManager and nsIServiceManager will refuse to return object instances. History This function was finalized for Mozilla 0.9.6. See bug bug 99147 for deta...
Append
pend( const self_type& aString ); Parameters aString [in] A nsACString to append to this string. void Append( const char_type* aData, size_type aDataLength = PR_UINT32_MAX ); Parameters aData [in] A raw character array to append to this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. void Append( char_type aChar ); Parameters aChar [in] A character to append to this string. Remarks If insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer. ...
Assign
sign( const self_type& aString ); Parameters aString [in] A nsACString to copy into this string. void Assign( const char_type* aData, size_type aDataLength = PR_UINT32_MAX ); Parameters aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. void Assign( char_type aChar ); Parameters aChar [in] The character to copy into this string. Remarks If insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer. ...
Insert
ype* aData, index_type aPosition, size_type aDataLength = PR_UINT32_MAX ); Parameters aData [in] A raw character array to append to this string. aPosition [in] An offset into the string's internal buffer specifying where to place the given characters. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. void Insert( char_type aChar, index_type aPosition ); Parameters aChar [in] A character to append to this string. aPosition [in] An offset into the string's internal buffer specifying where to place the given characters. Remarks If insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static e...
Replace
= PR_UINT32_MAX ); Parameters aCutStart [in] The starting index of the section to remove, measured in storage units. aCutLength [in] The length of the section to remove, measured in storage units. aData [in] A raw character array to append to this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. void Replace( index_type aCutStart, index_type aCutLength, char_type aChar ); Parameters aCutStart [in] The starting index of the section to remove, measured in storage units. aCutLength [in] The length of the section to remove, measured in storage units. aChar [in] A character to append to this string. Remarks If insufficient memory is availab...
Append
ppend( const self_type& aString ); Parameters aString [in] A nsAString to append to this string. void Append( const char_type* aData, size_type aDataLength = PR_UINT32_MAX ); Parameters aData [in] A raw character array to append to this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. void Append( char_type aChar ); Parameters aChar [in] A character to append to this string. Remarks If insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer. ...
Assign
ssign( const self_type& aString ); Parameters aString [in] A nsAString to copy into this string. void Assign( const char_type* aData, size_type aDataLength = PR_UINT32_MAX ); Parameters aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. void Assign( char_type aChar ); Parameters aChar [in] The character to copy into this string. Remarks If insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer. ...
Insert
ype* aData, index_type aPosition, size_type aDataLength = PR_UINT32_MAX ); Parameters aData [in] A raw character array to append to this string. aPosition [in] An offset into the string's internal buffer specifying where to place the given characters. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. void Insert( char_type aChar, index_type aPosition ); Parameters aChar [in] A character to append to this string. aPosition [in] An offset into the string's internal buffer specifying where to place the given characters. Remarks If insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static e...
Replace
= PR_UINT32_MAX ); Parameters aCutStart [in] The starting index of the section to remove, measured in storage units. aCutLength [in] The length of the section to remove, measured in storage units. aData [in] A raw character array to append to this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. void Replace( index_type aCutStart, index_type aCutLength, char_type aChar ); Parameter aCutStart [in] The starting index of the section to remove, measured in storage units. aCutLength [in] The length of the section to remove, measured in storage units. aChar [in] A character to append to this string. Remarks If insufficient memory is availabl...
nsEmbedCString
stractString ); Parameters aAbstractString [in] A nsACString to copy into this string. explicit nsEmbedCString( const char_type* aData, size_type aDataLength = PR_UINT32_MAX ); Parameters aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. Remarks The default constructor sets the string's internal buffer to point to a static empty (zero-length) buffer. ...
nsEmbedString
AbstractString ); Parameters aAbstractString [in] A nsAString to copy into this string. explicit nsEmbedString( const char_type* aData, size_type aDataLength = PR_UINT32_MAX ); Parameters aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. Remarks The default constructor sets the string's internal buffer to point to a static empty (zero-length) buffer. ...
Clone
ry block up to the size specified. static void* Clone( const void* aPtr, size_t aSize ); Parameters aPtr [in] The address of the memory block to copy. This must be non-null. aSize [in] Specifies the new size in bytes of the block of memory to allocate. The buffer at aPtr must be at least aSize bytes in length. Return Values This function returns nsnull if the memory allocation fails.
Otherwise, it returns a pointer to the newly allocated buffer. The result must be freed with a call to nsMemory::Free when it is no longer needed. See Also nsMemory::Free ...
Realloc
void* aPtr, size_t aSize ); Parameters aPtr [in] The address of the memory block to reallocate. This may be nsnull, in which case Realloc behaves like nsMemory::Alloc. aSize [in] Specifies the new size in bytes of the block of memory to allocate. This may be 0, in which case Realloc behaves like nsMemory::Free. Return Values This function returns nsnull if the memory allocation fails.
Otherwise, it returns a pointer to the newly allocated buffer. The result must be freed with a call to nsMemory::Free when it is no longer needed. Remarks If aPtr is non-null, then its contents will be unchanged to the minimum of the old and new sizes. Newly allocated memory is uninitialized. See Also nsMemory::Free ...
IAccessibleHyperlink
rned value is related to the IAccessibleText interface of the object that owns this hyperlink. Return value S_OK. valid() Returns whether the target object referenced by this link is still valid. This is a volatile state that may change without sending an appropriate event. [propget] HRESULT valid( [out] boolean valid ); Parameters valid true if the referenced target is still valid and false
otherwise. This has also been used to indicate whether or not the URI of the anchorTarget is malformed. Return value S_FALSE if there is nothing to return, [out] value is false. S_OK. See also IAccessibleAction IAccessibleText ...
IAccessibleTableCell
Parameters columnIndex Returns the 0 based column index of the cell of the specified cell or the index of the first column if the cell spans multiple columns. Return value S_OK. isSelected() Returns a boolean value indicating whether this cell is selected. [propget] HRESULT isSelected( [out] boolean isSelected ); Parameters isSelected Returns true if the specified cell is selected and false
otherwise. Return value S_OK. rowColumnExtents() Gets the row and column indexes and extents of this cell accessible and whether or not it is selected. This is a convenience function. It is not mandatory to implement it. [propget] HRESULT rowColumnExtents( [out] long row, [out] long column, [out] long rowExtents, [out] long columnExtents, [out] boolean isSelected ); Parameters row 0 based row ...
imgIRequest
age load. imgIRequest clone( in imgIDecoderObserver aObserver ); Parameters aObserver Return value decrementAnimationConsumers() Tell the image it can forget about a request that the image animate. void decrementAnimationConsumers(); Parameters None. getStaticRequest() If this request is for an animated image, the method creates a new request which contains the current frame of the image.
Otherwise returns the same request. imgIRequest getStaticRequest(); Parameters None. Return value incrementAnimationConsumers() Requests that the image animate (if it has an animation). void incrementAnimationConsumers(); Parameters None. lockImage() Locks an image. If the image does not exist yet, locks it once it becomes available. The lock persists for the lifetime of the imgIRequest (until unlockIma...
jsdIStackFrame
Supports object. Attempting to alter this bit will result in an NS_ERROR_ILLEGAL_VALUE. OPT_* values above, OR'd together. Last version set on this context. Scripts typically select this with the "language" attribute. See the VERSION_* consts on jsdIDebuggerService. Unique tag among all valid jsdIContext objects, useful as a hash key. Private data for this context, if it is an nsISupports, |null|
otherwise. Retrieve the underlying context wrapped by this jsdIContext. Top of the scope chain for this context. |true| if this context should be allowed to run scripts, |false|
otherwise. This attribute is only valid for contexts which implement nsIScriptContext. Setting or getting this attribute on any other context will throw a NS_ERROR_NO_INTERFACE exception. Stack frame objects. These are only valid i...
mozIAsyncFavicons
the page. aForceReload If false, we try to reload the favicon only if we do not have it or it has expired from the cache. Setting to true causes us to reload the favicon even if we have a usable copy. aFaviconLoadType Set to nsIFaviconService.FAVICON_LOAD_PRIVATE if the favicon is loaded from a private browsing window. Set to nsIFaviconService.FAVICON_LOAD_NON_PRIVATE
otherwise aCallback Optional Once we're done setting and/or fetching the favicon, we invoke this callback. replaceFaviconData() Sets the data for a given favicon URI either by replacing existing data in the database or taking the place of
otherwise fetched icon data when calling setAndFetchFaviconForPage later. Favicon data for favicon URIs that are not associated with a page URI via setAndF...
mozIRepresentativeColorCallback
nged in Gecko 17.0 (Firefox 17.0 / Thunderbird 17.0 / SeaMonkey 2.14) Method overview void onComplete(in boolean success, [optional] in unsigned long color); Methods onComplete() Will be called when color analysis finishes. void onComplete( in boolean success, [optional] in unsigned long color ); Parameters success True if analysis was successful, false
otherwise. Analysis can fail if the image is transparent, imageURI doesn't resolve to a valid image, or the image is too big. color The representative color as an integer in RGB form. e.g. 0xFF0102 == rgb(255,1,2). If success is false, color is not provided. ...
mozIStorageStatement
Return value Returns a boolean indicating whether there are more rows or not. Row data may be accessed using mozIStorageValueArray methods on the statement. step() Identical to calling executeStep(), and then calling reset() when no more rows are returned. Note: This method may only be called from JavaScript code. boolean step() Return value true if there are more rows left in the results,
otherwise false. execute() Execute the query, ignoring any results. This is accomplished by calling executeStep(), and then calling reset(). void execute(); See also Storage introduction and how-to article mozIStorageConnection Database connection to a specific file or in-memory data storage mozIStorageValueArray Wraps an array of SQL values, such as a result row. mozIStorageFunction Create a n...
mozIStorageStatementWrapper
is wrapper with aStatement. void initialize( in mozIStorageStatement aStatement ); Parameters aStatement The statement to be initialized. reset() This method resets the wrapped statement. void reset(); Parameters None. step() This method steps the wrapped statement. boolean step(); Parameters None. Return value Returns true if the stepping the wrapped statement was successful,
otherwise returns false. execute() This method executes the wrapped statement. void execute(); Parameters None. See also Storage mozIStorageStatement mozIStorageStatementRow mozIStorageStatementParams ...
mozIStorageValueArray
column to get the data from. aDataSize The size of the returned array. Return value The blob for the specified entry. getIsNull() Checks if given column index is NULL. boolean getIsNull( in unsigned long aIndex ); Parameters aIndex The zero-based numerical index for the column to get the data from. Return value Returns true if the column specified by aIndex is NULL, or false
otherwise. See also Storage introduction and how-to article mozIStorageConnection Database connection to a specific file or in-memory data storage mozIStorageStatement Create and execute SQL statements on a SQLite database. mozIStorageFunction Create a new SQLite function. mozIStorageAggregateFunction Create a new SQLite aggregate function. mozIStorageProgressHandler Monitor progress during the ex...
nsIAboutModule
ird 3.3 / SeaMonkey 2.1) Method overview unsigned long getURIFlags(in nsIURI aURI); nsIChannel newChannel(in nsIURI aURI); Constants Constant Value Description URI_SAFE_FOR_UNTRUSTED_CONTENT (1 << 0) A flag that indicates whether a URI is safe for untrusted content. If it is, web pages and so forth will be allowed to link to this about: URI.
Otherwise, only chrome will be able to link to it. ALLOW_SCRIPT (1 << 1) A flag that indicates whether script should be enabled for the given about: URI even if it's disabled in general. HIDE_FROM_ABOUTABOUT (1 << 2) A flag that indicates whether this about: URI doesn't want to be listed in about:about, especially if it's not useful without a query string. Methods get...
nsIAccessibleDocument
2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Returns the first accessible parent of a DOM node. Guaranteed not to return null if the DOM node is in a document. nsIAccessible getAccessibleInParentChain( in nsIDOMNode aDOMNode, in boolean aCanCreate ); Parameters aDOMNode The DOM node we need an accessible for. aCanCreate If true, this method can create a new accessible.
Otherwise, it will return the first cached accessible in the parent chain. Return value The first nsIAccessible found by crawling up the DOM node to the document root. Native code only!getCachedAccessNode Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any ...
nsIAccessibleHyperText
n NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. NS_ERROR_INVALID_ARG The link index is invalid. getLinkIndex() The link index at the given offset (character index). long getLinkIndex( in long charIndex ); Parameters charIndex The 0-based character index. Return value The index of the link if it's presented on the given character index,
otherwise -1. Exceptions thrown NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. getSelectedLinkIndex() Obsolete since Gecko 1.9 (Firefox 3) long getSelectedLinkIndex(); Parameters None. Return value Missing Description Exceptions thrown NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. ...
nsIAccessibleSelectable
object was not selected, then it does nothing. void removeChildFromSelection( in long index ); Parameters index Zero-based accessible child index. Exceptions thrown NS_ERROR_FAILURE If the specified object is not selectable. selectAllSelection() Select all children. boolean selectAllSelection(); Parameters None. Return value If the object does not accept multiple selection, return false.
Otherwise, returns true. ...
nsIAlertsService
ional in AString dir, Optional in AString lang, Optional in AString data, Optional in nsIPrincipal principal, Optional in boolean inPrivateBrowsing, Optional ); Parameters imageUrl A URL identifying the image to display in the notification alert. title The title for the alert. text The text to display in the alert, explaining the alert condition. The text must not be too long,
otherwise it might be truncated to a platform-specific length. If the text is too long, try to use line returns in the text to have it split and displayed over multiple lines. textClickable Optional If true, if the user clicks on it, the listener is notified; when hovered the notification background becomes lighter and the cursor turns to a pointer. Prior to Gecko 32 the text was made to look like a lin...
nsIApplicationCache
Read only. clientID ACString The client ID for this application cache. Clients can open a session with nsICacheService.createSession() using this client ID and a storage policy of STORE_OFFLINE to access this cache. Read only. groupID ACString The group ID for this cache group. This is the URI of the cache manifest file. Read only. usage unsigned long The disk usage of the applicatio...
nsIApplicationCacheChannel
g AsyncOpen() on the channel. inheritApplicationCache boolean true if the channel will ask its notification callbacks for an application cache if one is not explicitly provided. The default value is true. Exceptions thrown NS_ERROR_ALREADY_OPENED If set after calling AsyncOpen() on the channel. loadedFromApplicationCache PRBool true if the resource was loaded from the application cache,
otherwise false. This value may be false even if the resource is assigned to an application cache if, for example, it was loaded as a fallback. Read only. Methods markOfflineCacheEntryAsForeign() A shortcut method to mark the cache item of this channel as 'foreign'. See the 'cache selection algorithm' and CACHE_SELECTION_RELOAD action handling in nsContentSink. void markOfflineCacheEntryAsForeign(); Pa...
nsIApplicationUpdateService
s might be disabled by the application and the platform the application is running on. Read only. canUpdate boolean true if the update service is able to download and install updates. This depends on whether or not the current user has the necessary access privileges for the install directory. Read only. Obsolete since Gecko 1.9.1.7pre isDownloading boolean true if a download is in progress,
otherwise false. Read only. Methods addDownloadListener() Adds a listener that receives progress and state information about the update that is currently being downloaded. This information is most commonly used to update a user interface that informs the user as to the status of an update. void addDownloadListener( in nsIRequestObserver listener ); Parameters listener An object implementing nsIReque...
nsIAsyncInputStream
from the notification handler. This method may be called at any time (even if read has not been called). In other words, this method may be called when the stream already has data to read. It may also be called when the stream is closed. If the stream is already readable or closed when asyncWait is called, then the nsIInputStreamCallback.onInputStreamReady() event will be dispatched immediately.
Otherwise, the event will be dispatched when the stream becomes readable or closed. void asyncWait( in nsIInputStreamCallback aCallback, in unsigned long aFlags, in unsigned long aRequestedCount, in nsIEventTarget aEventTarget ); Parameters aCallback This object is notified when the stream becomes ready. This parameter may be null to clear an existing callback. aFlags This parameter specifies opt...
nsIAsyncOutputStream
notification handler. This method may be called at any time (even if write has not been called). In other words, this method may be called when the stream already has room for more data. It may also be called when the stream is closed. If the stream is already writable or closed when asyncWait is called, then the nsIOutputStreamCallback.onOutputStreamReady() event will be dispatched immediately.
Otherwise, the event will be dispatched when the stream becomes writable or closed. void asyncWait( in nsIOutputStreamCallback aCallback, in unsigned long aFlags, in unsigned long aRequestedCount, in nsIEventTarget aEventTarget ); Parameters aCallback This object is notified when the stream becomes ready. This parameter may be null to clear an existing callback. aFlags This parameter specifies op...
nsIAuthModule
ed to protect items of data to be sent to the server. void wrap( [const] in voidPtr aInToken, in unsigned long aInTokenLength, in boolean confidential, out voidPtr aOutToken, out unsigned long aOutTokenLength ); Parameters aInToken A buffer containing the data to be sent to the server. aInTokenLength The length of the input token. confidential If set to true, it will encrypt the data,
otherwise data will just be integrity protected (checksummed). aOutToken A buffer containing the resulting data to be sent to the server. aOutTokenLength The length of the output token buffer. Exceptions thrown NS_ERROR_NOT_IMPLEMENTED If the underlying authentication mechanism does not support security layers. ...
nsIAuthPrompt2
xt, in PRUint32 level, in nsIAuthInformation authInfo); boolean promptAuth(in nsIChannel aChannel, in PRUint32 level, in nsIAuthInformation authInfo); Constants Constant Value Description LEVEL_NONE 0 The password will be sent unencrypted. No security provided. LEVEL_PW_ENCRYPTED 1 Password will be sent encrypted, but the connection is
otherwise insecure. LEVEL_SECURE 2 The connection, both for password and data, is secure. Methods asyncPromptAuth() Asynchronously prompt the user for a username and password. This has largely the same semantics as nsIAuthPrompt.promptUsernameAndPassword(), but must return immediately after calling and return the entered data in a callback. If the user closes the dialog using a can...
nsIAuthPromptCallback
ct that was passed to nsIAuthPrompt2.asyncPromptAuth(). onAuthCancelled() Notification that the prompt was cancelled. void onAuthCancelled( in nsISupports aContext, in boolean userCancel ); Parameters aContext The context that was passed to nsIAuthPrompt2.asyncPromptAuth(). userCancel If false, this prompt was cancelled by calling the the cancel method on the nsICancelable;
otherwise, it was cancelled by the user. See also nsIAuthPrompt2 ...
nsIAutoCompleteInput
up list. consumeRollupEvent boolean If true, the event that rolls up the popup should be consumed by the popup itself. If false, the rollup event will be dispatched. Read only. controller nsIAutoCompleteController The controller. Read only. disableAutoComplete boolean true if auto-complete is currently disabled;
otherwise false. forceComplete boolean If true, the text field automatically completes to the default result whenever the user hits the enter key or the text field loses focus. maxRows unsigned long The maximum number of rows to display in the autocomplete suggestion popup. minResultsForPopup unsigned long Specifies a minim...
nsIBlocklistPrompt
y of addons and plugins that are blocked. These are javascript objects with properties: name - the plugin or extension name version - the version of the extension or plugin icon - the plugin or extension icon disable - can be used by the nsIBlocklistPrompt to allows users to decide whether a soft-blocked add-on should be disabled blocked - true if the item is hard-blocked, false
otherwise item - the nsIPluginTag or Addon object aCount Optional The number of addons. ...
nsICacheEntryInfo
Get the last time the cache entry was opened (in seconds since the Epoch). Read only. lastModified PRUint32 Get the last time the cache entry was modified (in seconds since the Epoch). Read only. Methods isStreamBased() This method finds out whether or not the cache entry is stream based. boolean isStreamBased(); Parameters None. Return value Returns true if the cache entry is stream based,
otherwise returns false. See also nsICache nsICacheVisitor ...
nsIChromeFrameMessageManager
RL); Methods loadFrameScript() Loads a script into the remote frame. void loadFrameScript( in AString aURL, in boolean aAllowDelayedLoad ); Parameters aURL The URL of the script to load into the frame; this must be an absolute URL, but data: URLs are supported. aAllowDelayedLoad If true, the script will be loaded when the remote frame becomes available;
otherwise, the script will only be loaded if the frame is already available. removeDelayedFrameScript() Removes a script from the list of scripts supporting delayed load. void removeDelayedFrameScript( in AString aURL ); Parameters aURL The URL of the script to remove from the list of scripts supporting delayed load. See also Content process event handling nsIContentFrameMessageMan...
nsIChromeRegistry
taining the loadable URI for the specified chrome URL. Violates the XPCOM interface guidelines wrappersEnabled() Returns whether XPCNativeWrappers are enabled for the specified URI. boolean wrappersEnabled( in nsIURI aURI ); Parameters aURI The URI for which to determine if XPCNativeWrappers are enabled. Return value true if XPCNativeWrappers are enabled for the specified URI;
otherwise false. See also Chrome Registration ...
nsICommandLine
n flags; that is, flags that don't accept a parameter. You can determine if the flag was provided and remove it from the list of flags waiting to be processed in one operation. boolean handleFlag( in AString aFlag, in boolean aCaseSensitive ); Parameters aFlag The flag name to find and remove. aCaseSensitive Whether to do case-sensitive comparisons. Return value true if the flag was found,
otherwise false. handleFlagWithParam() Finds a flag in the list of flags waiting to be processed and returns its value, after removing both the flag and its value from the list of flags waiting to be handled. This is useful for processing flags that accept a value. This is, essentially, a helper method that combines findFlag() and removeArguments() into one operation. AString handleFlagWithParam( in AStr...
nsIComponentRegistrar
Parameters None. Return value An nsISimpleEnumerator over the list of registered classes. Elements of the enumerator implement nsISupportsCString. isCIDRegistered() This method is used to test for the existence of a specific ClassID. boolean isCIDRegistered( in nsCIDRef aClass ); Parameters aClass The ClassID to be queried. Return value true if a factory is registered for the ClassID, false
otherwise. isContractIDRegistered() This method is used to test for the existence of a class implementing a specific ContractID. boolean isContractIDRegistered( in string aContractID ); Parameters aContractID The ContractID to be queried. Return value true if a factory is registered for the ContractID, false
otherwise. registerFactory() Registers a factory to be used to instantiate a particular class ...
nsIContentPrefService
nce exists; this may be specified as either a URI or as a string. In either case, the group consists of all sites matching the hostname portion of the specified URI. Specify null to check for the preference in the global preference space; those preferences apply to all sites. aName The name of the preference whose existence is to be determined. Return value true if the preference exists;
otherwise false. Exceptions thrown NS_ERROR_ILLEGAL_VALUE If aGroup is not a string, nsIURI, or null. Or if aName is null or an empty string removeGroupedPrefs() Remove all grouped prefs. Useful for removing references to the sites the user has visited when the user clears their private data. void removeGroupedPrefs(); removeObserver() Removes an observer that's presently monitoring a preference...
nsIContentPrefService2
private browsing and determines the kind of storage that a method uses, either the usual permanent storage or temporary storage set() aside for private browsing sessions. Pass null to unconditionally use permanent storage. Pass an nsILoadContext to use storage appropriate to the context's usePrivateBrowsing attribute: if usePrivateBrowsing is true, temporary private-browsing storage is used, and
otherwise permanent storage is used. A context can be obtained from the window or channel whose content pertains to the preferences being modified or retrieved. Callbacks The methods of callback objects are always called asynchronously. See nsIContentPrefCallback2 for more information about callbacks. Method overview void addObserverForName(in AString name, in nsIContentPrefObserver observer...
nsIContentViewer
ng by firing beforeunload on the document, and if it does, prompts the user. The result is returned. boolean permitUnload( in boolean aCallerClosesWindow Optional ); Parameters aCallerClosesWindow Optional Indicates that the current caller will close() the window. If the method returns true, all subsequent calls will be ignored. Return value true if the document will allow unloading;
otherwise false. requestWindowClose() boolean requestWindowClose(); Parameters None. Return value Missing Description Exceptions thrown Missing Exception Missing Description resetCloseWindow() Works in tandem with permitUnload(), if the caller decides not to close() the window it indicated it will, it is the caller's responsibility to reset that with this method. Note: @Note this method is only ...
nsICookie
Attributes Attribute Type Description expires PRUint64 Expiration time in seconds since midnight (00:00:00), January 1, 1970 UTC. expires = 0 represents a session cookie. expires = 1 represents an expiration time earlier than Jan 1, 1970. Read only. host AUTF8String The host (possibly fully qualified) of the cookie. Read only. isDomain boolean true if the cookie is a domain cookie, false
otherwise. Read only. isSecure boolean true if the cookie was transmitted over ssl, false
otherwise. Read only. name ACString The name of the cookie. Read only. path AUTF8String The path pertaining to the cookie. Read only. policy nsCookiePolicy Holds the sites compact policy value. Read only. status nsCookieStatus Holds the P3P status of cookie. Read only. value ACString The cookie value. Read...
nsICookieManager2
ice is the normal way to do this. This method is something of a back door. void add( in AUTF8String aHost, in AUTF8String aPath, in ACString aName, in ACString aValue, in boolean aIsSecure, in boolean aIsHttpOnly, in boolean aIsSession, in PRInt64 aExpiry ); Parameters aHost The host or domain for which the cookie is set. presence of a leading dot indicates a domain cookie;
otherwise, the cookie is treated as a non-domain cookie. See RFC2109 for details. The host string will be normalized to ASCII or ACE; any trailing dot will be stripped. To be a domain cookie, the host must have at least two subdomain parts (e.g. '.foo.com', not '.com'),
otherwise an exception will be thrown. An empty string is acceptable (e.g. file:// URI's). aPath The path within the domain for which th...
nsIDOMEventGroup
See also Document Object Model (DOM) Level 3 Events Specification ...
nsIDOMMouseScrollEvent
t occurred, in screen coordinates. screenYArg The Y coordinate at which the event occurred, in screen coordinates. clientXArg The X coordinate at which the event occurred, in client coordinates. clientYArg The Y coordinate at which the event occurred, in client coordinates. ctrlKeyArg true if the control key was down when the event occurred,
otherwise false. altKeyArg true if the Alt key was down when the event occurred,
otherwise false. shiftKeyArg true if the shift key was down when the event occurred,
otherwise false. metaKeyArg true if the meta key was down when the event occurred,
otherwise false. buttonArg Indicates which mouse button was pressed when the event occurred, if any. ...
nsIDOMOfflineResourceList
add to the list. mozHasItem Returns a Boolean value indicating whether or not the specified URI represents a resource that's in the application cache's list. Note: This method has been deprecated. You should use the mozItems attribute instead. void mozHasItem( in DOMString uri ); Parameters uri The URI of the resource to check. Return value true if the resource is in the list,
otherwise false. mozItem Returns the URI of the item at the specific offset into the list of cached resources. Note: This method is deprecated in Firefox 3.5; you should instead access the list directly using the items attribute. DOMString mozItem( in unsigned long index ); Parameters index The index of the cached item whose URI should be returned. Return value An DOMString containing the...
nsIDOMProgressEvent
adedArg, in unsigned long long totalArg ); Parameters typeArg The type of event. Must be one of "abort", "error", "load", "loadstart", or "progress". canBubbleArg Specifies whether or not the created event will bubble. cancelableArg Specifies whether or not the created event can be canceled. lengthComputableArg If the size of the data to be transferred is known, this should be true.
Otherwise, specify false. loadedArg The number of bytes already transferred. Must be a non-negative value. totalArg The total number of bytes to be transferred. If lengthComputable is false, this must be zero. See also Using XMLHttpRequest XMLHttpRequest nsIXMLHttpRequestEventTarget nsIXMLHttpRequest ...
nsIDOMStorageEventObsolete
torage area which changed, or "#session" if the event represents a change to session storage. Read only. Methods initStorageEvent() Initializes a storage event. void initStorageEvent( in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in DOMString domainArg ); Parameters typeArg The type argument. canBubbleArg true if the event is allowed to bubble,
otherwise false. cancelableArg true if the event can be canceled,
otherwise false. domainArg The domain to which the event belongs, or "#session" if the event is associated with session storage. See also Storage StorageEvent Structured client-side storage (HTML 5 specification) nsIDOMStorageItem ...
getFile
test list. Available on all platforms These symbolic names are available on all platforms (although, of course, they may refer to different physical paths on the storage device). C constant String value Notes NS_OS_HOME_DIR "Home" NS_OS_TEMP_DIR "TmpD" NS_OS_CURRENT_WORKING_DIR "CurWorkD" NS_OS_DESKTOP_DIR "Desk"
otherwise same as Home NS_OS_CURRENT_PROCESS_DIR "CurProcD" NS_XPCOM_CURRENT_PROCESS_DIR "XCurProcD" can be overriden by passing a "bin directory" to NS_InitXPCOM2(). NS_XPCOM_COMPONENT_DIR "ComsD" NS_XPCOM_COMPONENT_DIR_LIST "ComsDL" NS_XPCOM_COMPONENT_REGISTRY_FILE "ComRegF" NS_XPCOM_XPTI_REGISTRY_FILE "XptiReg...
nsIDownloadManagerUI
Read only. Constants Constant Value Description REASON_USER_INTERACTED 0 When opening the Download Manager user interface, this value indicates that it's being done at the user's request. REASON_NEW_DOWNLOAD 1 When opening the Download Manager user interface, this value indicates that the user interface is being displayed because a new d...
nsIDownloader
Methods init() Initialize this downloader. void init( in nsIDownloadObserver observer, in nsIFile downloadLocation ); Parameters observer The nsIDownloadObserver to be notified when the download completes. downloadLocation The location where the stream contents should be written. If null, the downloader will select a location and the resulting file will be deleted (or
otherwise made invalid) when the downloader object is destroyed. If an explicit download location is specified then the resulting file will not be deleted, and it will be the callers responsibility to keep track of the file, and so on. ...
nsIDragSession
a given data flavor. If numDropItems is greater than one, there is no indication as to which of the items matches the data flavor. boolean isDataFlavorSupported( in string aDataFlavor ); Parameters aDataFlavor A string representing the MIME type of the data to be matched, such as "text/unicode". Return value true if the specified flavor matches any of the native data on the clipboard,
otherwise false. ...
nsIDroppedLinkHandler
tion dropLink() Given a drop event, determines the link being dragged. If a uri is returned the caller can, for instance, load it. If null is returned, there is no valid link to be dropped. AString dropLink( in nsIDOMDragEvent aEvent, out AString aName, [optional] in boolean aDisallowInherit ); Parameters aEvent A drop event. aName The link title if it exists, or an empty string
otherwise. Return value A uri, or null if there is no valid link to be dropped. Exceptions thrown NS_ERROR_DOM_SECURITY_ERR Error will be thrown and the event canceled if the receiving target should not load the uri for security reasons. This will occur if the source of the drag initiated a link for dragging that it itself cannot access. This prevents a source document from tricking the user into a...
nsIEditor
ified boolean Read only. Returns true if the document is modifed and needs saving. flags unsigned long Edit flags for this editor. May be set at any time. isDocumentEditable PRBool Read only. Returns true if we have a document that is not marked read-only. isSelectionEditable boolean Read only. true if the current selection anchor is editable;
otherwise false. This helps to support cases where only parts of the document are editable, by letting you see if the current selection is in an editable section. rootElement nsIDOMElement Read only. The root editable element, which for a document is its body. selection nsISelection Read only. The selection/caret for this editor. In the case of a design mode document, this is...
nsIEventListenerInfo
in the system event group. Read only. type AString The type of the event for which the listener was added. Read only. Methods getDebugObject() Returns the debugger object if the debug service is active. nsISupports getDebugObject(); Parameters None. Return value If jsdIDebuggerService is active and the listener is implemented in JS, this returns the listener as a jsdIValue.
Otherwise null. This is the method you should use if you want to get access to the actual listener, but the debugger service must be already active, which significantly slows down script execution. Accordingly, this should probably only be used by real debuggers. This approach is necessary because event listeners added with addEventListener won't necessarily be nsIEventListeners; the DOM code will fix up o...
nsIExternalHelperAppService
d to helper applications. boolean applyDecodingForExtension( in AUTF8String aExtension, in ACString aEncodingType ); Parameters aExtension The filename extension to check. aEncodingType The encoding type to check. Return value true if data from URLs with the specified extension and encoding should be decoded prior to saving the file or delivering it to a helper application;
otherwise false. doContent() Binds an external helper application to a stream listener. The caller should pump data into the returned stream listener. When the OnStopRequest is issued, the stream listener implementation will launch the helper app with this data. nsIStreamListener doContent( in ACString aMimeContentType, in nsIRequest aRequest, in nsIInterfaceRequestor aWindowContext, in boolean aFo...
nsIFocusManager
rtElement aType aFlags Return value The element that was focused. setFocus() Changes the focused element reference within the window containing aElement to aElement. void setFocus( in nsIDOMElement aElement, in unsigned long aFlags ); Parameters aElement aFlags Native code only!windowHidden Called when a document in a window has been hidden or
otherwise can no longer accept focus. void windowHidden( in nsIDOMWindow aWindow ); Parameters aWindow Native code only!windowLowered Called when a window has been lowered. void windowLowered( in nsIDOMWindow aWindow ); Parameters aWindow Native code only!windowRaised Called when a window has been raised. void windowRaised( in nsIDOMWindow aWindow ); Parameters aWindow...
nsIFrameScriptLoader
ager or a window message manager) then: loadFrameScript() will load the frame script independently into each applicable frame: every open frame in the given window for the window message manager, or every frame in every window for the global message manager if aAllowDelayedLoad is true, then the script will also be loaded into any applicable new frames opened after the loadFrameScript() call.
Otherwise it will only be loaded into frames that exist at the time of the call. If this function is called on a ChromeMessageSender: it will load the frame script only into this ChromeMessageSender's frame aAllowDelayedLoad should always be true. It's possible that the frame for this ChromeMessageSender is not yet available at the time of the loadFrameScript() call, and if you pass false in this sit...
nsIGeolocationProvider
ce Gecko 1.9.2 void shutdown(); void startup(); void watch(in nsIGeolocationUpdate callback); Methods isReady() Obsolete since Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Reports whether or not the device is ready and has a position. boolean isReady(); Parameters None. Return value true if the device is ready and has a position available to return;
otherwise false. shutdown() Shuts down the location device. void shutdown(); Parameters None. startup() Start up the provider. This is called before any other method and may be called multiple times. void startup(); Parameters None. watch() Attaches a callback listener to be notified when a location change is observed. void watch( in nsIGeolocationUpdate callback ); Parameters callback An nsIGeolocat...
nsIGlobalHistory3
koFlags(in nsIURI aURI, in unsigned long aFlags); Methods addDocumentRedirect() Notifies the history system that the page loading via aOldChannel redirected to aNewChannel. Implementations should generally add the URI for aOldChannel to history for link coloring, but are advised not to expose it in the history user interface. This function is preferred if nsIGlobalHistory3 is available.
Otherwise, nsIGlobalHistory2.addURI() should be called with redirect=true. This function is preferred to nsIGlobalHistory2.addURI() because it provides more information (including the redirect destination, channels involved, and redirect flags) to the history implementation. For implementors of nsIGlobalHistory3: The history implementation is responsible for sending NS_LINK_VISITED_EVENT_TOPIC to observers...
nsIHttpActivityObserver
If this is false, the observeActivity() method should not be called. Read only. Note: This attribute is present only for compatibility and should not be used. Constants Activity type constants Constant Value Description ACTIVITY_TYPE_SOCKET_TRANSPORT 0x0001 Socket transport activity has occurred. ACTIVITY_TYPE_HTTP_TRANSACTION 0x0002 HTTP transport activity has occurred. Act...
nsIHttpChannel
f the server sent the equivalent of a "Cache-control: no-cache" response header. Equivalent response headers include: "Pragma: no-cache", "Expires: 0", and "Expires" with a date value in the past relative to the value of the "Date" header. boolean isNoCacheResponse(); Parameters None. Return value Returns true if the server sent the equivalent of a "Cache-control: no-cache" response header,
otherwise false. Exceptions thrown NS_ERROR_NOT_AVAILABLE If called before the response has been received (before onStartRequest()). isNoStoreResponse() boolean isNoStoreResponse(); Parameters None. Return value true if the server sent a "Cache-Control: no-store" response header. Exceptions thrown NS_ERROR_NOT_AVAILABLE If called before the response has been received (before onStartReques...
nsIIOService
rotocol handler ultimate control over its own security policy while ensuring reasonable, default protection. Is similar to nsIProtocolHandler.allowPort(). boolean allowPort( in long aPort, in string aScheme ); Parameters aPort The port to check aScheme The scheme for the protocol handler that could override the IOService's decision. Return value true if the port is allowed, false
otherwise. extractScheme() Utility to extract the scheme from a URL string, consistently and according to spec (see RFC 3986). Note: Most URL parsing is done via nsIURI, and in fact the scheme can also be extracted from a URL string via nsIURI. This method is provided purely as an optimization. ACString extractScheme( in AUTF8String urlString ); Parameters urlString The string for the URL to ...
nsIJSON
OutputStream stream, in string charset, in boolean writeBOM in JSObject value ); Parameters stream The nsIOutputStream to which to write the JSON string. charset The string encoding to use. Only the five Unicode encodings "UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32LE" and "UTF-32BE" are supported. writeBOM Specify true if you wish to write a byte-order mark (BOM) into the stream,
otherwise specify false. value The JavaScript object to encode. legacyDecode() Decodes a JSON string. This method accepts slightly more than the exact JSON syntax; details of extra accepted syntax are deliberately not described. This method is intended for use only by code processing legacy data. When the original instance requiring this function is removed, this method will be removed. Thus, this...
nsILivemarkService
a livemark container. NS_ERROR_MALFORMED_URI If the site URI annotation has somehow been corrupted (and can't be turned into an nsIURI) isLivemark() This method determines whether the folder with the given folder ID identifies a livemark container. boolean isLivemark( in long long folder ); Parameters folder A folder ID. Return value true if the given folder is a livemark folder,
otherwise it returns false. Exceptions thrown NS_ERROR_INVALID_ARG If the folder ID isn't known. reloadAllLivemarks() This method reloads all livemark subscriptions, whether or not they have expired. void reloadAllLivemarks(); Parameters None. reloadLivemarkFolder() This method reloads the livemark with this folder ID, whether or not it's expired. void reloadLivemarkFolder( in long long fo...
nsILoginManagerStorage
d() Implement to report whether or not login saving has been disabled for a specific host. boolean getLoginSavingEnabled( in AString aHost ); Parameters aHost The hostname whose login saving status should be returned. This string will be in the origin URL format, without a pathname. For example, "http://mozilla.com". Return value Return true if login saving is enabled for the specified host;
otherwise, return false. init() Implement this method to initialize the component. This is not called automatically; you must call it yourself if needed. void init(); Parameters None. initWithFile() Implement this method to initialize the component, overriding the default filename locations with those specified. This method is primarily used for unit tests and during profile migration. void initWithFile( ...
nsIMenuBoxObject
rfaces.nsIMenuBoxObject); Method overview boolean handleKeyPress(in nsIDOMKeyEvent keyEvent); void openMenu(in boolean openFlag); Attributes Attribute Type Description activeChild nsIDOMElement The currently active menu or menuitem child of the menu box. openedWithKey boolean true if the menubar was opened using the keyboard;
otherwise false. Note: For Gecko 2.0, the openedWithKey attribute exists on the nsIMenuBoxObject_MOZILLA_2_0_BRANCH interface. Subsequent Gecko versions will have the attribute on the nsIMenuBoxObject interface. Methods handleKeyPress() boolean handleKeyPress( in nsIDOMKeyEvent keyEvent ); Parameters keyEvent The key event to handle for the menu. Return value true if the event was hand...
nsIMessageListener
ager itself if no element owns it. If the message was sent from a frame script using a nsIContentFrameMessageManager, then this property is the XUL <browser> element for the frame from which the message was sent. name The message name. This is the first argument passed into the message-sending function. sync True if the message was sent using sendSyncMessage, false
otherwise. data A structured clone of the message payload: the second argument passed into the message-sending function. json Same as data. Deprecated. objects An object whose properties are any cross process object wrappers exposed by the sender as the third argument to the message-sending function. principal Principal for the window app. Each listener...
nsIMicrosummaryService
bookmarkID, in nsIMicrosummary microsummary ); Parameters bookmarkID The bookmark to check. microsummary The microsummary to check. Return value Returns whether or not the microsummary is the current one for the bookmark. refreshMicrosummary() Refreshes a microsummary, updating its value in the datastore and UI. If this method can refresh the microsummary instantly, it will.
Otherwise, it'll asynchronously download the necessary information (the generator and/or page) before refreshing the microsummary. Callers should check the content property of the returned microsummary object to distinguish between sync and async refreshes. If its value is null, then it's an async refresh, and the caller should register itself as an nsIMicrosummaryObserver via nsIMicrosummary.addObserver()...
nsIMsgCustomColumnHandler
e with. getSortLongForRow() If the column displays a number, this will return the number that the column should be sorted by. unsigned long getSortLongForRow(in nsIMsgDBHdr aHdr); Parameters aHdr The message's nsIMsgDBHdr. Return value The long value that sorting will be done with. isString() boolean isString(); Parameters None. Return value true if the column displays a string value. false
otherwise. This affects whether getSortStringForRow or getSortLongForRow is used to determine the sort key for the column. It does not affect whether getCellText vs. getImageSrc is used to determine what to display. See Also Extensions:Thunderbird:Creating_a_Custom_Column ...
nsIMsgDatabase
in string aProperty, in string aValue); MarkImapDeleted() void MarkImapDeleted(in nsMsgKey key, in boolean deleted, in nsIDBChangeListener instigator); applyRetentionSettings() Purge unwanted message headers and/or bodies. If deleteViaFolder is true, we'll call nsIMsgFolder.DeleteMessages() to delete the messages.
Otherwise, we'll just delete them from the db. void applyRetentionSettings(in nsIMsgRetentionSettings aMsgRetentionSettings, in boolean aDeleteViaFolder); HasNew() boolean HasNew(); ClearNewList() void ClearNewList(in boolean notify); AddToNewList() void AddToNewList(in nsMsgKey key); StartBatch() Batching - can be used to cache file stream for local mail, and perhaps t...
nsIMsgFilterCustomAction
, in nsIMsgFolder actionFolder, in nsMsgFilterTypeType filterType); /* allow duplicate actions in the same filter list? Default No. */ attribute boolean allowDuplicates; /* * The custom action itself * * Generally for the apply method, folder-based methods give correct * results and are preferred if available.
Otherwise, be careful * that the action does correct notifications to maintain counts, and correct * manipulations of both IMAP and local non-database storage of message * metadata. */ /** * Apply the custom action to an array of messages * * @param msgHdrs array of nsIMsgDBHdr objects of messages * @param actionValue user-set value to use in the action * @param copyList...
nsINavHistoryQuery
LTS_AS_URI since there will be no visits for these items. beginTime PRTime Begin time range for results (INCLUSIVE). beginTimeReference long One of the constants TIME_RELATIVE_* which indicates how to interpret the corresponding begin time value. domain AUTF8String This is the host or domain name (controlled by domainIsHost). When domainIsHost, domain only does exact matching on host names.
Otherwise, it will return anything whose host name ends in domain. This one is a little different than most. Setting it to an empty string is a real query and will match any URI that has no host name (local files and such). Set this to NULL (in C++ use SetIsVoid) if you don't want domain matching. domainIsHost boolean This controls the meaning of domain, and whether it is an exact match domainIsHost = t...
nsINavHistoryQueryResultNode
e will report that it has no children and will never try to populate itself. Method overview void getQueries([optional] out unsigned long queryCount, [retval,array,size_is(queryCount)] out nsINavHistoryQuery queries); Attributes Attribute Type Description folderItemId long long For both simple folder nodes and simple-folder-query nodes, this is set to the concrete itemId of the folder.
Otherwise, this is set to -1. Read only. queryOptions nsINavHistoryQueryOptions The options that group the node's children; only valid for RESULT_TYPE_QUERY nodes. Read only. Methods getQueries() Returns the queries that build the node's children; only valid for RESULT_TYPE_QUERY nodes. void getQueries( out unsigned long queryCount, Optional from Gecko 2.0 [retval,array,size_is(queryCount)] out...
nsINavHistoryResultNode
to which this node belongs. Read only. propertyBag nsIWritablePropertyBag You can use this to associate temporary information with the result node. This property bag is associated with the result node and is not persisted in any way. Read only. Obsolete since Gecko 2.0 tags AString For uri nodes, this is a sorted list of the tags, delimited with commans, for the uri represented by this node.
Otherwise this is an empty string. Read only. time PRTime The time at which the user accessed the page. Read only. For visits, this is the exact time at which the page visit occurred. For URIs, this is the most recent time at which the URI was visited. Even if you ask for all URIs for a given date range long ago, this might contain today's date if the URI was visited today. For hosts, or other node types...
nsINavHistoryResultTreeViewer
his value is somewhat heavyweight since it will force a tree refresh. Obsolete since Gecko 1.9 flatItemCount PRUint32 This tells you how many items are in the flattened list of results, that is how many rows are in this tree right now. The tree adaptor will also QI to nsITreeView, and this will be the same as nsITreeView.rowCount. This is only valid when a tree is attached, the result will be 0
otherwise. Read only. Obsolete since Gecko 1.9 Constants Constant Value Description INDEX_INVISIBLE 0xffffffff Returned by treeIndexForNode() when the requested node isn't visible (such as when its parent is collapsed). Also returned if there is no tree attached. Methods nodeForTreeIndex() Returns the node for a given row index. This is only valid when a tree is attached. nsINavHistoryResultNode...
nsINavHistoryService
this, addPageToSession/addURI will always check before actually adding the page. This function is public because some components may want to check if this page would go in the history (That is for annotations). boolean canAddURI( in nsIURI aURI ); Parameters aURI The URI that needs to be added to the history system. Return value Returns true if this URI would be added to the history,
otherwise returns false. addVisit() Obsolete since Gecko 22.0 (Firefox 22.0 / Thunderbird 22.0 / SeaMonkey 2.19) Note: This method was removed in Gecko 22.0. You should use the new async API mozIAsyncHistory.updatePlaces() instead. See this code for how a function to add visits and handle errors using the new API could look like. This method adds a visit for a specific page. ...
nsIObserverService
Observer anObserver, in string aTopic, in boolean ownsWeak ); Parameters anObserver The nsIObserver object which will receive notifications. aTopic The notification topic or subject. ownsWeak If set to false, the nsIObserverService will hold a strong reference to anObserver. If set to true and anObserver supports the nsISupportsWeakReference interface, a weak reference will be held.
Otherwise an error will be returned. (In most cases, you should use false.) enumerateObservers() Called to enumerate all observers registered for a particular topic. nsISimpleEnumerator enumerateObservers( in string aTopic ); Parameters aTopic The notification topic or subject. Return value Returns an enumeration of all registered listeners. See nsISimpleEnumerator. notifyObservers() This ...
Component; nsIPrefBranch
prefIsLocked( in string aPrefName ); Parameters aPrefName The preference to be tested. Return value Returns boolean - true The preference is locked. false The preference is not locked. removeObserver() Remove a preference change observer. Note: You must call removeObserver method on the same nsIPrefBranch instance on which you called addObserver method in order to remove aObserver;
otherwise, the observer will not be removed. void removeObserver( in string aDomain, in nsIObserver aObserver ); Parameters aDomain The preference which is being observed for changes. aObserver An observer previously registered with addObserver. resetBranch() Called to reset all of the preferences referenced by this branch to their default values. Note: This method can be called ...
nsIPrefBranch2
changes. aHoldWeak true holds a weak reference to aObserver. The object must implement the nsISupportsWeakReference interface or this will fail. false holds a strong reference to aObserver. removeObserver() Remove a preference change observer. Note: You must call removeObserver method on the same nsIPrefBranch2 instance on which you called addObserver() method in order to remove aObserver;
otherwise, the observer will not be removed. void removeObserver( in string aDomain, in nsIObserver aObserver ); Parameters aDomain The preference which is being observed for changes. aObserver An observer previously registered with addObserver. Remarks Registering as a preference observer can open an object to potential cyclical references which will cause memory leaks. These cyc...
nsIPrefService
d readUserPrefs(in nsIFile aFile); void resetPrefs(); void resetUserPrefs(); void savePrefFile(in nsIFile aFile); Methods getBranch() Call to get a Preferences "Branch" which accesses user preference data. Using a Set method on this object will always create or set a user preference value. When using a Get method a user set value will be returned if one exists,
otherwise a default value will be returned. nsIPrefBranch getBranch( in string aPrefRoot ); Parameters aPrefRoot The preference root tree on which to base this branch. For example, if the root browser.startup. is used, the branch will be able to easily access the preferences browser.startup.page, browser.startup.homepage, and browser.startup.homepage_override by simply requesting page, homepage, o...
nsIProcess
ync([array, size_is(count)] in wstring args, in unsigned long count, [optional] in nsIObserver observer, [optional] in boolean holdWeak); Attributes Attribute Type Description exitValue long The value returned by the process upon exit. This is only valid after the process has exited. Read only. isRunning boolean true if the process is running,
otherwise false. Only accurate if the process was run with blocking disabled. Read only. location nsIFile The location of the executable file on disk. Read only. Gecko 1.9.1 note This attribute is no longer implemented as of Gecko 1.9.1, and is removed entirely in Gecko 1.9.2. pid unsigned long The process ID of the process. This value is only available af...
nsIProcessScriptLoader
s(); loadProcessScript() Load a script in the child process. Process scripts are loaded as soon as loadProcessScript() is called. If this function is called on a ChromeMessageBroadcaster, : it will load the process script into all child processes. if aAllowDelayedLoad is true, then the script will also be loaded into any new child processes created after the loadProcessScript() call.
Otherwise it will only be loaded into child processes that exist at the time of the call. If this function is called on a ChromeMessageSender: it will load the process script only into this ChromeMessageSender's child process aAllowDelayedLoad should always be true. It's possible that the child process for this ChromeMessageSender is not yet available at the time of the loadProcessScript() call, and ...
nsIProfile
in boolean useExistingDir ); Parameters profileName The name to assign to the new profile. nativeProfileDir The pathname of the directory to use as the profile directory; if you specify null, a new folder will be created in the default profiles directory. langcode The locale to use for the new profile. useExistingDir If true, an existing directory may be used;
otherwise, the profile directory will be unique. deleteProfile() Deletes the specified profile. void deleteProfile( in wstring name, in boolean canDeleteFiles ); Parameters name The name of the profile to delete. canDeleteFiles If true, the Profile Manager will try to delete all of the profile's files and its directory. getProfileList() Returns an array of strings indicating the nam...
nsIScriptableUnescapeHTML
Fragment(fragment, 0, isXML, baseURI, element). You should call nsIParserUtils::parseFragment() instead of calling this method. nsIDOMDocumentFragment parseFragment( in AString fragment, in PRBool isXML, in nsIURI baseURI, in nsIDOMElement element ); Parameters fragment A string of HTML or XML source to parse as a fragment. isXML Set this to true if the fragment is an XML string;
otherwise set it to false. baseURI Pointer to the base URI against which to resolve any URIs included in the fragment. This parameter is ignored if isXML is false. element The nsIDOMElement to be used as the context node for the purposes of the fragment parsing algorithm. Return value An nsIDOMDocumentFragment of the element with the new text appended. Exceptions thrown NS_ERROR_FAILURE Unable ...
nsISearchEngine
on the application's installed search engines. Return value An nsISearchSubmission supportsResponseType() Determines whether the engine can return responses in the given MIME type. boolean supportsResponseType( in AString responseType ); Parameters responseType The MIME type to check for. Return value Returns true if the engine spec has a URL with the given responseType, false
otherwise. See also nsISearchSubmission nsIBrowserSearchService ...
nsIServerSocket
ork address to which the socket is bound. init() Initializes a server socket. void init( in long aPort, in boolean aLoopbackOnly, in long aBackLog ); Parameters aPort The port of the server socket. Pass -1 to indicate no preference, and a port will be selected automatically. aLoopbackOnly If true, the server socket will only respond to connections on the local loopback interface.
Otherwise, it will accept connections from any interface. To specify a particular network interface, use initWithAddress(). aBackLog The maximum length to which the queue of pending connections may grow. This parameter may be silently limited by the operating system. Pass -1 to use the default value. The default value is 5. Native code only!initWithAddress This method initializes a server socket and b...
nsISessionStartup
The previous session should be restored at startup. DEFER_SESSION 3 The previous session is viable but shouldn't be restored without explicit action (with the exception of app tabs, which are always restored in this case). Methods doRestore() Determines whether or not there is a session to restore. boolean doRestore(); Parameters None. Return value true if the session should be restored,
otherwise false. ...
nsISocketTransport
e timeout type, who's associated value should be retrieved. Can be one of the constants TIMEOUT_CONNECT or TIMEOUT_READ_WRITE. Return value Returns the timeout in seconds for the given Type. A value of PR_UINT32_MAX is equivalent to no timeout. isAlive() Test if this socket transport is (still) connected. boolean isAlive(); Parameters None. Return value Returns true if the socket is connected.
Otherwise false. setTimeout() Sets a Socket timeout. void setTimeout( in unsigned long aType, in unsigned long aValue ); Parameters aType The timeout type which should be set to aValue. Can be one of the constants TIMEOUT_CONNECT or TIMEOUT_READ_WRITE. aValue Defines the timeout in seconds, pass PR_UINT32_MAX to specify no timeout. The implementation may truncate timeout v...
nsIStandardURL
URL string matches this port, then the port will be removed from the canonical form of the URL. aSpec URL string. aOriginCharset The charset from which this URI string originated. this corresponds to the charset that should be used when communicating this URI to an origin server, for example. if null, then provide aBaseURI implements this interface, the origin charset of aBaseURI will be assumed,
otherwise defaulting to UTF-8 (that is, no charset transformation from aSpec). aBaseURI If null, aSpec must specify an absolute URI.
Otherwise, aSpec will be resolved relative to aBaseURI. See also nsIURL ...
nsITraceableChannel
face is used to allow intercepting of HTTP traffic. It is implemented by nsIHttpChannel. 1.0 66 Introduced Gecko 1.9.0.4 Inherits from: nsISupports Last changed in Gecko 1.9.0.4 The typical way to use this interface is as follows: Register for the "http-on-examine-response" notification to track all HTTP responses; Skip redirects (responseStatus = 3xx on nsIHttpChannel), since
otherwise you may end up with two listeners registered for a channel; QI the channel passed as the "subject" to your observer to nsITraceableChannel, and replace the default nsIStreamListener (that passes the data to the original requester - e.g. to XMLHttpRequest or to the browser tab that made the request) with your own implementation (see "Implementing nsIStreamListener" below). After that your nsISt...
nsITransferable
uestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsILoadContext); In C++ callers, if you have the corresponding document, you can just call nsIDocument.GetLoadContext() to get to the load context object. isLargeDataSet() Returns true if the data is large. boolean isLargeDataSet(); Parameters None. Return value true if the data is large;
otherwise, the result is false. removeDataFlavor() Removes the data flavor matching the given one (as determined by a string comparison), along with the corresponding data. void removeDataFlavor( in string aDataFlavor ); Parameters aDataFlavor The data flavor to remove. setTransferData() Sets the data in the transferable with the specified flavor. The transferable maintains its own copy of th...
nsITreeBoxObject
the number of rows added or removed. Use negative values for removed rows. Example You deleted the row with index rowIndex. Inform the tree about this change by calling rowCountChanged(rowIndex+1, -1); beginUpdateBatch() Notify the tree that the view is about to perform a batch update, that is, add, remove or invalidate several rows at once. This must be followed by calling endUpdateBatch(),
otherwise the tree will get out of sync. void beginUpdateBatch(); endUpdateBatch() Notify the tree that the view has completed a batch update. void endUpdateBatch(); clearStyleAndImageCaches() Called on a theme switch to flush out the tree's style and image caches. void clearStyleAndImageCaches(); Other references Tree Widget Changes (applies to Gecko 1.8.0 and later) XUL Tutorial:Tree Box Sorti...
nsIUTF8StringEnumerator
any strings that can be returned via getNext(). This method is generally used to determine whether or not to initiate or continue iteration over the enumerator, athough it can be called without subsequent getNext() calls. Calling this method doesn't affect the internal state of the enumerator. boolean hasMore(); Parameters None. Return value true if there are remaining strings in the enumerator,
otherwise false. ...
nsIVariant
Violates the XPCOM interface guidelines getAsID() nsresult getAsID( out nsID retval ); Parameters retval If the internal value is an IID then it is returned. If it is of type interface pointer then then IID of the pointer is returned. If it is of string type then an attempt is made to convert the string to an IID. Return value If the conversion succeeds, NS_OK is returned,
otherwise NS_ERROR_CANNOT_CONVERT_DATA is returned. Native code only!getAsInt16 PRInt16 getAsInt16(); Parameters None. Return value If the internal value is a string, it is first converted to a double, if possible. If it within the numeric limits of a PRInt16 then the value is returned. Native code only!getAsInt32 PRInt32 getAsInt32(); Parameters None. Return value If the internal value is a string, it i...
nsIWebBrowser
parentURIContentListener nsIURIContentListener URI content listener parent. The embedder may set this property to their own implementation if they intend to override or prevent how certain kinds of content are loaded. Note: If this attribute is set to an object that implements nsISupportsWeakReference, the implementation should get the nsIWeakReference and hold that.
Otherwise, the implementation should not refcount this interface; it should assume that a non null value is always valid. In that case, the embedder should explicitly set this value back to null if the parent content listener is destroyed before the browser object. Methods addWebBrowserListener() Registers a listener of the type specified by the iid to receive callbacks. The browser stores a weak ref...
nsIWebBrowserChrome3
e target for a link. AString onBeforeLinkTraversal( in AString originalTarget, in nsIURI linkURI, in nsIDOMNode linkNode, in PRBool isAppTab ); Parameters originalTarget The original link target. linkURI Link destination URI. linkNode Link DOM node. isAppTab Whether or not the link is in an application tab. Return value A new link target, if appropriate.
Otherwise returns originalTarget. See also nsIWebBrowserChrome2 ...
nsIWebContentHandlerRegistrar
er Summary of registerProtocolHandler void registerProtocolHandler( in DOMString protocol, in DOMString uri, in DOMString title, in nsIDOMWindow contentWindow ); Parameters protocol The protocol the site wishes to handle, specified as a string. uri The URI to the handler as a string. You must include "%s" to indicate where to insert the escaped URI of the document to be handled.
Otherwise NS_ERROR_DOM_SYNTAX_ERR will be thrown. This string must also be of either the http or https schemes. title The title of the handler presented to the user as a string. contentWindow The DOM content window from which the method has been called. Note: Script must execute from same domain as uri or else it will throw permission error. Can bypass this by opening about:config and setting prefer...
nsIWebNavigationInfo
rder to ensure they are properly registered for the types they support. unsigned long isTypeSupported( in ACString aType, in nsIWebNavigation aWebNav ); Parameters aType The MIME type to check. aWebNav The nsIWebNavigation object on which to check for compatibility. You may specify null to check for compatibility with nsIWebNavigation objects that are in their default state;
otherwise, the result is determined based on the configuration of the specified object (that is, how it is configured by using nsIWebBrowserSetup). Return value Returns one of the Support type constants, indicating whether or not the specified MIME type is supported, and in what form that support exists. Example let webnavigationinfo_service = Components.classes["@mozilla.org/webnavigation-info;1"] ...
nsIWebProgressListener
ECURE_LOW. Security strength flags These flags describe the security strength and accompany STATE_IS_SECURE in a call to the onSecurityChange() method. These flags are mutually exclusive. These flags are not meant to provide a precise description of data transfer security. These are instead intended as a rough indicator that may be used to, for example, color code a security indicator or
otherwise provide basic data transfer security feedback to the user. Constant Value Description STATE_SECURE_HIGH 0x00040000 This flag indicates a high degree of security. STATE_SECURE_MED 0x00010000 This flag indicates a medium degree of security. STATE_SECURE_LOW 0x00020000 This flag indicates a low degree of security. State identity fla...
nsIWinAppHelper
void postUpdate(in nsILocalFile logFile); Obsolete since Gecko 1.9.2 Attributes Attribute Type Description userCanElevate boolean Read only. Returns true only if all the following conditions are all true at once: The operating system is at least Windows Vista User Account Control is enabled The user is an Administrator The application is not already running with elevated permissions
Otherwise it returns false. Methods fixReg() Obsolete since Gecko 1.9 (Firefox 3) Invokes helper.exe with the /fixreg parameter. Note that this parameter was never actually supported. void fixReg(); Parameters None. postUpdate() Obsolete since Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Invokes helper.exe with the /postupdate parameter. ...
nsIWindowMediator
inWindow The window in question. inPosition Requested position one of the zLevel constants. zLevelTop send the window to the top window, zLevelBottom to the bottom. If set to zLevelBelow the window will be placed below ioBelow. The value of inBelow will be ignored for zLevelTop and zLevelBottom.) inBelow If inPosition is set to zLevelBelow, the window below which inWindow wants to be placed.
Otherwise this variable is ignored. outPosition Constrained position, values like inPosition. outBelow The window below which inWindow should be placed, if outPosition equals zLevelBelow.
Otherwise this value will be null. Return value PR_TRUE if the position returned is different from the position given. getEnumerator() Return an enumerator which iterates over all windows of type aWindowType from...
nsIXSLTProcessor
IDOMDocumentFragment transformToFragment(in nsIDOMNode source, in nsIDOMDocument output); Methods clearParameters() Removes all set parameters from this nsIXSLTProcessor. This will make the processor use the default-value for all parameters as specified in the stylesheet. void clearParameters(); Parameters None. getParameter() Gets a parameter if previously set by setParameter(). Returns null
otherwise. nsIVariant getParameter( in DOMString namespaceURI, in DOMString localName ); Parameters namespaceURI The namespaceURI of the XSLT parameter. localName The local name of the XSLT parameter. Return value An nsIVariant containing the value of the parameter. importStylesheet() Imports the specified stylesheet into this XSLTProcessor for transformations. void importStylesheet( in nsIDOMNode...
nsIXULTemplateBuilder
intended to be called only by the RDF query processor. If aTag is set, the content must have a tag name that matches aTag. aTag may be ignored for builders that don't generate real DOM content. boolean hasGeneratedContent( in nsIRDFResource aNode, in nsIAtom aTag ); Parameters aNode Node to check. aTag Tag that must match. Return value Returns true if the node has content generated for it;
otherwise returns false. addRuleFilter() Adds a rule filter for a given rule, which may be used for specialized rule filtering. Any existing filter on the rule is removed. The default conditions specified inside the <rule> tag are applied before the rule filter is applied, meaning that the filter may be used to further filter out results but not reaccept results that have already been rejected. void addRul...
nsIZipEntry
Description compression unsigned short The type of compression used for the item. The possible values and their meanings are defined in the zip file specification at ZIP Application Note Support. Read only. CRC32 unsigned long The CRC-32 hash of the file in the entry. Read only. isDirectory boolean True if the name of the entry ends with '/' and false
otherwise. Read only. isSynthetic boolean Use this attribute to determine whether this item is an actual zip entry or is one synthesized for part of a real entry's path. A synthesized entry represents a directory within the zip file which has no corresponding entry within the zip file. For example, the entry for the directory foo/ in a zip containing exactly one entry for foo/bar.txt is syn...
nsPIPromptService
number will be returned. eCheckboxState The value is 1. This is the default checkbox state and the result of it. eNumberButtons The value is 2. This is the number of the visible buttons on the dialog. eNumberEditfields The value is 3. This is the number of the visible text fields on the dialog. eEditField1Password The value is 4. If this value is 1, the first text field becomes a password field.
Otherwise, it's a normal edit field. Note that the second is always password field. eDefaultButton The value is 5. This is the button number which should be the default button on the dialog. eDelayButtonEnable The value is 6. If this is not 0, the all buttons are disabled when the dialog is shown. And they will be enabled later. eSoundEventId The value is 7. This is the sound event ID which should be play...
NS_IF_ADDREF
This page still needs some work, help to improve it! Summary Macro Addrefs the argument, if it is non-null. Does nothing for a null pointer. Only use this macro if the pointer might be NULL; use NS_ADDREF
otherwise. NS_IF_ADDREF(foo) is equal to if (foo) foo->AddRef(); Syntax NS_IF_ADDREF(foo); See Also NS_ADDREF ...
NS_IF_RELEASE
This page still needs some work, help to improve it! Summary Macro Decrements the reference count of a pointer by one. This macro also sets the pointer to NULL. NS_IF_RELEASE has no effect when the pointer is NULL. This macro should only be used when the pointer might be NULL;
otherwise, use NS_RELEASE. NS_IF_RELEASE is exactly equivalent to the following function: inline void NS_IF_RELEASE(nsISupports* foo) { if (foo) foo->Release(); foo = 0; } Syntax NS_IF_RELEASE(foo); See Also NS_ADDREF, NS_RELEASE ...
NS_CStringAppendData
tringAPI.h" nsresult NS_CStringAppendData( nsACString& aString, const char* aData, PRUint32 aDataLength = PR_UINT32_MAX ); Parameters aString [in] A nsACString instance to be modified. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null-terminated. Return Values The NS_CStringAppendData function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks This function is defined inline as a wrapper around NS_CStringSetDataRange. Example nsCStringContainer str; NS_CStringContainerInit(str); NS_CStringSetData(str, "hello"); NS_CStringAppendData(str, " world"); const char* data; NS_C...
NS_CStringContainerInit
<< XPCOM API Reference Summary The NS_CStringContainerInit function initializes a nsCStringContainer instance for use as a nsACString. #include "nsStringAPI.h" nsresult NS_CStringContainerInit( nsCStringContainer& aString ); Parameters aString [in] A nsCStringContainer instance to be initialized. Return Values The NS_CStringContainerInit function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks This function is equivalent to NS_CStringContainerInit2(container, nsnull, 0, 0). The nsCStringContainer structure has private members that should not be accessed directly. After a nsCStringContainer object has been initialized via NS_CStringContainerInit, it may be used as an ordinary nsACString object. With NS_CStringContainerInit, the coder is required to ...
NS_CStringContainerInit2
g takes ownership over the data pointer. The caller must have allocated the data array using the XPCOM memory allocator. This flag should not be combined with NS_CSTRING_CONTAINER_INIT_DEPEND. NS_CSTRING_CONTAINER_INIT_SUBSTRING Data passed into NS_CStringContainerInit2 is a substring that is not null-terminated. Return Values The NS_CStringContainerInit function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks After a nsCStringContainer object has been initialized via NS_CStringContainerInit2, it may be used as an ordinary nsACString object. When the string object is no longer needed, it should be passed to NS_CStringContainerFinish to free any extra memory that the string object may have allocated. It is generally better to use one of the helper classes, such as n...
NS_CStringCopy
from one nsACString instance to another. This is a low-level API. #include "nsStringAPI.h" nsresult NS_CStringCopy( nsACString& aDestString, const nsACString& aSrcString ); Parameters aDestString [in] A nsACString instance to be modified. aSrcString [in] A nsACString instance containing the new string value. Return Values The NS_CStringCopy function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks This function is designed to allow the implementation to efficiently assign the same value to two string objects. The implementation may employ reference counting techniques to optimize this operation. Example /* attribute ACString value; */ NS_IMETHODIMP MyComponent::GetValue(nsACString& aValue) { return NS_CStringCopy(aValue, mValue); } NS_IMETHODIMP M...
NS_CStringCutData
ngth ); Parameters aString [in] A nsACString instance to be modified. aCutStart [in] The starting index of the section to remove, measured in storage units. aCutLength [in] The length of the section to remove, measured in storage units. Pass PR_UINT32_MAX to specify the length from aCutStart to the end of the string. Return Values The NS_CStringCutData function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks This function is defined inline as a wrapper around NS_CStringSetDataRange . Example Code nsCStringContainer str; NS_CStringContainerInit(str); NS_CStringSetData(str, "hello world"); // remove " world" portion of string NS_CStringCutData(str, 5, PR_UINT32_MAX); const char* data; NS_CStringGetData(str, &data); printf("%s\n", data); // prints ...
NS_CStringInsertData
DataLength = PR_UINT32_MAX ); Parameters aString [in] A nsACString instance to be modified. aOffset [in] An offset into the string's internal buffer specifying where to place the given characters. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. Return Values The NS_CStringInsertData function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks This function is defined inline as a wrapper around NS_CStringSetDataRange. Example Code nsCStringContainer str; NS_CStringContainerInit(str); NS_CStringSetData(str, "hello"); NS_CStringInsertData(str, 5, " world"); const cha...
NS_CStringSetData
ude "nsStringAPI.h" nsresult NS_CStringSetData( nsACString& aString, const char* aData, PRUint32 aDataLength = PR_UINT32_MAX ); Parameters aString [in] A nsACString instance to modify. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null-terminated. Return Values The NS_CStringSetData function returns NS_OK if successful.
Otherwise, it returns an error code. Example nsCStringContainer str; rv = NS_CStringContainerInit(str); if (NS_SUCCEEDED(rv)) { rv = NS_CStringSetData(str, "hello world"); if (NS_SUCCEEDED(rv)) { // now, pass |str| to some function expecting a |const nsACString&| parameter...
NS_CStringSetDataRange
ng instance to modify. aCutStart [in] The starting index of the section to replace, measured in storage units. aCutLength [in] The length of the section to replace, measured in storage units. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. Return Values The NS_CStringSetDataRange function returns NS_OK if successful.
Otherwise, it returns an error code. Example // Replace all occurances of |matchVal| with |newVal| void ReplaceSubstring(nsACString& str, const nsACString& matchVal, const nsACString& newVal) { const char* sp, *mp, *np; PRUint32 ...
NS_CStringToUTF16
ning the source string to be converted. aSrcEncoding [in] The character encoding of the source string. See nsCStringEncoding for the set of values that can be passed for this parameter. aDest [out] A nsAString instance that will contain the result of the conversion. The result will be encoded using the host byte order. Return Values The NS_CStringToUTF16 function returns NS_OK if successful.
Otherwise, it returns an error code. The set of possible error codes is currently unspecified. Example Code nsEmbedCString str("hello"); nsEmbedString ustr; NS_CStringToUTF16(str, NS_CSTRING_ENCODING_ASCII, ustr); const PRUnichar *unicharBuf = ustr.get(); History This function was frozen for Mozilla 1.7. See bug bug 239123 for details. See Also nsACString, nsAString, nsCStringEncoding ...
NS_StringAppendData
" nsresult NS_StringAppendData( nsAString& aString, const PRUnichar* aData, PRUint32 aDataLength = PR_UINT32_MAX ); Parameters aString [in] A nsAString instance to be modified. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. Return Values The NS_StringAppendData function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks This function is defined inline as a wrapper around NS_StringSetDataRange Note: GCC requires the -fshort-wchar option to compile this example since PRUnichar is an unsigned short. This example should compile by default under MSVC. Exam...
NS_StringContainerInit
ence Summary The NS_StringContainerInit function initializes a nsStringContainer instance for use as a nsAString. This is a low-level API. #include "nsStringAPI.h" nsresult NS_StringContainerInit( nsStringContainer& aString ); Parameters aString [in] A nsStringContainer instance to be initialized. Return Values The NS_StringContainerInit function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks The nsStringContainer structure has unspecified size and layout. Its members may not be accessed directly. After a nsStringContainer object has been initialized, it may be used as an ordinary nsAString object. The internal buffer allocated by a nsStringContainer is always null-terminated. With NS_StringContainerInit, the coder is required to call NS_StringContai...
NS_StringCopy
rom one nsAString instance to another. This is a low-level API. #include "nsStringAPI.h" nsresult NS_StringCopy( nsAString& aDestString, const nsAString& aSrcString ); Parameters aDestString [in] A nsAString instance to be modified. aSrcString [in] A nsAString instance containing the new string value. Return Values The NS_StringCopy function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks This function is designed to allow the implementation to efficiently assign the same value to two string objects. The implementation may employ reference counting techniques to optimize this operation. Example Code /* attribute ACString value; */ NS_IMETHODIMP MyComponent::GetValue(nsAString& aValue) { return NS_StringCopy(aValue, mValue); } N...
NS_StringCutData
); Parameters aString [in] A nsAString instance to be modified. aCutStart [in] The starting index of the section to remove, measured in storage units. aCutLength [in] The length of the section to remove, measured in storage units. Pass PR_UINT32_MAX to specify the length from aCutStart to the end of the string. Return Values The NS_StringCutData function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks This function is defined inline as a wrapper around NS_StringSetDataRange. Note: GCC requires the -fshort-wchar option to compile this example since PRUnichar is an unsigned short. This example should compile by default under MSVC. Example Code nsStringContainer str; NS_StringContainerInit(str); NS_StringSetData(str, L"hello world"); // remove " w...
NS_StringInsertData
gth = PR_UINT32_MAX ); Parameters aString [in] A nsACString instance to be modified. aOffset [in] An offset into the string's internal buffer specifying where to place the given characters. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. Return Values The NS_StringInsertData function returns NS_OK if successful.
Otherwise, it returns an error code. Remarks This function is defined inline as a wrapper around NS_StringSetDataRange . Note: GCC requires the -fshort-wchar option to compile this example since PRUnichar is an unsigned short. This example should compile by default under MSVC. Ex...
NS_StringSetData
"nsStringAPI.h" nsresult NS_StringSetData( nsAString& aString, const PRUnichar* aData, PRUint32 aDataLength = PR_UINT32_MAX ); Parameters aString [in] A nsAString instance to modify. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. Return Values The NS_StringSetData function returns NS_OK if successful.
Otherwise, it returns an error code. Example Code nsStringContainer str; rv = NS_StringContainerInit(str); if (NS_SUCCEEDED(rv)) { rv = NS_StringSetData(str, "hello world"); if (NS_SUCCEEDED(rv)) { // now, pass |str| to some function expecting a |const nsAString...
NS_StringSetDataRange
nsAString instance to modify. aCutStart [in] The starting index of the section to replace, measured in storage units. aCutLength [in] The length of the section to replace, measured in storage units. aData [in] A raw character array to copy into this string. aDataLength [in] The length of aData, measured in storage units. If equal to PR_UINT32_MAX, then aData is assumed to be null-terminated.
Otherwise, aData need not be null terminated. Return Values The NS_StringSetDataRange function returns NS_OK if successful.
Otherwise, it returns an error code. Example Code // Replace all occurances of |matchVal| with |newVal| void ReplaceSubstring(nsAString& str, const nsAString& matchVal, const nsAString& newVal) { const PRUnichar* sp, *mp, *n...
NS_UTF16ToCString
o be converted. The source string should be encoded using the host byte order. aDestEncoding [in] The character encoding of the destination string. See nsCStringEncoding for the set of values that can be passed for this parameter. aDest [out] A nsACString instance that will contain the result of the conversion. Return Values The NS_UTF16ToCString function returns NS_OK if successful.
Otherwise, it returns an error code. The set of possible error codes is currently unspecified. Example Code // Convert UTF-16 (or UCS-2) string to UTF-8 void CopyUTF16toUTF8(const nsAString& in, nsACString& out) { NS_UTF16ToCString(in, NS_CSTRING_ENCODING_UTF8, out); } History This function was frozen for Mozilla 1.7. See bug bug 239123 for details. See Also nsACString, nsAString, nsCS...
Storage
nd the statement will get each set of bindings bound to it before execution asynchronously. Executing a Statement You may execute statements either synchronously (which is supported in Firefox Gecko 1.8 and 1.9) or asynchronously (starting in Gecko 1.9.1). If your code needs to work with applications based on Gecko 1.8 or 1.9, you should the technique covered in the section Synchronously below.
Otherwise, it's strongly recommended that you use asynchronous execution, for performance reasons. Asynchronously Gecko 1.9.1 introduced support for asynchronous execution of a statement by calling mozIStorageStatement.executeAsync() on the statement. Multiple statements can be executed in a transaction by calling mozIStorageConnection.executeAsync() on the connection and passing in an array of stateme...
Using the clipboard
process, except we use getData instead of setData and getTransferData instead of setTransferData. Here are the steps to pasting: Create a clipboard object which refers to the system clipboard. Create a transferring object which implements the nsITransferable interface. Initialize the transferring object with a null privacy context, as long as this object will not be placed on the clipboard.
Otherwise, use a one from a logical source window instead (see the description above). Tell the transferring object about the flavor of data you want to get. Retrieve the data from the clipboard and put it in the transferable. Get the data from the transferring object. The first steps are similar to that used for copying: var trans = Transferable(); trans.addDataFlavor("text/unicode"); Recall that...
XPCOM
h you can implement in your code to monitor HTTP transactions in real time, receiving a callback as the transactions take place.nsCOMPtr versus RefPtrGecko code uses both nsCOMPtr and RefPtr as smart pointers. This guide provides some explanation and advice on how to choose between them.Observer NotificationsThe following are topics that you can observe during the course of an application. Unless
otherwise noted you register for the topics using the nsIObserverService.Setting HTTP request headersHTTP is one of the core technologies behind the Web. In addition to the actual content, some important information is passed with HTTP headers for both HTTP requests and responses.StorageStorage is a SQLite database API. It is available to trusted callers, meaning extensions and Firefox components only.The ...
XPIDL Syntax
s can only occur at the beginning of lines; to simplify the grammar, I will not mention them in the grammar, especially since they are handled as a preprocessing step before the IDL source code is actually parsed. A `%{' that appears at the beginning of a line is the start of a raw code fragment, which extends until the end of a line that begins with `%}'. Text inside raw code fragments are not
otherwise parsed by xpidl directly. This may be followed by the language, as in `%{C++', to output the raw fragment only in the specified language. A `#include "file"' line instructs the xpidl processor to include that file in the same sense that the C preprocessor includes a file. Note that includes within comments or raw code fragments are not processed by xpidl. Unlike the C preprocessor, when a file i...
XPIDL
bove rule is if the parameter has the iid_is property (a special case for some QueryInterface-like operations). In general, this means that the only usable native types are those declared in nsrootidl.idl (see above). Methods and attributes are mangled on conversion to native code. If a method is declared notxpcom, the mangling of the return type is prevented, so it is called mostly as it looks.
Otherwise, the return type of the native method is nsresult, and the return type acts as a final outparameter if it is not void. The name is translated so that the first character is unconditionally uppercase; subsequent characters are unaffected. However, the presence of the binaryname property allows the user to select another name to use in native code (to avoid conflicts with other functions). For exam...
XUL Overlays
=1.8" src="overlay.js"/> UI reuse with overlays One of the biggest benefits of using overlays is that it allows you to reuse groups of elements that appear frequently in the UI. The overlay mechanism allows you to merge elements into existing subtrees, but it also allows you to store common UI elements in overlay files and merge them into any base files that use them. Using the ID attribute on an
otherwise empty node in the base file, you can essentially reference a subtree defined in an overlay file and merge it in wherever it's needed. For example, the buttons that appear at the bottom of common dialogs, the OK and Cancel buttons, may be used in dozens of places in the UI. Rather than redefining this set of buttons each time they are necessary in a particular dialog, base XUL files can overlay th...
Autoconfiguration in Thunderbird
2.3.4:80> #Must be the first and only virtual host with this ip! DocumentRoot /var/www/autoconfig/ ServerName autoconfig.hoster.com <Directory /var/www/autoconfig> Order allow,deny allow from all </Directory> </VirtualHost> Place the configuration file at the URL /mail/config-v1.1.xml on that host. All config files must be served as Content-Type: text/xml (or application/xml),
otherwise the file will be ignored. Also, they must use charset UTF-8 (esp. if there are any non-ASCII-characters). If you like to use name-based virtual hosts you probably don't want to setup the autoconfig subdomain for every domain of your customers. You can add a Rewriterule in the default virtual host (on debian /etc/apache2/sites-enabled/000-default) to match all autoconfig.* subdomains: <Virtual...
MailNews Filters
lf in as nsIMsgFilterHitNotify interface to handle filter hits. E.g., IMAP, POP3. ApplyFiltersToHdr will in turn call the applyFilterHit method of the passed in nsIMsgFilterHitNotify interface ptr. The protocol specific code will then apply all of the actions of the filter to the current msg header. If one of the actions is a move, or a stop filter execution action, we move on to the next header;
otherwise, we move on to the next filter. In the case of POP3, filter execution is synchronous. For each new header, we evaluate the filter criteria and apply the actions synchronously, including moving a message to an other local folder, and advance to the next header. For IMAP, we tend to initiate the urls synchronously, but because we don't run two urls simultaneously on the same folder, the urls don't ...
Folders and message lists
lderDisplayWidget has several ways of getting the currently-selected message(s), depending on what exactly you're trying to do: gFolderDisplay.selectedCount: Returns the number of messages currently selected. gFolderDisplay.selectedMessage: Returns the first currently-selected message. When using this, be sure that there's only one selected message (or that you only care about the first one).
Otherwise, use one of the methods described below. gFolderDisplay.selectedMessages: Returns an array of nsIMsgDBHdrs for the selected messages. If a collapsed thread is in there and working with collapsed threads is enabled, this will include the headers for the messages in that collapsed thread. gFolderDisplay.selectedMessageUris: Returns an array of the URIs corresponding to the selected messages. Like...
Using the Multiple Accounts API
server, and a permenant default server. Relevant API calls: nsISmtpService.smtpServers: list of SMTP servers nsISmtpService.createSmtpServer(): Create a new SMTP server nsISmtpServer.hostname, nsISmtpServer.username: Useful properties of the SMTP server. Appendix A: Listing of all properties (When brendan's idldoc comes along, I'll just link to that) All preferences are strings, unless
otherwise noted. Account Manager Pref: mail.accountmanager.accounts Account Preference: mail.account.account.server IDL: nsIMsgAccount.incomingServer The incoming server associated with this account. The preference is the preference "key" used, such as "server1". Preference: mail.account.account.identities IDL: nsIMsgAccount.identities The list of identites associated with this acco...
Toolkit version format
that mark version as "beta" in the AMO queues. Comparing versions When two version strings are compared, their version parts are compared left to right. An empty or missing version part is equivalent to 0. If at some point a version part of one version string is greater than the corresponding version part of another version string, then the first version string is greater than the other one.
Otherwise, the version strings are equal. Note, that since missing version parts are treated as if they were 0, the following version strings are equal: 1, 1.0, 1.0., 1.0.0, and even 1.0... Comparing version parts Version parts are also compared left to right, parts A and C are compared as numbers, while parts B and D are compared byte-wise. A string-part that exists is always less than a string-part tha...
Zombie compartments
the add-on, the more thorough the testing will be, but in practice a lot of problems show up quickly. Open about:memory and close all other pages. Return to about:memory and minimize memory and remeasure, multiple times if necessary. If only system compartments are present, and there are no ghost windows, congratulations! That's a good sign that the add-on doesn't cause zombie compartments.
Otherwise, please file a bug (using the "Tech Evangelism" product and the "Add-ons" component), add "[MemShrink]" to its whiteboard, and mark it as blocking bug 668871 and bug 700547. Restartless add-ons should also take special care that all their compartments get destroyed after disabling or uninstalling the add-on. (Please note that you may need to close the about:addons UI before changes are made). ...
Using Objective-C from js-ctypes
// [NSString getBytes:maxLength:usedLength:encoding:options:range:remainingRange:] SEL foo = sel_registerName("getBytes:maxLength:usedLength:encoding:options:range:remainingRange:"); Method which returns non-id type If a method returns a type which is compatible with id, we can cast it, or just use it as id type (since we don't need to use a different type for each instance, in terms of C).
Otherwise, the following functions can be used, depending on return type and architecture. objc_msgSend_stret For the method which returns structs on the stack. objc_msgSend_fpret / objc_msgSend_fp2ret For the method which returns floating-point values on the stack. objc_msgSend For the method which returns the value in a register, or returns nothing. For example, [NSSpeechSynthesizer isSpeaking]...
Using js-ctypes
se with the loaded library. Note: js-ctypes only works with C libraries; you can't use C++ methods directly. Instead, you'll need to create a shim library that uses C functions that then call into the C++ library for you. Examples can be found here: Bugzilla :: Bug 505907 - Support C++ calling from JSctypes Library search paths If you specify a full path, that path is used to load the library.
Otherwise, the system looks for the library in its standard locations. Windows On Windows, the following locations are searched for the library, in this order: The application's directory. The system directory. The 16-bit system directory. The Windows directory. The current working directory The directories listed in the PATH environment variable. Note: This information comes from this article ...
CData
Noitidart/_scratchpad MDNFirefox" at js array position 36 (so 37 if count from 1), we see 183, and at 77 we see char code of 0 IF casted to unsign...
PointerType
f the value can't be converted. PointerType CData Method_overview bool isNull() Methods inherited from CData CData address() String toSource() String toString() PointerType CData Methods isNull() Determines whether or not the pointer's value is null. bool isNull(); Parameters None. Return value true if the pointer's value is null,
otherwise false. See Also CType CData Type conversion ...
Drawing and Event Handling - Plugins
g it correctly. The browser sets up the port for the plug-in before passing the plug-in an update event in two ways: The browser calls SetOrigin(npport->portx, npport->porty). This method makes the instance's upper-left coordinate equal to (0,0). The browser sets the port's clip region to the region of the plug-in currently visible (not scrolled off the page, obscured by floating palettes, or
otherwise hidden). However, for the plug-in to draw at any other time, for example, to highlight on a mouse-down event or draw animation at idle time, it must save the current setting of the port, set up its drawing environment as appropriate, draw, and then restore the port to the previous settings. In this case, the plug-in makes it unnecessary for the browser to save and restore its port settings befo...
Plug-in Basics - Plugins
ements. Use the id attribute, which specifies the name of the plug-in, if the plug-in is communicating with JavaScript. This is equivalent to the name attribute of applet and embed. It must be unique. Using the appropriate attributes It's up to you to provide enough attributes and to make sure that they do not conflict; for example, the values of width and height may be wrong for the plug-in.
Otherwise, the plug-in cannot be embedded. Gecko interprets the attributes as follows: When the browser encounters an object element, it goes through the element attributes, ignoring or parsing as appropriate. It analyzes the attributes to determine the object type, then determines whether the browser can handle the type. If the browser can handle the type-that is, if a plug-in exists for that type-the...
Accessibility Inspector - Firefox Developer Tools
This article takes you through the main features of the Accessibility Inspector and how to use it. A (very) brief guide to accessibility Accessibility is the practice of making your websites usable by as many people as possible. ...
Introduction to DOM Inspector - Firefox Developer Tools
of the biggest and most immediate advantages that this brings to your web and application development is that it makes it possible to find the markup and the nodes in which the interesting parts of a page or a piece of the user interface are defined. One common use of the DOM Inspector is to find the name and location of particular icon being used in the user interface, which is not an easy task
otherwise. If you're inspecting a chrome document, as you select nodes in the DOM Nodes viewer, the rendered versions of those nodes are highlighted in the user interface itself. (Note that there are bugs which prevent the flasher from DOM Inspector APIs from working correctly on certain platforms.) If you inspect the main browser window, for example, and select nodes in the DOM Nodes viewer (other than t...
Debugger.Frame - Firefox Developer Tools
within which evaluation is taking place (a Debugger.Environment instance), or null on frames that do not represent the evaluation of debuggee code, like calls non-debuggee functions, host functions or "debugger" frames. callee The function whose application created this frame, as a debuggee value, or null if this is not a "call" frame. generator True if this frame is a generator frame, false
otherwise. constructing True if this frame is for a function called as a constructor, false
otherwise. arguments The arguments passed to the current frame, or null if this is not a "call" frame. When non-null, this is an object, allocated in the same global as the debugger, with Array.prototype on its prototype chain, a non-writable length property, and properties whose names are array indices. Each pr...
Debugger-API - Firefox Developer Tools
e scope of these global objects. You can set functions to be called when new stack frames are pushed; when new code is loaded; and so on. Omitted from this picture are Debugger.Source instances, which represent JavaScript compilation units. A Debugger.Source can furnish a full copy of its source code, and explain how the code entered the system, whether via a call to eval, a <script> element, or
otherwise. A Debugger.Script points to the Debugger.Source from which it is derived. Also omitted is the Debugger's Debugger.Memory instance, which holds methods and accessors for observing the debuggee's memory use. All these types follow some general conventions, which you should look through before drilling down into any particular type's specification. All shadow objects are unique per Debugger and ...
Index - Firefox Developer Tools
the bottom of the page. This view makes it easy to visualize the nesting of your content. 3 Accessibility Inspector Accessibility, Accessibility inspector, DevTools, Guide, Tools The Accessibility Inspector provides a means to access important information exposed to assistive technologies on the current page via the accessibility tree, allowing you to check what's missing or
otherwise needs attention. This article takes you through the main features of the Accessibility Inspector and how to use it. 4 Color vision simulation Accessibility, Accessibility inspector, Color blindness, DevTools, Guide, Simulation, Tools The simulator in the Accessibility Inspector in Firefox Developer Tools lets you see what a web page would look like to users with various forms...
Dominators view - Firefox Developer Tools
Starting in Firefox 46, the Memory tool includes a new view called the Dominators view. This is useful for understanding the "retained size" of objects allocated by your site: that is, the size of the objects themselves plus the size of the objects that they keep alive through references. If you already know what shallow size, retained size, and dominators are, skip to the Dominators UI section.
Otherwise, you might want to review the article on Dominators concepts. Dominators UI To see the Dominators view for a snapshot, select "Dominators" in the "View" drop-down list. It looks something like this: The Dominators view consists of two panels: the Dominators Tree panel shows you which nodes in the snapshot are retaining the most memory the Retaining Paths panel (new in Firefox 47) shows t...
Network request details - Firefox Developer Tools
equest. Version: The HTTP version used Transferred: The amount of data transferred with the request The Referrer Policy, which governs which referrer information, sent in the Referer header, should be included with requests. (See Referrer-Policy for a description of possible values) Blocking: If the request is to a site that is associated with a known tracker, an icon and a message are shown;
otherwise, this field is not shown. Response headers The response headers section shows details about the response. For each line in the response headers section, a question mark links to the documentation for that response header, if one is available. A Raw toggle button in the section heading controls whether the headers are shown with formatting, or as plain, unformatted text. Note that the keys i...
Responsive Design Mode - Firefox Developer Tools
g The final two options define when the page is reloaded: Reload when touch simulation is toggled: when this option is enabled, the page is reloaded whenever you toggle touch support. Reload when user agent is changed: when this option is enabled, the page isreloaded whenever the user agent is changed. Reloading on these changes can be helpful because certain page behaviors would
otherwise not be applied. For example, many pages check for touch support on load and only add event handlers if it is supported, or only enable certain features on certain browsers. However, if you are not interested in examining such features (maybe you are just checking the overall layout at different sizes), these reloads can waste time and possibly result in the loss of productive work, so it is usef...
Web Console Helpers - Firefox Developer Tools
rame See working with iframes. clear() Clears the console output area. clearHistory() Just like a normal command line, the console command line remembers the commands you've typed. Use this function to clear the console's command history. copy() Copies the argument to the clipboard. If the argument is a string, it's copied as-is. If the argument is a DOM node, its outerHTML is copied.
Otherwise, JSON.stringify will be called on the argument, and the result will be copied to the clipboard. help()Deprecated since Gecko 62 :help Displays help text. Actually, in a delightful example of recursion, it brings you to this page. inspect() Given an object, generates rich output for that object. Once you select the object in the output area, you can use the arrow keys to navigate the object. ...
The JavaScript input interpreter - Firefox Developer Tools
u can supply any of the following: a selector string that will be passed to document.querySelector to locate the iframe element the iframe element itself the content window inside the iframe See working with iframes. copy() New in Firefox 38. Copy the argument to the clipboard. If the argument is a string, it's copied as-is. If the argument is a DOM node, its outerHTML is copied.
Otherwise, JSON.stringify will be called on the argument, and the result will be copied to the clipboard. clearHistory() New in Firefox 39. Just like a normal command line, the console command line remembers the commands you've typed. Use this function to clear the console's command history. :screenshot New in Firefox 62. Create a screenshot of the current page with the supplied filename. If you don't ...
Firefox Developer Tools
network requests made when a page is loaded. Performance Tools Analyze your site's general responsiveness, JavaScript, and layout performance. Responsive Design Mode See how your website or app will look and behave on different devices and network types. Accessibility inspector Provides a means to access the page's accessibility tree, allowing you to check what's missing or
otherwise needs attention. Application panel Provides tools for inspecting and debugging modern web apps (also known as Progressive Web Apps). This includes inspection of service workers and web app manifests. Note: The collective term for the UI inside which the DevTools all live is the Toolbox. More Tools These developer tools are also built into Firefox. Unlike the "Core Tools" above, you m...
Animation.pending - Web APIs
Specifications Specification Status Comment Web AnimationsThe definition of 'pending' in that specification. Working Draft ...
Animation - Web APIs
ion has been removed. It will cause the end styling state to be written to the element being animated, in the form of properties inside a style attribute. Animation.finish() Seeks either end of an animation, depending on whether the animation is playing or reversing. Animation.pause() Suspends playing of an animation. animation.persist() Explicitly persists an animation, when it would
otherwise be removed due to the browser's Automatically removing filling animations behavior. Animation.play() Starts or resumes playing of an animation, or begins the animation again if it previously finished. Animation.reverse() Reverses playback direction, stopping at the start of the animation. If the animation is finished or unplayed, it will play from end to beginning. Animation.updatePlay...
AudioBuffer() - Web APIs
n constructing this object. User agents are required to support sample rates from 8,000 Hz to 96,000 Hz (but are allowed to go farther outside this range). Deprecated parameters context A reference to an AudioContext. This parameter was removed from the spec. Return value A new AudioBuffer object instance. Exceptions NotSupportedError One or more of the options are negative or
otherwise has an invalid value (such as numberOfChannels being higher than supported, or a sampleRate outside the nominal range). RangeError There isn't enough memory available to allocate the buffer. Specifications Specification Status Comment Web Audio APIThe definition of 'AudioBuffer' in that specification. Working Draft Initial definition. Browser Compatibilit...
AudioBufferSourceNode.loop - Web APIs
The loop property of the AudioBufferSourceNode interface is a Boolean indicating if the audio asset must be replayed when the end of the AudioBuffer is reached. The loop property's default value is false. Syntax var loopingEnabled = AudioBufferSourceNode.loop; AudioBufferSourceNode.loop = true | false; Value A Boolean which is true if looping is enabled;
otherwise, the value is false. When looping is enabled, the sound begins playing at the time specified as the start point when start() is called. When the time specified by the loopEnd property is reached, playback continues at the time specified by loopStart Example In this example, the AudioContext.decodeAudioData function is used to decode an audio track and put it into an AudioBufferSourceNode. Buttons are provided to play and stop ...
AudioListener.forwardX - Web APIs
Syntax var audioCtx = new AudioContext(); var myListener = audioCtx.listener; myListener.forwardX.value = 0; Value An AudioParam. ...
AudioListener.forwardY - Web APIs
Syntax var audioCtx = new AudioContext(); var myListener = audioCtx.listener; myListener.forwardY.value = 0; Value An AudioParam. ...
AudioListener.forwardZ - Web APIs
Syntax var audioCtx = new AudioContext(); var myListener = audioCtx.listener; myListener.forwardZ.value = 0; Value An AudioParam. ...
AudioListener.positionX - Web APIs
Syntax var audioCtx = new AudioContext(); var myListener = audioCtx.listener; myListener.positionX.value = 1; Value An AudioParam. Its default value is 0, and it can range between positive and negative infinity. ...
AudioListener.positionY - Web APIs
Syntax var audioCtx = new AudioContext(); var myListener = audioCtx.listener; myListener.positionY.value = 1; Value An AudioParam. Its default value is 0, and it can range between positive and negative infinity. ...
AudioListener.positionZ - Web APIs
Syntax var audioCtx = new AudioContext(); var myListener = audioCtx.listener; myListener.positionZ.value = 1; Value An AudioParam. Its default value is 0, and it can range between positive and negative infinity. ...
AudioListener.upX - Web APIs
Syntax var audioCtx = new AudioContext(); var myListener = audioCtx.listener; myListener.upX.value = 0; Value An AudioParam. Its default value is 0, and it can range between positive and negative infinity. ...
AudioListener.upY - Web APIs
Syntax var audioCtx = new AudioContext(); var myListener = audioCtx.listener; myListener.upY.value = 0; Value An AudioParam. Its default value is 1, and it can range between positive and negative infinity. ...
AudioListener.upZ - Web APIs
Syntax var audioCtx = new AudioContext(); var myListener = audioCtx.listener; myListener.upZ.value = 0; Value An AudioParam. Its default value is 0, and it can range between positive and negative infinity. ...
AudioNode.connect() - Web APIs
escribing which input of the destination you want to connect the current AudioNode to; the default is 0. The index numbers are defined according to the number of input channels (see Audio channels). It is possible to connect an AudioNode to another AudioNode, which in turn connects back to the first AudioNode, creating a cycle. This is allowed only if there is at least one DelayNode in the cycle.
Otherwise, a NotSupportedError exception is thrown. This parameter is not allowed if the destination is an AudioParam. Return value If the destination is a node, connect() returns a reference to the destination AudioNode object, allowing you to chain multiple connect() calls. In some browsers, older implementations of this interface return undefined. If the destination is an AudioParam, connect() retur...
AudioScheduledSourceNode - Web APIs
ode interfaces which share the ability to be started and stopped, optionally at specified times. Specifically, this interface defines the start() and stop() methods, as well as the onended event handler. You can't create an AudioScheduledSourceNode object directly. Instead, use the interface which extends it, such as AudioBufferSourceNode, OscillatorNode, and ConstantSourceNode. Unless stated
otherwise, nodes based upon AudioScheduledSourceNode output silence when not playing (that is, before start() is called and after stop() is called). Silence is represented, as always, by a stream of samples with the value zero (0). Properties Inherits properties from its parent interface, AudioNode. Methods Inherits methods from its parent interface, AudioNode, and adds the following methods: start(...
AudioTrack.label - Web APIs
Syntax var audioTrackLabel = AudioTrack.label; Value A DOMString specifying the track's human-readable label, if one is available in the track metadata.
Otherwise, an empty string ("") is returned. For example, a track whose kind is "commentary" might have a label such as "Commentary with director Mark Markmarkimark and star Donna Donnalidon". Example This example returns an array of track kinds and labels for potential use in a user interface to select audio tracks for a specified media element. ...
AudioWorkletNodeOptions - Web APIs
IndexSizeError will be thrown. If outputChannelCount isn't specified, and numberOfInputs and numberOfOutputs are both 1, the AudioWorkletNode's initial channel count is set to 1. This has the effect of changing the output channel count to dynamically change to the computed number of channels, based on the input's channel count and the current setting of the AudioNode property channelCountMode.
Otherwise, if outputChannelCount is provided and if the values of numberOfInputs and numberOfOutputs are both 1, the audio worklet node's channel count is set to the value of outputChannelCount.
Otherwise, the channel count of each channel in the set of output channels is set to match the corresponding value in the outputChannelCount array. Examples // FILL IN EXAMPLE SNIPPET Specifications Sp...
AudioWorkletProcessor.process - Web APIs
e current block, the array may contain a single value that is constant for the entire block, instead of 128 identical values. If the automation rate is "k-rate", the array will contain a single value, which is to be used for each of 128 frames. Return value A Boolean value indicating whether or not to force the AudioWorkletNode to remain active even if the user agent's internal logic would
otherwise decide that it's safe to shut down the node. The returned value lets your processor have influence over the lifetime policy of the AudioWorkletProcessor and the node that owns it. If the combination of the return value and the state of the node causes the browser to decide to stop the node, process() will not be called again. Returning true forces the Web Audio API to keep the node alive, while...
BaseAudioContext.createBuffer() - Web APIs
length to use for a specific number of seconds of audio, use numSeconds * sampleRate. sampleRate The sample rate of the linear audio data in sample-frames per second. All browsers must support sample rates in at least the range 8,000 Hz to 96,000 Hz. Returns An AudioBuffer configured based on the specified options. Exceptions NotSupportedError One or more of the options are negative or
otherwise has an invalid value (such as numberOfChannels being higher than supported, or a sampleRate outside the nominal range). RangeError There isn't enough memory available to allocate the buffer. Examples First, a couple of simple trivial examples, to help explain how the parameters are used: var audioCtx = new AudioContext(); var buffer = audioCtx.createBuffer(2, 22050, 44100); If you use this...
BaseAudioContext.createPeriodicWave() - Web APIs
hich is used to define a periodic waveform that can be used to shape the output of an OscillatorNode. Syntax var wave = AudioContext.createPeriodicWave(real, imag[, constraints]); Returns A PeriodicWave. Parameters real An array of cosine terms (traditionally the A terms). imag An array of sine terms (traditionally the B terms). The real and imag arrays have to have the same length,
otherwise an error is thrown. constraints Optional An dictionary object that specifies whether normalization should be disabled (if not specified, normalization is enabled by default.) It takes one property: disableNormalization: If set to true, normalization is disabled for the periodic wave. The default is false. If normalized, the resulting wave will have a maximum absolute peak value of ...
BatteryManager.charging - Web APIs
A Boolean value indicating whether or not the device's battery is currently being charged. Syntax var charging = battery.charging On return, charging indicates whether or not the battery, which is a BatteryManager object, is currently being charged; if the battery is charging, this value is true.
Otherwise, the value is false. Example HTML Content <div id="charging">(charging state unknown)</div> JavaScript Content navigator.getBattery().then(function(battery) { var charging = battery.charging; document.querySelector('#charging').textContent = charging ; }); Specifications Specification Status Comment Battery Status API Candidate Recommendation Initial definition ...
Bluetooth.getAvailability() - Web APIs
Note: User might not allow use of Web Bluetooth API, even if getAvailability() returned true (navigator.bluetooth.requestDevice() might not resolve with a BluetoothDevice). Also, user can configure User Agent to return a fixed value instead of a real one. ...
Bluetooth.referringDevice - Web APIs
The Bluetooth.referringDevice attribute of the Bluetooth interface returns a BluetoothDevice if the current document was opened in response to an instruction sent by this device and null
otherwise. Syntax Bluetooth.referringDevice Value A BluetoothDevice, if the document was opened in response to an instruction sent by this device and null
otherwise. Specifications Specification Status Comment Web BluetoothThe definition of 'referringDevice' in that specification. Draft Initial definition. ...
BluetoothRemoteGATTCharacteristic - Web APIs
e first BluetoothGATTDescriptor for a given descriptor UUID. BluetoothRemoteGATTCharacteristic.getDescriptors() Returns a Promise that resolves to an Array of all BluetoothGATTDescriptor objects for a given descriptor UUID. BluetoothRemoteGATTCharacteristic.readValue() Returns a Promise that resolves to an ArrayBuffer holding a duplicate of the value property if it is available and supported.
Otherwise it throws an error. BluetoothRemoteGATTCharacteristic.writeValue() Sets the value property to the bytes contained in an ArrayBuffer and returns a Promise. BluetoothRemoteGATTCharacteristic.startNotifications() Returns a Promise when navigator.bluetooth is added to the active notification context. BluetoothRemoteGATTCharacteristic.stopNotifications() Returns a Promise when navigator.bluetoot...
readValue() - Web APIs
Syntax BluetoothRemoteGATTDescriptor.readValue().then(function(value[]) { ... }) Returns A Promise that resolves to an ArrayBuffer. Specifications Specification Status Comment Web BluetoothThe definition of 'readValue()' in that specification. Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
BluetoothRemoteGATTDescriptor - Web APIs
for theClient Characteristic Configuration descriptor. BluetoothRemoteGATTDescriptor.valueRead only Returns the currently cached descriptor value. This value gets updated when the value of the descriptor is read. Methods BluetoothRemoteGATTDescriptor.readValue() Returns a Promise that resolves to an ArrayBuffer holding a duplicate of the value property if it is available and supported.
Otherwise it throws an error. BluetoothRemoteGATTDescriptor.writeValue() Sets the value property to the bytes contained in an ArrayBuffer and returns a Promise. Specifications Specification Status Comment Web BluetoothThe definition of 'BluetoothRemoteGATTDescriptor' in that specification. Draft Initial definition. Browser Compatibility The compatibility table on ...
CSS.supports() - Web APIs
ows to test the support of a pair property-value: propertyName A DOMString containing the name of the CSS property to check. value A DOMString containing the value of the CSS property to check. The second syntax takes one parameter matching the condition of @supports: supportCondition A DOMString containing the condition to check. Return value true if the browser supports the rule,
otherwise false. Examples result = CSS.supports("text-decoration-style", "blink"); result = CSS.supports("display: flex"); result = CSS.supports("(--foo: red)"); result = CSS.supports(`(transform-style: preserve) or (-moz-transform-style: preserve) or (-o-transform-style: preserve) or (-webkit-transform-style: preserve)`); // result is true or false Specification Speci...
CSSNumericValue - Web APIs
plied number from the CSSNumericValue. CSSNumericValue.mul Multiplies the CSSNumericValue by the supplied value. CSSNumericValue.div Divides the CSSNumericValue by the supplied value. CSSNumericValue.min Returns the minimum value passed CSSNumericValue.max Returns the maximum value passed CSSNumericValue.equals True if all the values are the exact same type and value, in the same order.
Otherwise, false. CSSNumericValue.to Converts value into another one with the specified unit. CSSNumericValue.toSum TBD CSSNumericValue.type TBD CSSNumericValue.parse Allows a CSSNumericValue to be constructed directly from a string containing CSS. Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'CSSNumericValue' in that specification.
CSSRule - Web APIs
s cssRules list. Properties common to all CSSRule instances CSSRule.cssText Represents the textual representation of the rule, e.g. "h1,h2 { font-size: 16pt }" or "@import 'url'". To access or modify parts of the rule (e.g. the value of "font-size" in the example) use the properties on the specialized interface for the rule's type. CSSRule.parentRule Read only Returns the containing rule,
otherwise null. E.g. if this rule is a style rule inside an @media block, the parent rule would be that CSSMediaRule. CSSRule.parentStyleSheet Read only Returns the CSSStyleSheet object for the style sheet that contains this rule CSSRule.type Read only One of the Type constants indicating the type of CSS rule. Constants Type constants The CSSRule interface specifies integer constants that can be ...
CSSStyleSheet - Web APIs
the stylesheet. This is normally used to access individual rules like this: styleSheet.cssRules[i] // where i = 0..cssRules.length-1 To add or remove items in cssRules, use the CSSStyleSheet's insertRule() and deleteRule() methods. ownerRule Read only If this stylesheet is imported into the document using an @import rule, the ownerRule property returns the corresponding CSSImportRule;
otherwise, this property's value is null. Methods Inherits methods from its parent, StyleSheet. deleteRule() Deletes the rule at the specified index into the stylesheet's rule list. insertRule() Inserts a new rule at the specified position in the stylesheet, given the textual representation of the rule. Legacy properties These properties are legacy properties first introduced by Microsoft long ...
CSS Font Loading API - Web APIs
The CSS Font Loading API provides events and interfaces for dynamically loading font resources. Interfaces FontFace Represents a single usable font face. FontFaceSet An interface loading font faces and checking their download statuses. FontFaceSource A mixin providing all of the fonts used in font-related operations, unless defined
otherwise. It defines the FontFaceSources.fonts property available to Document and WorkerGlobalScope. FontFaceSetLoadEvent Fired whenever a FontFaceSet loads. Specifications Specification Status Comment CSS Font Loading Module Level 3 Working Draft Initial definition. ...
CSS Typed Object Model API - Web APIs
alue. CSSNumericValue.mul - Multiplies supplied numbers to the CSSNumericValue. CSSNumericValue.div - Divides a supplied number by other numbers, throwing an error if 0. CSSNumericValue.min - Returns the minimum value passed CSSNumericValue.max - Returns the maximum value passed CSSNumericValue.equals - Returns true if all the values are the exact same type and value, in the same order.
Otherwise, false CSSNumericValue.to - Converts value into another one with the specified unit. CSSNumericValue.toSum CSSNumericValue.type CSSNumericValue.parse - Returns a number parsed from a CSS string CSSPositionValue Represents values for properties that take a position, for example object-position. CSSTransformValue An interface representing a list of transform list values. They "con...
Cache.delete() - Web APIs
n not to perform VARY header matching. In other words, if the URL matches you will get a match regardless of whether the Response object has a VARY header. It defaults to false. cacheName: A DOMString that represents a specific cache to search within. Note that this option is ignored by Cache.delete(). Return value a Promise that resolves to true if the cache entry is deleted, or false
otherwise. Examples caches.open('v1').then(function(cache) { cache.delete('/images/image.png').then(function(response) { someUIUpdateFunction(); }); }) Specifications Specification Status Comment Service WorkersThe definition of 'Cache: delete' in that specification. Working Draft Initial definition. ...
Cache - Web APIs
{ return cache.match(event.request).then(function(response) { if (response) { // If there is an entry in the cache for event.request, then response will be defined // and we can just return it. Note that in this example, only font resources are cached. console.log(' Found response in cache:', response); return response; } //
Otherwise, if there is no entry in the cache for event.request, response will be // undefined, and we need to fetch() the resource. console.log(' No response for %s found in cache. About to fetch ' + 'from network...', event.request.url); // We call .clone() on the request since we might use it in a call to cache.put() later on. // Both fetch() and cache.put() "co...
CacheStorage.delete() - Web APIs
at resolves to true. If no Cache object is found, it resolves to false. You can access CacheStorage through the global caches property. Syntax caches.delete(cacheName).then(function(boolean) { // your cache is now deleted }); Parameters cacheName The name of the cache you want to delete. Return value a Promise that resolves to true if the Cache object is found and deleted, and false
otherwise. Examples In this code snippet we wait for an activate event, and then run a waitUntil() block that clears up any old, unused caches before a new service worker is activated. Here we have an array of cache names we want to keep (cachesToKeep). We return the keys of the caches in the CacheStorage object using CacheStorage.keys, then check each key to see if it is in the array. If not, we delete ...
CanvasRenderingContext2D.drawWindow() - Web APIs
aster because we won't have to compute the window's transparency. flags Optional Used to better control the drawWindow call. Flags can be ORed together. Constant Value Description DRAWWINDOW_DRAW_CARET 0x01 Show the caret if appropriate when drawing. DRAWWINDOW_DO_NOT_FLUSH 0x02 Do not flush pending layout notifications that could
otherwise be batched up. DRAWWINDOW_DRAW_VIEW 0x04 Draw scrollbars and scroll the viewport if they are present. DRAWWINDOW_USE_WIDGET_LAYERS 0x08 Use the widget layer manager if available. This means hardware acceleration may be used, but it might actually be slower or lower quality than normal. It will, however, more accurately reflect the pixels rendered to the scr...
Applying styles and colors - Web APIs
t color to the stroke and/or fill style. globalAlpha = transparencyValue Applies the specified transparency value to all future shapes drawn on the canvas. The value must be between 0.0 (fully transparent) to 1.0 (fully opaque). This value is 1.0 (fully opaque) by default. The globalAlpha property can be useful if you want to draw a lot of shapes on the canvas with similar transparency, but
otherwise it's generally more useful to set the transparency on individual shapes when setting their colors. Because the strokeStyle and fillStyle properties accept CSS rgba color values, we can use the following notation to assign a transparent color to them. // Assigning transparent colors to stroke and fill style ctx.strokeStyle = 'rgba(255, 0, 0, 0.5)'; ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'; The ...
Drawing shapes with canvas - Web APIs
hich takes six parameters: x and y are the coordinates of the center of the circle on which the arc should be drawn. radius is self-explanatory. The startAngle and endAngle parameters define the start and end points of the arc in radians, along the curve of the circle. These are measured from the x axis. The anticlockwise parameter is a Boolean value which, when true, draws the arc anticlockwise;
otherwise, the arc is drawn clockwise. Note: Angles in the arc function are measured in radians, not degrees. To convert degrees to radians you can use the following JavaScript expression: radians = (Math.PI/180)*degrees. The following example is a little more complex than the ones we've seen above. It draws 12 different arcs all with different angles and fills. The two for loops are for looping throu...
Using images - Web APIs
to retrieve that specific image Using images from other domains Using the crossorigin attribute of an <img> element (reflected by the HTMLImageElement.crossOrigin property), you can request permission to load an image from another domain for use in your call to drawImage(). If the hosting domain permits cross-domain access to the image, the image can be used in your canvas without tainting it;
otherwise using the image will taint the canvas. Using other canvas elements Just as with normal images, we access other canvas elements using either the document.getElementsByTagName() or document.getElementById() method. Be sure you've drawn something to the source canvas before using it in your target canvas. One of the more practical uses of this would be to use a second canvas element as a thumbnai...
Clients.matchAll() - Web APIs
.clients.matchAll(options).then(function(clients) { // do something with your clients list }); Parameters options Optional An options object allowing you to set options for the matching operation. Available options are: includeUncontrolled: A Boolean -- if set to true, the matching operation will return all service worker clients who share the same origin as the current service worker.
Otherwise, it returns only the service worker clients controlled by the current service worker. The default is false. type: Sets the type of clients you want matched. Available values are "window", "worker", "sharedworker", and "all". The default is "all". Return value A Promise that resolves to an array of Client objects. In Chrome 46/Firefox 54 and later, this method returns clients in most re...
Clipboard.read() - Web APIs
with a DataTransfer object containing the clipboard's contents. The promise is rejected if permission to access the clipboard is not granted. Example After using navigator.permissions.query() to find out if we have (or if the user will be prompted to allow) "clipboard-read" access, this example fetches the data currently on the clipboard. If it's not a png image, an error message is presented.
Otherwise, an image element referred to using the variable imgElem has its source replaced with the clipboard's contents. // First, ask the Permissions API if we have some kind of access to // the "clipboard-read" feature. navigator.permissions.query({name: "clipboard-read"}).then(result => { // If permission to read the clipboard is granted or if the user will // be prompted to allow it, we proceed.
console.log() - Web APIs
OM elements, whereas console.dir does not. This is often useful when trying to see the full representation of the DOM JS object. There's more information in the Chrome Console API reference about this and other functions. Logging objects Don't use console.log(obj), use console.log(JSON.parse(JSON.stringify(obj))). This way you are sure you are seeing the value of obj at the moment you log it.
Otherwise, many browsers provide a live view that constantly updates as values change. This may not be what you want. Specifications Specification Status Comment Console APIThe definition of 'console.log()' in that specification. Living Standard Initial definition ...
CustomElementRegistry.define() - Web APIs
controls how the element is defined. One option is currently supported: extends: String specifying the name of a built-in element to extend. Used to create a customized built-in element. Return value Void. Exceptions Exception Description NotSupportedError The CustomElementRegistry already contains an entry with the same name or the same constructor (or is
otherwise already defined), or extends is specified and it is a valid custom element name, or extends is specified but the element it is trying to extend is an unknown element. SyntaxError The provided name is not a valid custom element name. TypeError The referenced constructor is not a constructor. Note: You'll often get NotSupportedErrors thrown that seem like define() is...
DOMMatrix - Web APIs
atrix by applying the specified skew transformation along the Y-axis. Returns itself. Static methods This interface inherits methods from DOMMatrixReadOnly. fromFloat32Array() Creates a new mutable DOMMatrix object given an array of single-precision (32-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix.
Otherwise, a TypeError exception is thrown. fromFloat64Array() Creates a new mutable DOMMatrix object given an array of double-precision (64-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix.
Otherwise, a TypeError exception is thrown. fromMatrix() Creates a new mutable DOMMatrix object given an existing matrix or a...
DOMMatrixReadOnly - Web APIs
fied vector. By default, the vector is (0, 0, 0). The original matrix is not changed. Static methods This interface inherits methods from DOMMatrixReadOnly. fromFloat32Array() Creates a new mutable DOMMatrix object given an array of single-precision (32-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix.
Otherwise, a TypeError exception is thrown. fromFloat64Array() Creates a new mutable DOMMatrix object given an array of double-precision (64-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix.
Otherwise, a TypeError exception is thrown. fromMatrix() Creates a new mutable DOMMatrix object given an existing matrix or a...
DOMTokenList - Web APIs
Is an integer representing the number of objects stored in the object. DOMTokenList.value A stringifier property that returns the value of the list as a DOMString. Methods DOMTokenList.item(index) Returns the item in the list by its index, or undefined if index is greater than or equal to the list's length. DOMTokenList.contains(token) Returns true if the list contains the given token,
otherwise false. DOMTokenList.add(token1[, token2[, ...tokenN]]) Adds the specified token(s) to the list. DOMTokenList.remove(token1[, token2[, ...tokenN]]) Removes the specified token(s) from the list. DOMTokenList.replace(oldToken, newToken) Replaces token with newToken. DOMTokenList.supports(token) Returns true if a given token is in the associated attribute's supported tokens. DOMTokenList.tog...
DataTransfer.setDragImage() - Web APIs
use values that are half the width and height of the image. This method must be called in the dragstart event handler. Syntax void dataTransfer.setDragImage(img | element, xOffset, yOffset); Arguments img | element An image Element element to use for the drag feedback image. If Element is an img element, then set the drag data store bitmap to the element's image (at its intrinsic size);
otherwise, set the drag data store bitmap to an image generated from the given element (the exact mechanism for doing so is not currently specified). xOffset A long indicating the horizontal offset within the image. yOffset A long indicating the vertical offset within the image. Return value void Example This example shows how to use the setDragImage() method. Note the example refers to an im...
DeprecationReportBody - Web APIs
string containing a human-readable description of the deprecation, including information such as what newer feature has superceded it, if any. This typically matches the message a browser will display in its DevTools console when a deprecated feature is used, if one is available. sourceFile A string containing the path to the source file where the deprecated feature was used, if known, or null
otherwise. lineNumber A number representing the line in the source file in which the deprecated feature was used, if known, or null
otherwise. columnNumber A number representing the column in the source file in which the deprecated feature was used, if known, or null
otherwise. Examples In our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated featu...
Document.fullscreen - Web APIs
in strict mode); the setter is a no-operation and it will be ignored. Note: Since this property is deprecated, you can determine if full-screen mode is active on the document by checking to see if Document.fullscreenElement is not null. Syntax var isFullScreen = document.fullscreen; Value A Boolean value which is true if the document is currently displaying an element in full-screen mode;
otherwise, the value is false. Example This simple function reports whether or not full-screen mode is currently active, using the obsolete fullscreen property. function isDocumentInFullScreenMode() { return document.fullscreen; } This next example, on the other hand, uses the current fullscreenElement property to determine the same thing: function isDocumentInFullScreenMode() { return document.f...
Document: fullscreenchange event - Web APIs
t Event handler property onfullscreenchange The event is sent to the Element that is transitioning into or out of full-screen mode, and this event then bubbles up to the Document. To find out whether the Element is entering or exiting full-screen mode, check the value of DocumentOrShadowRoot.fullscreenElement: if this value is null then the element is exiting full-screen mode,
otherwise it is entering full-screen mode. Examples In this example, a handler for the fullscreenchange event is added to the Document. document.addEventListener('fullscreenchange', (event) => { // document.fullscreenElement will point to the element that // is in fullscreen mode if there is one. If there isn't one, // the value of the property is null. if (document.fullscreenElement) { cons...
Document.mozSyntheticDocument - Web APIs
The Document.mozSyntheticDocument property indicates whether or not the document is a synthetic one; that is, a document representing a standalone image, video, audio, or the like. Syntax var isSynthetic = document.mozSyntheticDocument; On return, isSynthetic is true if the document is a synthetic one;
otherwise it's false. Example This can be useful if you have a contextual menu item you only want to display for synthetic documents (or, conversely, for documents that aren't synthetic). var isSynthetic = document.mozSyntheticDocument; if (isSynthetic) { /* insert your menu item here */ } Specifications Not part of any specification. ...
Document.onfullscreenchange - Web APIs
document receives a fullscreenchange event, indicating that the document is transitioning into or out of full-screen mode. Usage notes The fullscreenchange event does not directly specify whether the transition is into or out of full-screen mode, so your event handler should look at the value of Document.fullscreenElement. If it's null, the event indicates a transition out of full-screen mode.
Otherwise, the specified element is about to take over the screen. Example document.onfullscreenchange = function ( event ) { console.log("FULL SCREEN CHANGE") }; document.documentElement.onclick = function () { // requestFullscreen() must be in an event handler or it will fail document.documentElement.requestFullscreen(); } Specifications Specification Status Comment ...
Document.querySelectorAll() - Web APIs
st whose ID is userlist which have a data-active attribute whose value is 1: var container = document.querySelector("#userlist"); var matches = container.querySelectorAll("li[data-active='1']"); Accessing the matches Once the NodeList of matching elements is returned, you can examine it just like any array. If the array is empty (that is, its length property is 0), then no matches were found.
Otherwise, you can simply use standard array notation to access the contents of the list. You can use any common looping statement, such as: var highlightedItems = userList.querySelectorAll(".highlighted"); highlightedItems.forEach(function(userItem) { deleteUser(userItem); }); User notes querySelectorAll() behaves differently than most common JavaScript DOM libraries, which might lead to unexpected ...
Document.rootElement - Web APIs
It is deprecated in favor of Document.documentElement, which returns the root element for all documents. Syntax const element = document.rootElement Notes If the document is a non-empty SVG document, then the rootElement will be an SVGSVGElement, identical to the documentElement. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGDocument.rootElement' in that specification. ...
Document.scrollingElement - Web APIs
The scrollingElement read-only property of the Document interface returns a reference to the Element that scrolls the document. In standards mode, this is the root element of the document, document.documentElement. When in quirks mode, the scrollingElement attribute returns the HTML body element if it exists and is not potentially scrollable,
otherwise it returns null. Syntax var element = document.scrollingElement; Example var scrollElm = document.scrollingElement; scrollElm.scrollTop = 0; Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'scrollingElement' in that specification. Working Draft Initial definition ...
Document.title - Web APIs
document.title = newTitle; newTitle is the new title of the document. The assignment affects the return value of document.title, the title displayed for the document (e.g. ...
EffectTiming.duration - Web APIs
ing objects returned by AnimationEffectReadOnly, KeyframeEffectReadOnly, and KeyframeEffect. Syntax var timingProperties = { duration: durationInMilliseconds | "auto" }; timingProperties.duration = durationInMilliseconds | "auto"; Value The number of milliseconds long a single beginning-to-end iteration of the animation should take. The default is "auto". This value must not be negative;
otherwise, it can have any value (including positive infinity). Currently, a value of "auto" is the same as specifying 0.0. This is a forwards-compatiblity measure since in the future, "auto" will be expanded to take into account the duration of any child effects. Consider using "auto" rather than 0 if that makes sense. Exceptions TypeError The specified value is either a string other than "auto", ...
Element.clientHeight - Web APIs
It includes padding but excludes borders, margins, and horizontal scrollbars (if present). clientHeight can be calculated as: CSS height + CSS padding - height of horizontal scrollbar (if present). When clientHeight is used on the root element (the <html> element), (or on <body> if the document is in quirks mode), the viewport's height (excluding any scrollbar) is returned. This is a special case of clientHeight. Note: This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect(). ...
Element.clientWidth - Web APIs
It includes padding but excludes borders, margins, and vertical scrollbars (if present). When clientWidth is used on the root element (the <html> element), (or on <body> if the document is in quirks mode), the viewport's width (excluding any scrollbar) is returned. This is a special case of clientWidth. Note: This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect(). Syntax var intElemClientWidth = element.clientWidth; intElemClientWidth is an integer corresponding to the clientWidth of element in pixels. ...
Element: error event - Web APIs
nt object when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid. Bubbles No Cancelable No Interface Event or UIEvent Event handler property onerror The event object is a UIEvent instance if it was generated from a user interface element, or an Event instance
otherwise. Examples Live example HTML <div class="controls"> <button id="img-error" type="button">Generate image error</button> <img class="bad-img" /> </div> <div class="event-log"> <label>Event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea> </div> CSS body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: contr...
Element.getElementsByClassName() - Web APIs
, they immediately appear in the collection. Similarly, if an existing element that doesn't match names has its set of classes adjusted so that it matches, it immediately appears in the collection. The opposite is also true; as elements no longer match the set of names, they are immediately removed from the collection. In quirks mode, the class names are compared in a case-insensitive fashion.
Otherwise, they're case sensitive. Examples Matching a single class To look for elements that include among their classes a single specified class, we just provide that class name when calling getElementsByClassName(): element.getElementsByClassName('test'); This example finds all elements that have a class of test, which are also a descendant of the element that has the id of main: document.getElem...
Element.querySelectorAll() - Web APIs
se ID is "userlist" which have a "data-active" attribute whose value is "1": var container = document.querySelector("#userlist"); var matches = container.querySelectorAll("li[data-active='1']"); Accessing the matches Once the NodeList of matching elements is returned, you can examine it just like any array. If the array is empty (that is, its length property is 0), then no matches were found.
Otherwise, you can simply use standard array notation to access the contents of the list. You can use any common looping statement, such as: var highlightedItems = userList.querySelectorAll(".highlighted"); highlightedItems.forEach(function(userItem) { deleteUser(userItem); }); Note: NodeList is not a genuine array, that is to say it doesn't have the array methods like slice, some, map etc. To conver...
Element.requestFullscreen() - Web APIs
ves these events instead. Earlier implementations of the Fullscreen API would always send these events to the document rather than the element, and you may need to be able to handle that situation. Check Browser compatibility in fullscreen for specifics on when each browser made this change. Note: This method must be called while responding to a user interaction or a device orientation change;
otherwise it will fail. Syntax var promise = Element.requestFullscreen(options); Parameters options Optional A FullscreenOptions object providing options that control the behavior of the transition to full-screen mode. Currently, the only option is navigationUI, which controls whether or not to show navigation UI while the element is in full-screen mode. The default value is "auto", which indicat...
Element.setAttribute() - Web APIs
To get the current value of an attribute, use getAttribute(); to remove an attribute, call removeAttribute(). Syntax Element.setAttribute(name, value); Parameters name A DOMString specifying the name of the attribute whose value is to be set. The attribute name is automatically converted to all lower-case when setAttribute() is called on an HTML element in an HTML document. value A DOMString containing the value to assign to the attribute. ...
Element.toggleAttribute() - Web APIs
the attribute to be toggled. The attribute name is automatically converted to all lower-case when toggleAttribute() is called on an HTML element in an HTML document. force Optional A boolean value to determine whether the attribute should be added or removed, no matter whether the attribute is present or not at the moment. Return value true if attribute name is eventually present, and false
otherwise. Exceptions InvalidCharacterError The specified attribute name contains one or more characters which are not valid in attribute names. Example In the following example, toggleAttribute() is used to toggle the readonly attribute of a <input>. HTML <input value="text"> <button>toggleAttribute("readonly")</button> JavaScript var button = document.querySelector("button"); var input = docu...
Event.msConvertURL() - Web APIs
s not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The msConvertURL method instructs the HTML paste operation on how to modify the src attribute that corresponds to each file in the clipboardData.files collection, allowing
otherwise inaccessible files to be converted to blob or data URIs. This proprietary method is specific to Internet Explorer and the Microsoft Edge browser. Syntax var retVal = DragEvent.msConvertURL(file, targetType, targetURL); Parameters file [in] Type: File The file object to be converted. targetType [in] Type: DOMString One of the following values indicating the desired conversion type: "spe...
Event.returnValue - Web APIs
his property to false prevents the default action. Note: While returnValue has been adopted into the DOM standard, it is present primarily to support existing code. You should use preventDefault(), and defaultPrevented instead of this historical property. Syntax event.returnValue = bool; var bool = event.returnValue; Value A Boolean value which is true if the event has not been canceled;
otherwise, if the event has been canceled or the default has been prevented, the value is false. The value returned by returnValue is the opposite of the value returned by defaultPrevented. Usage notes returnValue was introduced into the DOM by Internet Explorer 6, and due to that browser's ubiquity became so commonly used that other browsers eventually implemented it as well. It has been adopted into t...
EventTarget.dispatchEvent() - Web APIs
patched manually with dispatchEvent(). Syntax cancelled = !target.dispatchEvent(event) Parameter event is the Event object to be dispatched. target is used to initialize the Event.target and determine which event listeners to invoke. Return Value The return value is false if event is cancelable and at least one of the event handlers which received event called Event.preventDefault().
Otherwise it returns true. The dispatchEvent() method throws UNSPECIFIED_EVENT_TYPE_ERR if the event's type was not specified by initializing the event before the method was called, or if the event's type is null or an empty string. Exceptions Exceptions thrown by event handlers are reported as uncaught exceptions. The event handlers run on a nested callstack; they block the caller until they complete,...
EventTarget.removeEventListener() - Web APIs
Notes If an EventListener is removed from an EventTarget while it is processing an event, it will not be triggered by the current actions. An EventListener will not be invoked for the event it was registered for after being removed. However, it can be reattached. Calling remov...
FetchEvent.isReload - Web APIs
Pressing the refresh button is a reload while clicking a link and pressing the back button is not. Syntax var reloaded = FetchEvent.isReload Value A Boolean. ...
Using Fetch - Web APIs
ete('X-Custom-Header'); console.log(myHeaders.get('X-Custom-Header')); // [ ] Some of these operations are only useful in ServiceWorkers, but they provide a much nicer API for manipulating headers. All of the Headers methods throw a TypeError if a header name is used that is not a valid HTTP Header name. The mutation operations will throw a TypeError if there is an immutable guard (see below).
Otherwise, they fail silently. For example: const myResponse = Response.error(); try { myResponse.headers.set('Origin', 'http://mybank.com'); } catch (e) { console.log('Cannot pretend to be a bank!'); } A good use case for headers is checking whether the content type is correct before you process it further. For example: fetch(myRequest) .then(response => { const contentType = response.heade...
FileSystemEntry - Web APIs
A FileSystem object representing the file system in which the entry is located. fullPath Read only A USVString object which provides the full, absolute path from the file system's root to the entry; it can also be thought of as a path which is relative to the root directory, prepended with a "/" character. isDirectory Read only A Boolean which is true if the entry represents a directory;
otherwise, it's false. isFile Read only A Boolean which is true if the entry represents a file. If it's not a file, this value is false. name Read only A USVString containing the name of the entry (the final part of the path, after the last "/" character). Methods This interface defines the following methods. copyTo() Copies the file or directory to a new location on the file system. getMetad...
FileSystemEntrySync - Web APIs
ther a FileEntrySync or DirectoryEntry. It includes methods for working with files--including copying, moving, removing, and reading files--as well as information about the file it points to--including the file name and its path from the root to the entry. Warning: This API was never accepted and never became standardized. Various browsers implement pieces of the File and Directory Entries API (
otherwise known as the File System API) but you should try to avoid using it. Basic concepts The FileSystemEntrySync interface includes methods that you would expect for manipulating files and directories, but it also include a really handy method for getting a URL of the entry: toURL(). It also introduces a new URL scheme: filesystem:. You can use the filesystem: scheme on Google Chrome to see all the...
File and Directory Entries API - Web APIs
're available on the Window object and implemented in LocalFileSystem: requestFileSystem() and resolveLocalFileSystemURL(). Synchronous API The synchronous API is should only be used in Workers; these calls block until they're finished executing, and simply return the results instead of using callbacks. Using them on the main thread will block the browser, which is naughty. The interfaces below
otherwise mirror the ones from the asynchronous API. FileSystemSync Represents a file system. FileSystemEntrySync The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories. FileSystemFileEntrySync Represents a single file in a file system. FileSystemDirectoryEntrySync Represents a single directory in a file syste...
accessKeyLabel - Web APIs
The HTMLElement.accessKeyLabel read-only property returns a String that represents the element's assigned access key (if any);
otherwise it returns an empty string. Syntax label = element.accessKeyLabel Example JavaScript var node = document.getElementById('btn1'); if (node.accessKeyLabel) { node.title += ' [' + node.accessKeyLabel + ']'; } else { node.title += ' [' + node.accessKey + ']'; } node.onclick = function () { var p = document.createElement('p'); p.textContent = 'Clicked!'; node.parentNode.appendChild(p); }; HTML <button accesskey="h" title="Caption" id="btn1">Hover me</button> Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLElement.accessKeyLabel' in that specification. Living Standard...
HTMLElement.isContentEditable - Web APIs
The HTMLElement.isContentEditable read-only property returns a Boolean that is true if the contents of the element are editable;
otherwise it returns false. Syntax editable = element.isContentEditable Example HTML <p id="myText1">Uneditable Paragraph</p> <p id="myText2" contentEditable="true">Editable Paragraph</p> <p id="infoText1">Can edit the first paragraph? </p> <p id="infoText2">Can edit the second paragraph? </p> JavaScript document.getElementById('infoText1').innerHTML += document.getElementById('myText1').isContentEditable; document.getElementById('infoText2').innerHTML += document.getElementById('myText2').isContentEditable; Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLElement.contenteditable' in t...
HTMLFormElement.requestSubmit() - Web APIs
ere clicked. The form's content is validated, and the form is submitted only if validation succeeds. Once the form has been submitted, the submit event is sent back to the form object. Examples In the example below, the form is submitted by attempting to send the request using requestSubmit() if it's available. If a submit button with the ID main-submit is found, that's used to submit the form.
Otherwise, the form is submitted with no submitter parameter, so it's submitted directly by the form itself. If, on the other hand, requestSubmit() isn't available, this code falls back to calling the form's submit() method. let myForm = document.querySelector("form"); let submitButton = myForm.querySelector("#main-submit"); if (myForm.requestSubmit) { if (submitButton) { myForm.requestSubmit(subm...
HTMLImageElement.alt - Web APIs
> </div> </div> CSS The CSS for this example simply sets up the styles for the layout as shown in the result below. They're not crucial to the concept shown in the HTML above, but you may expand the view below if you wish to read the CSS used. View the CSS Editors: If you change the CSS below, please be sure to close the details box using the toggle at the top of the CSS view before saving.
Otherwise, readers will find it open by default, which is not the intent here. body { margin: 0; padding: 0; } p { margin-block-start: 0; margin-block-end: 1em; margin-top: 0; margin-bottom: 1em; } .container { width: 100vh; height: 95vh; font: 16px Arial,Helvetica,sans-serif; } .left-margin { background-color: rgb(241, 240, 237, 255); width: 9em; height: 100%; float: left; ...
HTMLImageElement.currentSrc - Web APIs
ment.srcset properties. currentSrc lets you determine which image from the set of provided images was selected by the browser. Example In this example, two different sizes are provided for an image of a clock. One is 200px wide and the other is 400px wide. The sizes attribute is provided to indicate that the image should be drawn at 50% of the document width if the viewport is under 400px wide;
otherwise, the image is drawn at 90% width of the document. HTML <img src="/files/16797/clock-demo-400px.png" alt="Clock" srcset="/files/16864/clock-demo-200px.png 200w, /files/16797/clock-demo-400px.png 400w" sizes="(max-width: 400px) 50%, 90%"> JavaScript var clockImage = document.querySelector("img"); let p = document.createElement("p"); if (!clockImage.currentSrc.endsWith("200px...
HTMLImageElement.isMap - Web APIs
ay only be used on images located within an <a> element. Note: For accessibility reasons, you should generally avoid using server-side image maps, as they require the use of a mouse. Use a client-side image map instead. Syntax htmlImageElement.isMap = true|false; let isMap = htmlImageElement.isMap; Value A Boolean value which is true if the image is being used for a server-side image map;
otherwise, the value is false. Usage notes When an image marked as being part of a server-side image map is clicked, the browser constructs the string "?x,y", where x and y indicate the coordinates at which the mouse was clicked as offsets from the top-left corner of the image, specified in CSS pixels. The browser then fetches that URL from the server and displays or downloads it depending on the value ...
HTMLImageElement.lowSrc - Web APIs
This property reflects the HTML lowsrc attribute. Syntax htmlImageElement.lowSrc = imageUrl; imageUrl = htmlImageElement.lowSrc; Value A DOMString specifying the URL of a version of the image specified by src which has been modified in some fashion so that it loads significantly more quickly than the primary image. ...
HTMLImageElement.src - Web APIs
h the size multiplier 1x; that is, the image specified by src is used on low-density screens (such as typical 72 DPI or 96 DPI displays). Additionally, if you use src along with both sizes (or the corresponding sizes content attribute) and srcset in order to choose an image based on the viewport size, the src attribute is only used as a fallback for browsers that don't support sizes and srcset;
otherwise, it's not used at all. Examples Specifying a single image HTML <img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg" width="160" alt="Slices of grapefruit, looking yummy."> Result Using src with an image set When using a set of images with the srcset property, the src serves as either a fallback for older browsers, or as the 1x size of the image. HTML Result Sp...
HTMLImageElement.srcset - Web APIs
used. Space characters, other than the whitespace separating the URL and the corresponding condition descriptor, are ignored; this includes both leading and trailing space, as well as space before or after each comma. If the condition descriptor is not provided (in other words, the image candidate provides only a URL), the candidate is used as the fallback if none of the other candidates match.
Otherwise, the condition descriptor may take one of two forms: To indicate that the image resource specified by the image candidate string should be used when the image is being rendered with a particular width in pixels, provide a width descriptor comprised the number giving that width in pixels followed by the lower case letter "w". For example, to provide an image resource to be used when the rendere...
HTMLImageElement - Web APIs
azy). HTMLImageElement.naturalHeight Read only Returns an integer value representing the intrinsic height of the image in CSS pixels, if it is available; else, it shows 0. This is the height the image would be if it were rendered at its natural full size. HTMLImageElement.naturalWidth Read only An integer value representing the intrinsic width of the image in CSS pixels, if it is available;
otherwise, it will show 0. This is the width the image would be if it were rendered at its natural full size. HTMLImageElement.referrerPolicy A DOMString that reflects the referrerpolicy HTML attribute, which tells the user agent how to decide which referrer to use in order to fetch the image. Read this article for details on the possible values of this string. HTMLImageElement.sizes A DOMString reflec...
HTMLLegendElement - Web APIs
</a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits properties from its parent, HTMLElement. HTMLLegendElement.form Read only Is a HTMLFormElement representing the form that this legend belongs to. If the legend has a fieldset element as its parent, then this attribute returns the same value as the form attribute on the parent fieldset element.
Otherwise, it returns null. HTMLLegendElement.accessKey Is a DOMString representing a single-character access key to give access to the element. HTMLLegendElement.align Is a DOMString representing the alignment relative to the form set Methods No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living Stan...
HTMLMediaElement.currentSrc - Web APIs
f the chosen media resource. This could happen, for example, if the web server selects a media file based on the resolution of the user's display. The value is an empty string if the networkState property is EMPTY. Syntax var mediaUrl = audioObject.currentSrc; Value A DOMString object containing the absolute URL of the chosen media source; this may be an empty string if networkState is EMPTY;
otherwise, it will be one of the resources listed by the HTMLSourceElement contained within the media element, or the value or src if no <source> element is provided. Example var obj = document.createElement('video'); console.log(obj.currentSrc); // "" Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.currentSrc' in that specifi...
HTMLMediaElement.currentTime - Web APIs
whose timeline doesn't begin at 0 seconds cannot be seeked to a time before its timeline's earliest time. The length of the media in seconds can be determined using the duration property. Example var video = document.createElement('video'); console.log(video.currentTime); Usage notes Reduced time precision To offer protection against timing attacks and fingerprinting, browsers may round or
otherwise adjust the value returned by currentTime. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.currentTime' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLMediaElement.currentTime' in that specification. Recommendation Initial definition. ...
HTMLObjectElement - Web APIs
a DOMString that reflects the codebase HTML attribute, specifying the base path to use to resolve relative URIs. HTMLObjectElement.codeType Is a DOMString that reflects the codetype HTML attribute, specifying the content type of the data. HTMLObjectElement.contentDocument Read only Returns a Document representing the active document of the object element's nested browsing context, if any;
otherwise null. HTMLObjectElement.contentWindow Read only Returns a WindowProxy representing the window proxy of the object element's nested browsing context, if any;
otherwise null. HTMLObjectElement.data Returns a DOMString that reflects the data HTML attribute, specifying the address of a resource's data. HTMLObjectElement.declare Is a Boolean that reflects the declare HTML attribute, indicatin...
HTMLOptionElement - Web APIs
for the option. If this attribute isn't specifically set, reading it returns the element's text content. HTMLOptionElement.selected Is a Boolean that indicates whether the option is currently selected. HTMLOptionElement.text Is a DOMString that contains the text content of the element. HTMLOptionElement.value Is a DOMString that reflects the value of the value HTML attribute, if it exists;
otherwise reflects value of the Node.textContent property. Methods Inherits methods from its parent, HTMLElement. Option() Is a constructor creating an HTMLOptionElement object. It has four values: the text to display, text, the value associated, value, the value of defaultSelected, and the value of selected. The last three values are optional. Specifications Specification Status C...
HTMLScriptElement - Web APIs
pulating the behavior and execution of <script> elements (beyond the inherited HTMLElement interface). JavaScript files should be served with the application/javascript MIME type, but browsers are lenient and block them only if the script is served with an image type (image/*), video type (video/*), audio type (audio/*), or text/csv. If the script is blocked, its element receives an error event;
otherwise, it receives a load event. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width=...
The HTML DOM API - Web APIs
end" button so it can't be clicked. In addition, the user name input field is made the active focus by calling the focus() method it inherits from HTMLElement. Then addEventListener() is called to add a handler for the input event to the user name input. This code looks at the length of the current value of the input; if it's zero, then the "Send" button is disabled if it's not already disabled.
Otherwise, the code ensures that the button is enabled. With this in place, the "Send" button is always enabled whenever the user name input field has a value, and disabled when it's empty. HTML The HTML for the form looks like this: <p>Please provide the information below. Items marked with "*" are required.</p> <form action="" method="get"> <p> <label for="userName" required>Your name:</label> ...
File drag and drop - Web APIs
#drop_zone { border: 5px solid blue; width: 200px; height: 100px; } Note that dragstart and dragend events are not fired when dragging a file into the browser from the OS. Process the drop The drop event is fired when the user drops the file(s). In the following drop handler, if the browser supports DataTransferItemList interface, the getAsFile() method is used to access each file;
otherwise the DataTransfer interface's files property is used to access each file. This example shows how to write the name of each dragged file to the console. In a real application, an application may want to process a file using the File API. Note that in this example, any drag item that is not a file is ignored. function dropHandler(ev) { console.log('File(s) dropped'); // Prevent default beha...
History.pushState() - Web APIs
onal The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL;
otherwise, pushState() will throw an exception. If this parameter isn't specified, it's set to the document's current URL. Description In a sense, calling pushState() is similar to setting window.location = "#foo", in that both will also create and activate another history entry associated with the current document. But pushState() has a few advantages: The new URL can be any URL in the same origin a...
History.replaceState() - Web APIs
to the replaceState method. The state object can be null. title Most browsers currently ignore this parameter, although they may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state. url Optional The URL of the history entry. The new URL must be of the same origin as the current URL;
otherwise replaceState throws an exception. Examples Suppose https://www.mozilla.org/foo.html executes the following JavaScript: const stateObj = { foo: 'bar' }; history.pushState(stateObj, '', 'bar.html'); The explanation of these two lines above can be found in the Example of pushState() method section of the Working with the History API article. Then suppose https://www.mozilla.org/bar.html execute...
Working with the History API - Web APIs
URL The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL;
otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL. Note: In Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) through Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), the passed object is serialized using JSON. Starting in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3), the object is seriali...
IDBCursorSync - Web APIs
UPLICATE 3 This cursor does not include duplicates, and its direction is monotonically decreasing in the order of keys. Methods continue() Advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter. If no key is specified, advance to the immediate next position. Returns false if the cursor has reached the end of its range;
otherwise returns true. bool continue ( in optional any key ); Parameters key The key to which to move the cursor's position. remove() Deletes the record at the cursor's position, without changing the cursor's position void delete ( ) raises (DatabaseException); Exceptions This method can raise an IDBDatabaseException with the following code: NOT_ALLOWED_ERR If the underlying index or o...
IDBFactorySync - Web APIs
f indexed databases. Method overview IDBDatabaseSync open (in DOMString name, in DOMString description, in optional boolean modifyDatabase) raises (IDBDatabaseException); Methods open() Opens and returns a connection to a database. Blocks the calling thread until the connection object is ready to return. If there is already a database with the specified name, it uses that one;
otherwise, it creates the database using the specified name and description. IDBDatabaseSync open ( in DOMString name, in DOMString description ) raises (IDBDatabaseException); Parameters name The name for the database. description The description for the database. Returns IDBDatabaseSync An object to access the open database. Exceptions This method can raise an IDBDatabaseException w...
compareVersion - Web APIs
sion object containing version information or a String in the format major.minor.release.build, where major, minor, release, and build are integer values representing version information. Returns If the versions are the same or if Software Installation is not enabled, this method returns 0. If the version of registryName is smaller (earlier) than version, this method returns a negative number.
Otherwise, this method returns a positive number. In particular, this method returns one of the following values: -5 component not present or not registered. -4 registryName has a smaller (earlier) major number than version. -3 registryName has a smaller (earlier) minor number than version. -2 registryName has a smaller (earlier) release number than version. -1 registryName has a smaller (earli...
enabled - Web APIs
The method reflects the value of the Software Installation preference in the user interface, and of the xpinstall.enabled preference in pref.js. ...
getVersion - Web APIs
t Version Registry for the specified component. It is used in both trigger scripts and installation scripts. Method of InstallTrigger object Syntax InstallVersion getVersion ( String component ); Parameters The getVersion method has one parameter: component The name of a component in the Client Version Registry. Returns If Software Installation is disabled, this method returns NULL.
Otherwise, it returns an InstallVersion object representing the version of the component. If the component has not been registered in the Client Version Registry or if the specified component was installed with a null version, this method returns null. Installing a component with a NULL version indicates that the component should always be updated when the opportunity arises. ...
IntersectionObserverEntry.rootBounds - Web APIs
erty is a DOMRectReadOnly corresponding to the target's root intersection rectangle, offset by the IntersectionObserver.rootMargin if one is specified. Syntax var rootBounds = IntersectionObserverEntry.rootBounds; Value A DOMRectReadOnly which describes the root intersection rectangle. For roots which are the Document's viewport, this rectangle is the bounds rectangle of the entire document.
Otherwise, it's the bounds of the root element. This rectangle is offset by the values in IntersectionObserver.rootMargin. Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserverEntry.rootBounds' in that specification. Working Draft Initial definition ...
IntersectionObserverEntry - Web APIs
The IntersectionObserverEntry interface of the Intersection Observer API describes the intersection between the target element and its root container at a specific moment of transition. Instances of IntersectionObserverEntry are delivered to an IntersectionObserver callback in its entries parameter;
otherwise, these objects can only be obtained by calling IntersectionObserver.takeRecords(). Properties IntersectionObserverEntry.boundingClientRect Read only Returns the bounds rectangle of the target element as a DOMRectReadOnly. The bounds are computed as described in the documentation for Element.getBoundingClientRect(). IntersectionObserverEntry.intersectionRatio Read only Returns the ratio of the intersectionRect to the boundingClientRect. IntersectionObserverEntry.intersectionRect Read...
Intersection Observer API - Web APIs
r. The root intersection rectangle is the rectangle used to check against the target or targets. This rectangle is determined like this: If the intersection root is the implicit root (that is, the top-level Document), the root intersection rectangle is the viewport's rectangle. If the intersection root has an overflow clip, the root intersection rectangle is the root element's content area.
Otherwise, the root intersection rectangle is the intersection root's bounding client rectangle (as returned by calling getBoundingClientRect() on it). The root intersection rectangle can be adjusted further by setting the root margin, rootMargin, when creating the IntersectionObserver. The values in rootMargin define offsets added to each side of the intersection root's bounding box to create the final ...
InterventionReportBody - Web APIs
ture. message A string containing a human-readable description of the intervention, including information such how the intervention could be avoided. This typically matches the message a browser will display in its DevTools console when an intervention is imposed, if one is available. sourceFile A string containing the path to the source file where the intervention occurred, if known, or null
otherwise. lineNumber A number representing the line in the source file in which the intervention occurred, if known, or null
otherwise. columnNumber A number representing the column in the source file in which the intervention occurred, if known, or null
otherwise. Examples let options = { types: ['intervention'], buffered: true } let observer = new ReportingObserver(function(reports, observer...
KeyboardEvent.charCode - Web APIs
e)}\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. If the key pressed generates a character (e.g., 'a'), charCode is set to the code of that character; charCode respects the letter case (in other words, charCode takes into account whether the shift key is held down).
Otherwise, the code of the pressed key is stored in keyCode. When one or more modifier keys are pressed, there are some complex rules for charCode. See Gecko Keypress Event for details. charCode is never set in the keydown and keyup events. In these cases, keyCode is set instead. To get the code of the key regardless of whether it was stored in keyCode or charCode, query the which property. Characters ...
KeyboardEvent.getModifierState() - Web APIs
Syntax var active = event.getModifierState(keyArg); Returns A Boolean Parameters keyArg A modifier key value. The value must be one of the KeyboardEvent.key values which represent modifier keys, or the string "Accel" . This is case-sensitive. Modifier keys on Internet Explorer IE9 uses "Scroll" for "ScrollLock" and "Win" for "OS". ...
KeyboardEvent.initKeyEvent() - Web APIs
is a combination of keys containing the Alt key. shiftKeyArg A Boolean that is true if the virtual key to be generated is a combination of keys containing the Shift key. metaKeyArg Is a Boolean that is true if the virtual key to be generated is a combination of keys containing the Meta key. keyCodeArg Is a unsigned long representing the virtual key code value of the key which was depressed,
otherwise 0. See KeyboardEvent.keyCode for the list of key codes. charCodeArg Is a unsigned long representingthe Unicode character associated with the depressed key
otherwise 0. Example var event = document.createEvent('KeyboardEvent'); // create a key event // define the event event.initKeyEvent("keypress", // typeArg, true, // canBubbleArg, tru...
KeyboardEvent.location - Web APIs
y is pressed on a standard 101 key US keyboard. This value is only used for keys that have more than one possible location on the keyboard. DOM_KEY_LOCATION_NUMPAD 3 The key was on the numeric keypad, or has a virtual key code that corresponds to the numeric keypad. Note: When NumLock is locked, Gecko always returns DOM_KEY_LOCATION_NUMPAD for the keys on the numeric pad.
Otherwise, when NumLock is unlocked and the keyboard actually has a numeric keypad, Gecko always returns DOM_KEY_LOCATION_NUMPAD too. On the other hand, if the keyboard doesn't have a keypad, such as on a notebook computer, some keys become Numpad only when NumLock is locked. When such keys fires key events, the location attribute value depends on the key. That is, it must not be DOM_KEY_LOCATION_NUMPAD. ...
LargestContentfulPaint - Web APIs
er leaves the tab. // Catch errors since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let lcp; const po = new PerformanceObserver((entryList) => { const entries = entryList.getEntries(); const lastEntry = entries[entries.length - 1]; // Update `lcp` to the latest value, using `renderTime` if it's available, //
otherwise using `loadTime`. (Note: `renderTime` may not be available on // image elements loaded cross-origin without the `Timing-Allow-Origin` header.) lcp = lastEntry.renderTime || lastEntry.loadTime; }); po.observe({type: 'largest-contentful-paint', buffered: true}); // Send data to the server. addEventListener('visibilitychange', function fn() { if (lcp && document.visibilityState...
MediaDeviceInfo - Web APIs
merated value that is either "videoinput", "audioinput" or "audiooutput". MediaDeviceInfo.labelRead only Returns a DOMString that is a label describing this device (for example "External USB Webcam"). For security reasons, the label field is always blank unless an active media stream exists or the user has granted persistent permission for media device access. The set of device labels could
otherwise be used as part of a fingerprinting mechanism to identify a user. Methods None. Example Here's an example that uses enumerateDevices() to get a list of devices. if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) { console.log("enumerateDevices() not supported."); return; } // List cameras and microphones. navigator.mediaDevices.enumerateDevices() .then(function(d...
MediaQueryList.matches - Web APIs
of the MediaQueryList interface is a Boolean that returns true if the document currently matches the media query list, or false if not. You can be notified when the value of matches changes by watching for the change event to be fired at the MediaQueryList. Syntax var matches = <varm>MediaQueryList.matches; Value A Boolean which is true if the document currently matches the media query list;
otherwise, it's false. Examples This example detects viewport orientation changes by creating a media query using the orientation media feature: function addMQListener(mq, callback) { if (mq.addEventListener) { mq.addEventListener("change", callback); } else { mq.addListener(callback); } } addMQListener(window.matchMedia("(orientation:landscape)"), event => { if (event.matches) { ...
MediaStream() - Web APIs
Syntax newStream = new MediaStream(); newStream = new MediaStream(stream); newStream = new MediaStream(tracks[]); Parameters stream A different MediaStream object whose tracks are added to the newly-created stream automatically. ...
MediaStream.getTrackById() - Web APIs
ck object representing the track with the specified ID string. If there is no track with the specified ID, this method returns null. Syntax var track = MediaStream.getTrackById(id); Parameters id A DOMString which identifies the track to be returned. Return value If a track is found for which MediaStreamTrack.id matches the specified id string, that MediaStreamTrack object is returned.
Otherwise, the returned value is null. Example This example activates a commentary track on a video by ducking the audio level of the main audio track to 50%, then enabling the commentary track. stream.getTrackById("primary-audio-track").applyConstraints({ volume: 0.5 }); stream.getTrackById("commentary-track").enabled = true; Specifications Specification Status Comment Med...
MediaStream - Web APIs
a new MediaStream object. You can create an empty stream, a stream which is based upon an existing stream, or a stream that contains a specified list of tracks (specified as an array of MediaStreamTrack objects). Properties This interface inherits properties from its parent, EventTarget. MediaStream.active Read only A Boolean value that returns true if the MediaStream is active, or false
otherwise. MediaStream.ended Read only A Boolean value set to true if the end of the stream has been reached. This has been removed from the specification; you should instead check the value of MediaStreamTrack.readyState to see if its value is ended for the track or tracks you want to ensure have finished playing. MediaStream.id Read only A DOMString containing 36 characters denoting a universa...
MediaStreamTrack.enabled - Web APIs
In the case of audio, a disabled track generates frames of silence (that is, frames in which every sample's value is 0). For video tracks, every frame is filled entirely with black pixels. ...
MediaTrackConstraints.aspectRatio - Web APIs
alue is the width divided by the height and is rounded to ten decimal places. For example, the standard high-definition video aspect ratio of 16:9 can be computed as 1920/1080, or 1.7777777778. If this value is a number, the user agent will attempt to obtain media whose aspect ratio is as close as possible to this number given the capabilities of the hardware and the other constraints specified.
Otherwise, the value of this ConstrainDouble will guide the user agent in its efforts to provide an exact match to the required aspect ratio (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an example. Specifications Specification Status Co...
MediaTrackConstraints.channelCount - Web APIs
since browsers will simply ignore any constraints they're unfamiliar with. Syntax var constraintsObject = { channelCount: constraint }; constraintsObject.channelCount = constraint; Value If this value is a number, the user agent will attempt to obtain media whose channel count is as close as possible to this number given the capabilities of the hardware and the other constraints specified.
Otherwise, the value of this ConstrainLong will guide the user agent in its efforts to provide an exact match to the required channel count (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. The channel count is 1 for monaural sound, 2 for stereo, and so forth. Example See Example: Constraint exerciser in Capabilities, constraints, and settings ...
MediaTrackConstraints.frameRate - Web APIs
frameRate: constraint }; constraintsObject.frameRate = constraint; Value A ConstrainDouble describing the acceptable or required value(s) for a video track's frame rate, in frames per second. If this value is a number, the user agent will attempt to obtain media whose frame rate is as close as possible to this number given the capabilities of the hardware and the other constraints specified.
Otherwise, the value of this ConstrainDouble will guide the user agent in its efforts to provide an exact match to the required frame rate (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an example. Specifications Specification Status Comm...
MediaTrackConstraints.height - Web APIs
this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Syntax var constraintsObject = { height: constraint }; constraintsObject.height = constraint; Value If this value is a number, the user agent will attempt to obtain media whose height is as close as possible to this number given the capabilities of the hardware and the other constraints specified.
Otherwise, the value of this ConstrainLong will guide the user agent in its efforts to provide an exact match to the required height (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an example. Specifications Specification Status Comment ...
MediaTrackConstraints.latency - Web APIs
pecified in seconds. In audio processing, latency is the time between the start of processing (when sound occurs in the real world, or is generated by a hardware device) and the data being made available to the next step in the audio input or output process. In most cases, low latency is desirable for performance and user experience purposes, but when power consumption is a concern, or delays are
otherwise acceptable, higher latency might be acceptable. If this property's value is a number, the user agent will attempt to obtain media whose latency tends to be as close as possible to this number given the capabilities of the hardware and the other constraints specified.
Otherwise, the value of this ConstrainDouble will guide the user agent in its efforts to provide an exact match to the required la...
MediaTrackConstraints.sampleRate - Web APIs
essary since browsers will simply ignore any constraints they're unfamiliar with. Syntax var constraintsObject = { sampleRate: constraint }; constraintsObject.sampleRate = constraint; Value If this value is a number, the user agent will attempt to obtain media whose sample rate is as close as possible to this number given the capabilities of the hardware and the other constraints specified.
Otherwise, the value of this ConstrainLong will guide the user agent in its efforts to provide an exact match to the required sample rate (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an example. Specifications Specification Status Comme...
MediaTrackConstraints.sampleSize - Web APIs
imply ignore any constraints they're unfamiliar with. Syntax var constraintsObject = { sampleSize: constraint }; constraintsObject.sampleSize = constraint; Value If this value is a number, the user agent will attempt to obtain media whose sample size (in bits per linear sample) is as close as possible to this number given the capabilities of the hardware and the other constraints specified.
Otherwise, the value of this ConstrainLong will guide the user agent in its efforts to provide an exact match to the required sample size (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. Since this property can only represent linear sample sizes, this constraint can only be met by devices that can produce audio with linear samples. Example S...
MediaTrackControls.volume - Web APIs
= constraint; Value A ConstrainDouble describing the acceptable or required value(s) for an audio track's volume, on a linear scale where 0.0 means silence and 1.0 is the highest supported volume. If this value is a number, the user agent will attempt to obtain media whose volume is as close as possible to this number given the capabilities of the hardware and the other constraints specified.
Otherwise, the value of this ConstrainDouble will guide the user agent in its efforts to provide an exact match to the required volume (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. Any constraint set which only permits values outside the range 0.0 to 1.0 cannot be satisfied and will result in failure. Example See Example: Constraint exercis...
MediaTrackConstraints.width - Web APIs
ly this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Syntax var constraintsObject = { width: constraint }; constraintsObject.width = constraint; Value If this value is a number, the user agent will attempt to obtain media whose width is as close as possible to this number given the capabilities of the hardware and the other constraints specified.
Otherwise, the value of this ConstrainLong will guide the user agent in its efforts to provide an exact match to the required width (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an example. Specifications Specification Status Comment ...
Capabilities, constraints, and settings - Web APIs
eo" button to be clicked: document.getElementById("startButton").addEventListener("click", function() { startVideo(); }, false); Applying constraint set updates Next, we set up an event listener for the "Apply Constraints" button. If it's clicked and there's not already media in use, we call startVideo(), and let that function handle starting the stream with the specified settings in place.
Otherwise, we follow these steps to apply the updated constraints to the already-active stream: buildConstraints() is called to construct updated MediaTrackConstraints objects for the audio track (audioConstraints) and the video track (videoConstraints). MediaStreamTrack.applyConstraints() is called on the video track (if there is one) to apply the new videoConstraints. If this succeeds, the contents o...
MessageEvent.ports - Web APIs
when sending a message to a shared worker). Syntax var myPorts = messageEvent.ports; Value An array of MessagePort objects. Example onconnect = function(e) { var port = e.ports[0]; port.addEventListener('message', function(e) { var workerResult = 'Result: ' + (e.data[0] * e.data[1]); port.postMessage(workerResult); }); port.start(); // Required when using addEventListener.
Otherwise called implicitly by onmessage setter. } Specifications Specification Status Comment HTML Living StandardThe definition of 'ports' in that specification. Living Standard Initial definition ...
MessageEvent - Web APIs
-- we then use MessagePort start() method to start the port, and the onmessage handler to deal with messages sent from the main threads. onconnect = function(e) { var port = e.ports[0]; port.addEventListener('message', function(e) { var workerResult = 'Result: ' + (e.data[0] * e.data[1]); port.postMessage(workerResult); }); port.start(); // Required when using addEventListener.
Otherwise called implicitly by onmessage setter. } Specifications Specification Status Comment HTML Living StandardThe definition of 'MessageEvent' in that specification. Living Standard ...
Microdata DOM API - Web APIs
operties element . itemValue [ = value ] Returns the element's value. Can be set, to change the element's value. Setting the value when the element has no itemprop attribute or when the element's value is an item throws an InvalidAccessError exception. element . properties If the element has an itemscope attribute, returns an HTMLPropertiesCollection object with all the element's properties.
Otherwise, an empty HTMLPropertiesCollection object. Code example This sample shows how the getItems() method can be used to obtain a list of all the top-level microdata items of a particular type given in the document: var cats = document.getItems("http://example.com/feline"); Once an element representing an item has been obtained, its properties can be extracted using the properties IDL attribute. Th...
Microsoft API extensions - Web APIs
These extensions are prefixed with MS or ms. Note: These APIs will only work in Microsoft applications, and are not on a standards track. ...
MouseEvent.getModifierState() - Web APIs
See the document of KeyboardEvent.getModifierState() for details. Syntax var active = event.getModifierState(keyArg); Returns A Boolean Parameters keyArg A modifier key value. The value must be one of the KeyboardEvent.key values which represent modifier keys or "Accel". This is case-sensitive. ...
msPlayToPrimary - Web APIs
compatibilities between implementations and the behavior may change in the future. msPlayToPrimary is a read/write property which gets or sets the primary DLNA PlayTo device. This proprietary property is specific to Internet Explorer and Microsoft Edge. Syntax ptr = object.msPlayToPrimary; Value Boolean value set to true indicates that the device is the primary DLNA PlayTo device,
otherwise false. Example // Microsoft extensions interface HTMLImageElement : HTMLElement { attribute boolean msPlayToDisabled; attribute boolean msPlayToPrimary; attribute DOMString msPlayToPreferredSourceUri; }; See also HTMLMediaElement ...
Navigation Timing API - Web APIs
f getting the response using code like this: const connectTime = perfData.responseEnd - perfData.requestStart; Here, the time at which the request was initiated (requestStart). from the time at which the response was finished being received (responseEnd). Calculate page render time As another example of an interesting piece of data you can obtain using the Navigation Timing API that you can't
otherwise easily get, you can get the amount of time it took to render the page: const renderTime = perfData.domComplete - perfData.domLoading; This is obtained by starting with the time at which loading of the DOM and its dependencies is complete (domComplete) and subtracting from it the time at which parsing of the DOM began (domLoading). Specifications Specification Status Comment ...
Navigator.doNotTrack - Web APIs
The Navigator.doNotTrack property returns the user's Do Not Track setting, which indicates whether the user is requesting web sites and advertisers to not track them. The value of the property reflects that of the DNT HTTP header, i.e. values of "1", "0", or "unspecified". Example console.log(navigator.doNotTrack); // prints "1" if DNT is enabled; "0" if the user opted-in for tracking;
otherwise this is "unspecified" Specifications Specification Status Comment Tracking Preference Expression (DNT)The definition of 'Navigator.doNotTrack' in that specification. Obsolete Initial definition ...
Navigator.msLaunchUri() - Web APIs
backOptional A function matching the signature of MSLaunchUriCallback to be executed if the protocol handler is present. noHandlerCallbackOptional A function matching MSLaunchUriCallback to be executed if the protocol handler is not present. Return value undefined. Usage notes If a default protocol handler is available on the system that matches the URI, the successCallback is invoked,
otherwise, the noHandlerCallback is called. To help protect a user's privacy, Windows displays a prompt for the user to allow the service or app to be launched. The user can choose to not see the prompt after the first instance for a particular protocol and automatically open the app or service without a user intervention. The msLaunchUri() method does not support HTTP, Secure Hypertext Transfer Protocol ...
Navigator.registerProtocolHandler() - Web APIs
ermitted schemes For security reasons, registerProtocolHandler() restricts which schemes can be registered. A custom scheme may be registered as long as: The custom scheme's name begins with web+ The custom scheme's name includes at least 1 letter after the web+ prefix The custom scheme has only lowercase ASCII letters in its name. For example, web+burger, as shown in the Example below. ...
Navigator.sendBeacon() - Web APIs
of data over HTTP to a web server. Syntax navigator.sendBeacon(url, data); Parameters url The URL that will receive the data. Can be relative or absolute. data A ArrayBuffer, ArrayBufferView, Blob, DOMString, FormData, or URLSearchParams object containing the data to send. Return values The sendBeacon() method returns true if the user agent successfully queued the data for transfer.
Otherwise, it returns false. Description This method is for analytics and diagnostics that send data to a server before the document is unloaded, where sending the data any sooner may miss some possible data collection. For example, which link the user clicked before navigating away and unloading the page. Ensuring that data has been sent during the unloading of a document has traditionally been difficu...
Navigator - Web APIs
property to return the correct value. Navigator.battery Read only Returns a BatteryManager object you can use to get information about the battery charging status. Navigator.connection Read only Provides a NetworkInformation object containing information about the network connection of a device. Navigator.cookieEnabled Read only Returns false if setting a cookie will be ignored and true
otherwise. Navigator.geolocation Read only Returns a Geolocation object allowing accessing the location of the device. NavigatorConcurrentHardware.hardwareConcurrency Read only Returns the number of logical processor cores available. NavigatorPlugins.javaEnabled Read only Returns a Boolean flag indicating whether the host browser is Java-enabled or not. Navigator.keyboard Read only Returns a...
Node.hasChildNodes() - Web APIs
The Node.hasChildNodes() method returns a Boolean value indicating whether the given Node has child nodes or not. Syntax bool = node.hasChildNodes(); Return value A Boolean that is true if the node has child nodes, and false
otherwise. Example let foo = document.getElementById('foo'); if (foo.hasChildNodes()) { // Do something with 'foo.childNodes' } Polyfill Here is one possible polyfill: ;(function(prototype) { prototype.hasChildNodes = prototype.hasChildNodes || function() { return !!this.firstChild; } })(Node.prototype); There are various ways to determine whether the node has a child node: node.hasChildNodes() node.firstChild != null (or just node.firstChild) node.childNodes && node.childNodes.length (or node.childNodes.length > 0) Specifications Specif...
Notification.permission - Web APIs
t's check if the browser supports notifications if (!("Notification" in window)) { console.log("This browser does not support desktop notification"); } // Let's check whether notification permissions have alredy been granted else if (Notification.permission === "granted") { // If it's okay let's create a notification var notification = new Notification("Hi there!"); } //
Otherwise, we need to ask the user for permission else if (Notification.permission !== 'denied' || Notification.permission === "default") { Notification.requestPermission(function (permission) { // If the user accepts, let's create a notification if (permission === "granted") { var notification = new Notification("Hi there!"); } }); } // At last, if the user has den...
Notification.requestPermission() - Web APIs
// Let's check if the browser supports notifications if (!("Notification" in window)) { alert("This browser does not support desktop notification"); } // Let's check whether notification permissions have already been granted else if (Notification.permission === "granted") { // If it's okay let's create a notification var notification = new Notification("Hi there!"); } //
Otherwise, we need to ask the user for permission else if (Notification.permission !== "denied") { Notification.requestPermission().then(function (permission) { // If the user accepts, let's create a notification if (permission === "granted") { var notification = new Notification("Hi there!"); } }); } // At last, if the user has denied notifications, and you // wa...
Notification - Web APIs
// Let's check if the browser supports notifications if (!("Notification" in window)) { alert("This browser does not support desktop notification"); } // Let's check whether notification permissions have already been granted else if (Notification.permission === "granted") { // If it's okay let's create a notification var notification = new Notification("Hi there!"); } //
Otherwise, we need to ask the user for permission else if (Notification.permission !== "denied") { Notification.requestPermission().then(function (permission) { // If the user accepts, let's create a notification if (permission === "granted") { var notification = new Notification("Hi there!"); } }); } // At last, if the user has denied notifications, and you // wa...
Page Visibility API - Web APIs
}, false); // When the video plays, set the title. videoElement.addEventListener("play", function(){ document.title = 'Playing'; }, false); } Properties added to the Document interface The Page Visibility API adds the following properties to the Document interface: Document.hidden Read only Returns true if the page is in a state considered to be hidden to the user, and false
otherwise. Document.visibilityState Read only A DOMString indicating the document's current visibility state. Possible values are: visible The page content may be at least partially visible. In practice this means that the page is the foreground tab of a non-minimized window. hidden The page's content is not visible to the user, either due to the document's tab being in the background or part ...
PannerNode.coneInnerAngle - Web APIs
and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneOuterAngle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneOuterGain = 0; // increase the Z position to ensure the cone has an effect // (
otherwise the sound is located at the same position as the listener) panner.positionZ.setValueAtTime(1, context.currentTime); Having set up the PannerNode, we can now schedule some updates to its Y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yRotationToVector(0); // schedule the no-rotation vector immediately panner.orientat...
PannerNode.coneOuterAngle - Web APIs
and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneOuterAngle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneOuterGain = 0; // increase the Z position to ensure the cone has an effect // (
otherwise the sound is located at the same position as the listener) panner.positionZ.setValueAtTime(1, context.currentTime); Having set up the PannerNode, we can now schedule some updates to its Y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yRotationToVector(0); // schedule the no-rotation vector immediately panner.orientat...
PannerNode.coneOuterGain - Web APIs
and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneOuterAngle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneOuterGain = 0; // increase the Z position to ensure the cone has an effect // (
otherwise the sound is located at the same position as the listener) panner.positionZ.setValueAtTime(1, context.currentTime); Having set up the PannerNode, we can now schedule some updates to its Y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yRotationToVector(0); // schedule the no-rotation vector immediately panner.orientat...
PannerNode.orientationX - Web APIs
and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneOuterAngle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneOuterGain = 0; // increase the Z position to ensure the cone has an effect // (
otherwise the sound is located at the same position as the listener) panner.positionZ.setValueAtTime(1, context.currentTime); Having set up the PannerNode, we can now schedule some updates to its Y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yRotationToVector(0); // schedule the no-rotation vector immediately panner.orientat...
PannerNode.orientationY - Web APIs
and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneOuterAngle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneOuterGain = 0; // increase the Z position to ensure the cone has an effect // (
otherwise the sound is located at the same position as the listener) panner.positionZ.setValueAtTime(1, context.currentTime); Having set up the PannerNode, we can now schedule some updates to its Y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yRotationToVector(0); // schedule the no-rotation vector immediately panner.orientat...
PannerNode.orientationZ - Web APIs
and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneOuterAngle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneOuterGain = 0; // increase the Z position to ensure the cone has an effect // (
otherwise the sound is located at the same position as the listener) panner.positionZ.setValueAtTime(1, context.currentTime); Having set up the PannerNode, we can now schedule some updates to its Y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yRotationToVector(0); // schedule the no-rotation vector immediately panner.orientat...
performance.now() - Web APIs
ample Date.now), the timestamps returned by performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision. Also unlike Date.now(), the values returned by performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP).
Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now(). Reduced time precision To offer protection against timing attacks and fingerprinting, the precision of performance.now() might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision preference is enabled by default and defaults to 1ms. // reduced time precision (...
PerformanceResourceTiming.redirectEnd - Web APIs
er receiving the last byte of the response of the last redirect. When fetching a resource, if there are multiple HTTP redirects, and any of the redirects have an origin that is different from the current document, and the timing allow check algorithm passes for each redirected resource, this property returns the time immediately after receiving the last byte of the response of the last redirect;
otherwise, zero is returned. Note: This feature is available in Web Workers. Syntax resource.redirectEnd; Return value A timestamp immediately after receiving the last byte of the response of the last redirect. Example In the following example, the value of the *Start and *End properties of all "resource" type events are logged. function print_PerformanceEntries() { // Use getEntriesByType() to ...
PerformanceResourceTiming.redirectStart - Web APIs
property returns a timestamp representing the start time of the fetch which that initiates the redirect. If there are HTTP redirects when fetching the resource and if any of the redirects are not from the same origin as the current document, but the timing allow check algorithm passes for each redirected resource, this property returns the starting time of the fetch that initiates the redirect;
otherwise, zero is returned. Note: This feature is available in Web Workers. Syntax resource.redirectStart; Return value A timestamp representing the start time of the fetch which initiates the redirect. Example In the following example, the value of the *Start and *End properties of all "resource" type events are logged. function print_PerformanceEntries() { // Use getEntriesByType() to just ge...
PointerEvent.pressure - Web APIs
er input. Syntax var pressure = pointerEvent.pressure; Return value pressure The normalized pressure of the pointer input in the range of 0 to 1, inclusive, where 0 and 1 represent the minimum and maximum pressure the hardware is capable of detecting, respectively. For hardware that does not support pressure, such as a mouse, the value is 0.5 when the pointer is active buttons state and 0
otherwise. Example In this snippet, when a pointerdown event is fired, different functions are called depending on the value of the event's pressure property. someElement.addEventListener('pointerdown', function(event) { if (event.pressure == 0) { // No pressure process_no_pressure(event); } else if (event.pressure == 1) { // Maximum pressure process_max_pressure(event); } else { ...
Using Pointer Events - Web APIs
s is very similar to the previous function; the only real differences are that we draw a small square to mark the end and that when we call Array.splice(), we simply remove the old entry from the ongoing touch list, without adding in the updated information. The result is that we stop tracking that touch point. Handling canceled touches If the user's finger wanders into browser UI, or the touch
otherwise needs to be canceled, the pointercancel event is sent, and we call the handleCancel() function below. function handleCancel(evt) { log("pointercancel: id = " + evt.pointerId); var idx = ongoingTouchIndexById(evt.pointerId); ongoingTouches.splice(idx, 1); // remove it; we're done } Since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without d...
Proximity Events - Web APIs
ties. The UserProximityEvent event provides a rough approximation of the distance, expressed through a boolean. The UserProximityEvent.near property is true if the object is close or false if the object is far. Example window.addEventListener('userproximity', function(event) { if (event.near) { // let's power off the screen navigator.mozPower.screenEnabled = false; } else { //
Otherwise, let's power on the screen navigator.mozPower.screenEnabled = true; } }); Specifications Specification Status Comment Proximity SensorThe definition of 'Proximity Events' in that specification. Working Draft Initial specification ...
PushSubscription.expirationTime - Web APIs
Syntax var expirationTime = pushSubscription.expirationTime Value A DOMHighResTimeStamp. Specifications Specification Status Comment Push APIThe definition of 'expirationTime' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
PushSubscription - Web APIs
ndpoint and allows unsubscription from a push service. An instance of this interface can be serialized. Properties PushSubscription.endpoint Read only A USVString containing the endpoint associated with the push subscription. PushSubscription.expirationTime Read only A DOMHighResTimeStamp of the subscription expiration time associated with the push subscription, if there is one, or null
otherwise. PushSubscription.options Read only An object containing the options used to create the subscription. PushSubscription.subscriptionId Read only A DOMString containing the subscription ID associated with the push subscription. Methods PushSubscription.getKey() Returns an ArrayBuffer which contains the client's public key, which can then be sent to a server and used in encrypting ...
RTCConfiguration - Web APIs
cy enum defines string constants which specify what ICE candidates are gathered to support non-multiplexed RTCP. <<<add a link to info about multiplexed RTCP. Constant Description "negotiate" Instructs the ICE agent to gather both RTP and RTCP candidates. If the remote peer can multiplex RTCP, then RTCP candidates are multiplexed atop the corresponding RTP candidates.
Otherwise, both the RTP and RTCP candidates are returned, separately. "require" Tells the ICE agent to gather ICE candidates for only RTP, and to multiplex RTCP atop them. If the remote peer doesn't support RTCP multiplexing, then session negotiation fails. Using certificates When you wish to provide your own certificates for use by an RTCPeerConnection instead of having the RTCPeerConn...
RTCDataChannel.ordered - Web APIs
elivery of messages; the default is true, which indicates that the data channel is indeed ordered. This is set when the RTCDataChannel is created, by setting the ordered property on the RTCDataChannelInit object passed as RTCPeerConnection.createDataChannel()'s options parameter. Syntax var ordered = aDataChannel.ordered; A Boolean value which is true if in-order delivery is guaranteed and is
otherwise false. Example var pc = new RTCPeerConnection(); var dc = pc.createDataChannel("my channel"); if (!dc.ordered) { // Handle unordered messaging } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.ordered' in that specification. Candidate Recommendation Initial specification. ...
RTCIceCandidate.address - Web APIs
The address field's value is set when the RTCIceCandidate() constructor is used. You can't specify the address in the options object, but the address is automatically extracted from the candidate a-line, if it's formatted properly. Syntax var address = RTCIceCandidate.address; Value A DOMString providing the IP address from which the candidate comes. ...
RTCIceCandidate.usernameFragment - Web APIs
Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCIceCandidate.usernameFragment' in that specification. Candidate Recommendation Initial definition. ...
RTCIceCandidate - Web APIs
the media stream within the component with which the candidate is associated, or null if no such association exists. sdpMLineIndex Read only If not null, sdpMLineIndex indicates the zero-based index number of the media description (as defined in RFC 4566) in the SDP with which the candidate is associated. tcpType Read only If protocol is "tcp", tcpType represents the type of TCP candidate.
Otherwise, tcpType is null. type Read only A DOMString indicating the type of candidate as one of the strings from the RTCIceCandidateType enumerated type. usernameFragment Read only A DOMString containing a randomly-generated username fragment ("ice-ufrag") which ICE uses for message integrity along with a randomly-generated password ("ice-pwd"). You can use this string to verify generations of ICE ...
RTCIceCandidatePairStats.circuitBreakerTriggerCount - Web APIs
The RTCIceCandidatePairStats property circuitBreakerTriggerCount indicates the number of times the circuit-breaker has been triggered to indicate a connection timeout or other unexpected connection abort on this specific connection configuration. A circuit breaker trigger is fired each time the connection times out or
otherwise needs to be halted automatically. Syntax cbtCount = rtcIceCandidatePairStats.circuitBreakerTriggerCount; Value An integer value indicating the number of times the circuit-breaker has been triggered for the 5-tuple used by this connection. A 5-tuple defining a TCP connection is made up of the following data: The source IP address. The source port number. The destination IP address. The destination port number. Network protocol. Specifications Specific...
RTCIceCandidatePairStats - Web APIs
n this candidate pair. circuitBreakerTriggerCount Optional An integer value indicating the number of times the circuit-breaker has been triggered for this particular 5-tuple (the set of five values comprising a TCP connection: source IP address, source port number, destination IP address, destination port number, and protocol). The circuit breaker is triggered whenever a connection times out or
otherwise needs to be automatically aborted. consentExpiredTimestamp Optional A DOMHighResTimeStamp value indicating the time at which the most recent STUN binding response expired. This value is undefined if no valid STUN binding responses have been sent on the candidate pair; this can only happen if responsesReceived is 0. consentRequestsSent Optional The total number of consent requests that have be...
RTCIceCandidateStats.address - Web APIs
CandidateStats.address; Value Either an IPv4 or IPv6 address or a fully-qualified domain name, which corresponds to the candidate. If the value of address is comprised entirely of digits from 0-9 with periods as separators, the value is interpreted as an IPv4 address. If the value is entirely comprised of hexadecimal digits and colon (":") characters, it is interpreted as an IPv6 address.
Otherwise, the address is presumed to be a fully-qualified domain name, which is resolved first using an AAAA record (assuming IPv6 is available), then using an A record (if no result is found or the device onlu supports IPv4). If multiple IP addresses are returned in response to the query, the user agent selects one, which is then used for the duration of ICE processing. Usage notes The address propert...
RTCIceCandidateStats.relayProtocol - Web APIs
Syntax relayProtocol = rtcIceCandidateStats.relayProtocol; Value A DOMString identifying the protocol being used by the endpoint to communicate with the TURN server. The possible values are: tcp TCP (Transport Control Protocol) is being used to communicate with the TURN server. ...
RTCOfferOptions.iceRestart - Web APIs
eConnectionState === "failed") { if (pc.restartIce) { pc.restartIce(); } else { pc.createOffer({ iceRestart: true }) .then(pc.setLocalDescription) .then(sendOfferToServer); } } } If the state changes to failed, this handler starts by looking to see if the RTCPeerConnection includes the restartIce() method; if it does, we call that to request an ICE restart.
Otherwise, we call back to the older technique: we manually create a new offer with iceRestart set to true, then that offer is set as the new local description for the connection. After that, the offer is sent to the server by calling a custom function sendOfferToServer(). Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definitio...
RTCPeerConnection() - Web APIs
emote peer unless it can successfully authenticate with the given name. rtcpMuxPolicy Optional The RTCP mux policy to use when gathering ICE candidates, in order to support non-multiplexed RTCP. The value must be one of those from the RTCRtcpMuxPolicy enum. The default is "require". Return value A newly-created RTCPeerConnection object, configured as described by configuration, if specified;
otherwise, configured to appropriate basic defaults. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection()' in that specification. Candidate Recommendation Initial definition. ...
RTCPeerConnection.addTrack() - Web APIs
ream = null; pc.ontrack = ev => { if (ev.streams && ev.streams[0]) { videoElem.srcObject = ev.streams[0]; } else { if (!inboundStream) { inboundStream = new MediaStream(); videoElem.srcObject = inboundStream; } inboundStream.addTrack(ev.track); } } Here, the track event handler adds the track to the first stream specified by the event, if a stream is specified.
Otherwise, the first time ontrack is called, a new stream is created and attached to the video element, and then the track is added to the new stream. From then on, new tracks are added to that stream. You could also just create a new stream for each track received: pc.ontrack = ev => { if (ev.streams && ev.streams[0]) { videoElem.srcObject = ev.streams[0]; } else { let inboundStream = new Me...
RTCPeerConnection: addstream event - Web APIs
Bubbles No Cancelable No Interface MediaStreamEvent Event handler property RTCPeerConnection.onaddstream You can, similarly, watch for streams to be removed from the connection by monitoring the removestream event. Examples This example looks to determine if the user's browser supports the track event. If it does, a track event listener is set up;
otherwise, an addstream event listener is set up. pc is an RTCPeerConnection. if (pc.addTrack !== undefined) { pc.ontrack = ev => { ev.streams.forEach(stream => doAddStream(stream)); } } else { pc.onaddstream = ev => { doAddStream(ev.stream); } } This calls a function doAddStream() once for each stream being added to the RTCPeerConnection, regardless of whether the browser sends addstrea...
RTCPeerConnection.localDescription - Web APIs
The read-only property RTCPeerConnection.localDescription returns an RTCSessionDescription describing the session for the local end of the connection. If it has not yet been set, this is null. Syntax var sessionDescription = peerConnection.localDescription; On a more fundamental level, the returned value is the value of RTCPeerConnection.pendingLocalDescription if that property isn't null;
otherwise, the value of RTCPeerConnection.currentLocalDescription is returned. See Pending and current descriptions in WebRTC connectivity for details on this algorithm and why it's used. Example This example looks at the localDescription and displays an alert containing the RTCSessionDescription object's type and sdp fields. var pc = new RTCPeerConnection(); ... var sd = pc.localDescription; if (sd) { ...
RTCPeerConnection.pendingLocalDescription - Web APIs
rrentLocalDescription or RTCPeerConnection.localDescription to get the current state of the endpoint. For details on the difference, see Pending and current descriptions in WebRTC connectivity. Syntax sessionDescription = RTCPeerConnection.pendingLocalDescription; Return value If a local description change is in progress, this is an RTCSessionDescription describing the proposed configuration.
Otherwise, this returns null. Example This example looks at the pendingLocalDescription to determine whether or not there's a description change being processed. var pc = new RTCPeerConnection(); ... var sd = pc.pendingLocalDescription; if (sd) { // There's a description change underway! } else { // No description change pending } Specifications Specification Status Comment ...
RTCPeerConnection.pendingRemoteDescription - Web APIs
RTCPeerConnection.remoteDescription to get the current session description for the remote endpoint. For details on the difference, see Pending and current descriptions in WebRTC connectivity. Syntax sessionDescription = RTCPeerConnection.pendingRemoteDescription; Return value If a remote description change is in progress, this is an RTCSessionDescription describing the proposed configuration.
Otherwise, this returns null. Example This example looks at the pendingRemoteDescription to determine whether or not there's a description change being processed. var pc = new RTCPeerConnection(); ... var sd = pc.pendingRemoteDescription; if (sd) { // There's a description change underway! } else { // No description change pending } Specifications Specification Status Comment ...
RTCPeerConnection.remoteDescription - Web APIs
scription which has been received over the signaling server (as either an offer or an answer) and then put into effect by your code calling RTCPeerConnection.setRemoteDescription() in response. Syntax var sessionDescription = peerConnection.remoteDescription; On a more fundamental level, the returned value is the value of RTCPeerConnection.pendingRemoteDescription if that property isn't null;
otherwise, the value of RTCPeerConnection.currentRemoteDescription is returned. See Pending and current descriptions in WebRTC connectivity for details on this algorithm and why it's used. Example This example looks at the remoteDescription and displays an alert containing the RTCSessionDescription object's type and sdp fields. var pc = new RTCPeerConnection(); ... var sd = pc.remoteDescription; if (sd)...
RTCPeerConnection.setLocalDescription() - Web APIs
he description is omitted, the WebRTC runtime tries to automatically do the right thing. Implicit description If you don't explicity provide a session description, the WebRTC runtime will try to handle it correctly. If the signaling state is one of stable, have-local-offer, or have-remote-pranswer, the WebRTC runtime automatically creates a new offer and sets that as the new local description.
Otherwise, setLocalDescription() creates an answer, which becomes the new local description. Type of the description parameter The description is of type RTCSessionDescriptionInit, which is a serialized version of a RTCSessionDescription browser object. They're interchangeable: myPeerConnection.createOffer().then(function(offer) { return myPeerConnection.setLocalDescription(offer); }); This is equiv...
RTCPeerConnection - Web APIs
cy enum defines string constants which specify what ICE candidates are gathered to support non-multiplexed RTCP. <<<add a link to info about multiplexed RTCP. Constant Description "negotiate" Instructs the ICE agent to gather both RTP and RTCP candidates. If the remote peer can multiplex RTCP, then RTCP candidates are multiplexed atop the corresponding RTP candidates.
Otherwise, both the RTP and RTCP candidates are returned, separately. "require" Tells the ICE agent to gather ICE candidates for only RTP, and to multiplex RTCP atop them. If the remote peer doesn't support RTCP multiplexing, then session negotiation fails. RTCSignalingState enum The RTCSignalingState enum specifies the possible values of RTCPeerConnection.signalingState, which indicate...
RTCRtpContributingSource.audioLevel - Web APIs
The read-only audioLevel property of the RTCRtpContributingSource interface indicates the audio level contained in the last RTP packet played from the described source. audioLevel will be the level value defined in [RFC6465] if the RFC 6465 header extension is present, and
otherwise null. Syntax var audioLevel = RTCRtpContributingSource.audioLevel Value A double-precision floating-point number which indicates the volume level of the audio in the most recently received RTP packet from the source described by the RTCRtpContributingSource. This value, which is in the range 0.0 to 1.0, is on a linear scale and its value is defined in dBov, or decibels (overload). This is the amplitude relative to the point at which clipping of the audio begins to occur. A value of 1.0 represents 0 dBov (maximum v...
RTCRtpReceiver.getCapabilities() static function - Web APIs
always called using the form: capabilities = RTCRtpReceiver.getCapabilities("audio"); The returned set of capabilities is the most optimistic possible list. It is entirely possible that certain combinations of options may fail to work when you actually try to use them. Calling RTCRtpReceiver.getCapabilities() doesn't prime the browser in any way to handle media. Nothing is loaded, fetched, or
otherwise prepared. It's simply a means of determining what might be usable before starting to try to access media. Because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. For that reason, in privacy-sensitive con...
RTCRtpSender.getCapabilities() static function - Web APIs
s is always called using the form: capabilities = RTCRtpSender.getCapabilities("audio"); The returned set of capabilities is the most optimistic possible list. It is entirely possible that certain combinations of options may fail to work when you actually try to use them. Calling RTCRtpSender.getCapabilities() doesn't prime the browser in any way to handle media. Nothing is loaded, fetched, or
otherwise prepared. It's simply a means of determining what might be usable before starting to try to access media. Because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. For that reason, in privacy-sensitive con...
RTCRtpTransceiver - Web APIs
CRtpTransceiver is used to represent this pairing, along with other important state from the media section. Each non-disabled SRTP media section is always represented by exactly one transceiver. A transceiver is uniquely identified using its mid property, which is the same as the media ID (mid) of its corresponding m-line. An RTCRtpTransceiver is associated with an m-line if its mid is non-null;
otherwise it's considered disassociated. Properties currentDirection Read only A string from the enum RTCRtpTransceiverDirection which indicates the transceiver's current directionality, or null if the transceiver is stopped or has never participated in an exchange of offers and answers. direction A string from the enum RTCRtpTransceiverDirection which is used to set the transceiver's desired direc...
RTCStatsReport - Web APIs
An RTCIceCandidatePairStats object providing statistics related to an RTCIceTransport. Candidate pairs other than the currently active pair for the transport are deleted when the RTCPeerConnection changes its RTCPeerConnection.iceGatheringState to new during an ICE restart. The active candidate pair is deleted after the transport switches to another candidate pair; this change cannot be detected
otherwise. certificate An RTCCertificateStats object providing statistics related to a certificate being used by an RTCIceTransport. codec An RTCCodecStats object containing statistics about a codec currently being used by RTP streams to send or receive data for the RTCPeerConnection. csrc An RTCContributingSourceStats object which contains statistics related to a contributing source (CSRC) that cont...
RTCStatsType - Web APIs
An RTCIceCandidatePairStats object providing statistics related to an RTCIceTransport. Candidate pairs other than the currently active pair for the transport are deleted when the RTCPeerConnection changes its RTCPeerConnection.iceGatheringState to new during an ICE restart. The active candidate pair is deleted after the transport switches to another candidate pair; this change cannot be detected
otherwise. certificate An RTCCertificateStats object providing statistics related to a certificate being used by an RTCIceTransport. codec An RTCCodecStats object containing statistics about a codec currently being used by RTP streams to send or receive data for the RTCPeerConnection. csrc An RTCContributingSourceStats object which contains statistics related to a contributing source (CSRC) that cont...
ReadableStreamBYOBReader.releaseLock() - Web APIs
The releaseLock() method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. If the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently;
otherwise, the reader will appear closed. A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by the reader's ReadableStreamBYOBReader.read() method has not finished. This will result in a TypeError being thrown. Syntax readableStreamBYOBReader.releaseLock(); Parameters None. Return value undefined. Exceptions TypeError The source object is not a ReadableStreamBYOBReader, or a read request is pending. Examples TBD. Specifications ...
ReadableStreamDefaultReader.releaseLock() - Web APIs
A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by the reader's ReadableStreamDefaultReader.read() method has not finished. This will result in a TypeError being thrown. ...
SVGAngle - Web APIs
reflected through the animVal attribute is always read only. An SVGAngle object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. An SVGAngle object can be associated with a particular element. The associated element is used to determine which element's content attribute to update if the object reflects an attribute. Unless
otherwise described, an SVGAngle object is not associated with any element. Every SVGAngle object operates in one of two modes: Reflect the base value of a reflected animatable attribute (being exposed through the baseVal member of an SVGAnimatedAngle), Be detached, which is the case for SVGAngle objects created with SVGSVGElement.createSVGAngle(). Constants SVG_ANGLETYPE_UNKNOWN Some unknown t...
SVGMarkerElement - Web APIs
orientType SVGAnimatedEnumeration Corresponds to attribute orient on the given marker element. One of the Marker Orientation Types defined on this interface. orientAngle SVGAnimatedAngle Corresponds to attribute orient on the given marker element. If markerUnits is SVG_MARKER_ORIENT_ANGLE, the angle value for attribute orient;
otherwise, it will be set to zero. Methods This also inherits methods from its parent, SVGElement, and implements properties from SVGStylable. setOrientToAngle(in SVGAngle angle) void Sets the value of attribute orient to the given angle. Exceptions: ...
SVGSVGElement - Web APIs
ed. SVGSVGElement.pixelUnitToMillimeterY A float representing the size of a pixel unit along the y-axis of the viewport. SVGSVGElement.screenPixelToMillimeterX User interface (UI) events in DOM Level 2 indicate the screen positions at which the given UI event occurred. When the browser actually knows the physical size of a "screen unit", this float attribute will express that information;
otherwise, user agents will provide a suitable default value (such as .28mm). SVGSVGElement.screenPixelToMillimeterY Corresponding size of a screen pixel along the y-axis of the viewport. SVGSVGElement.useCurrentView The initial view (i.e., before magnification and panning) of the current innermost SVG document fragment can be either the "standard" view, i.e., based on attributes on the <svg> element...
Screen.lockOrientation() - Web APIs
ndscape-primary depends on natural orientation of devices. For example, if the panel resolution is 1280*800, default will make it landscape, if the resolution is 800*1280, default will make it to portrait. Note: It's possible to set several locks at the same time. So, if the lock is set for only one orientation, the screen orientation will never change until the screen orientation is unlocked.
Otherwise, the screen orientation will change from an orientation to another as long as the orientations are amongst the orientations the device has been locked to. Return value Returns true if the orientation was authorized to be locked or false if the orientation locking was denied. Note that the return value doesn't indicate that the screen orientation is indeed locked: there may be a delay. Example...
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
ediately for both the current client and all other active clients. Syntax ServiceWorkerGlobalScope.skipWaiting().then(function() { //Do something }); Returns A Promise that immediately resolves with undefined. Example While self.skipWaiting() can be called at any point during the service worker's execution, it will only have an effect if there's a newly installed service worker that might
otherwise remain in the waiting state. Therefore, it's common to call self.skipWaiting() from inside of an InstallEvent handler. The following example causes a newly installed service worker to progress into the activating state, regardless of whether there is already an active service worker. self.addEventListener('install', function(event) { // The promise that skipWaiting() returns can be safely ign...
SharedWorker - Web APIs
-- we then use MessagePort start() method to start the port, and the onmessage handler to deal with messages sent from the main threads. onconnect = function(e) { var port = e.ports[0]; port.addEventListener('message', function(e) { var workerResult = 'Result: ' + (e.data[0] * e.data[1]); port.postMessage(workerResult); }); port.start(); // Required when using addEventListener.
Otherwise called implicitly by onmessage setter. } Specifications Specification Status Comment HTML Living StandardThe definition of 'SharedWorker' in that specification. Living Standard No change from Unknown. ...
StorageManager.persist() - Web APIs
Syntax navigator.storage.persist().then(function(persistent) { ... }) Parameters None. Return value A Promise that resolves to a Boolean. ...
Using the Storage Access API - Web APIs
The Storage Access API should be used by embedded cross-origin documents to verify whether they have access to their first-party storage and, if not, to request access. We'll briefly look at a common storage access scenario. Usage notes The Storage Access API is designed to allow embedded content to request access to storage that would
otherwise be blocked when a user's browser is set to block all third-party cookies. Since embedded content won't know which storage policy is in use by the user, it's best to always check whether the embedded frame has storage access before attempting to read or write from storage. This is particularly true for Document.cookie access, as browsers will often return an empty cookie jar when third-party cookies are blocked. Accessing a user's cookies in an embedde...
Streams API concepts - Web APIs
to start reading your stream, you typically need to cancel the first reader before you do anything else (although you can tee streams, see the Teeing section below) Note that there are two different types of readable stream. As well as the conventional readable stream there is a type called a byte stream -- this is an extended version of a conventional stream for reading underlying byte sources (
otherwise known as BYOB, or "bring your own buffer") sources. These allow streams to be read straight into a buffer supplied by the developer, minimizing the copying required. Which underlying stream (and by extension, reader and controller) your code will use depends on how the stream was created in the first place (see the ReadableStream() constructor page). Important: Byte streams are not implemented ...
Using readable streams - Web APIs
m. You'll rarely have to do this, so we'll just concentrate on the first one for now. The first object can contain up to five members, only the first of which is required: start(controller) -- A method that is called once, immediately after the ReadableStream is constructed. Inside this method, you should include code that sets up the stream functionality, e.g. beginning generation of data or
otherwise getting access to the source. pull(controller) -- A method that, when included, is called repeatedly until the stream's internal queue is full. This can be used to control the stream as more chunks are enqueued. cancel() -- A method that, when included, will be called if the app signals that the stream is to be cancelled (e.g. if ReadableStream.cancel() is called). The contents should do whatev...
SubtleCrypto.deriveBits() - Web APIs
gorithm, baseKey, length ); Parameters algorithm is an object defining the derivation algorithm to use. To use ECDH, pass an EcdhKeyDeriveParams object. To use HKDF, pass an HkdfParams object. To use PBKDF2, pass a Pbkdf2Params object. baseKey is a CryptoKey representing the input to the derivation algorithm. If algorithm is ECDH, this will be the ECDH private key.
Otherwise it will be the initial key material for the derivation function: for example, for PBKDF2 it might be a password, imported as a CryptoKey using SubtleCrypto.importKey(). length is a number representing the number of bits to derive. Return value result is a Promise that fulfills with an ArrayBuffer containing the derived bits. Exceptions The promise is rejected when one of the following ex...
SubtleCrypto.deriveKey() - Web APIs
extractable, keyUsages ); Parameters algorithm is an object defining the derivation algorithm to use. To use ECDH, pass an EcdhKeyDeriveParams object. To use HKDF, pass an HkdfParams object. To use PBKDF2, pass a Pbkdf2Params object. baseKey is a CryptoKey representing the input to the derivation algorithm. If algorithm is ECDH, then this will be the ECDH private key.
Otherwise it will be the initial key material for the derivation function: for example, for PBKDF2 it might be a password, imported as a CryptoKey using SubtleCrypto.importKey(). derivedKeyAlgorithm is an object defining the algorithm the derived key will be used for. For HMAC: pass an HmacKeyGenParams object. For AES-CTR, AES-CBC, AES-GCM, or AES-KW: pass an AesKeyGenParams object. extract...
SubtleCrypto.exportKey() - Web APIs
a string value describing the data format in which the key should be exported. It can be one of the following: raw: Raw format. pkcs8: PKCS #8 format. spki: SubjectPublicKeyInfo format. jwk: JSON Web Key format. key is the CryptoKey to export. Return value result is a Promise. If format was jwk, then the promise fulfills with a JSON object containing the key.
Otherwise the promise fulfills with an ArrayBuffer containing the key. Exceptions The promise is rejected when one of the following exceptions is encountered: InvalidAccessError Raised when trying to export a non-extractable key. NotSupported Raised when trying to export in an unknown format. TypeError Raised when trying to use an invalid format. Examples Note: You can try the working e...
SubtleCrypto.wrapKey() - Web APIs
As with SubtleCrypto.exportKey(), you specify an export format for the key. To export a key, it must have CryptoKey.extractable set to true. ...
TextTrack.mode - Web APIs
DOMString which indicates the track's current mode. The text track mode is one of the values listed below, under Text track mode constants. Text track mode constants The text track mode--sometimes identified using the IDL enum TextTrackMode--must be one of the following values: disabled The text track is currently disabled. While the track's presence is exposed in the DOM, the user agent is
otherwise ignoring it. No cues are active, no events are being fired, and the user agent won't attempt to obtain the track's cues. This is the default value, unless the text track has the default Boolean attribute is specified, in which case the default is showing. hidden The text track is currently active but the cues aren't being displayed. If the user agent hasn't tried to obtain the track's cues yet,...
TextTrack - Web APIs
tchType Read only Returns a DOMString which indicates the track's in-band metadata track dispatch type. needs details TextTrack.kind Read only Returns a DOMString indicating what kind of text track the TextTrack describes. The value must be one of those in the TextTrackKind enum. TextTrack.label Read only A human-readable DOMString which contains the text track's label, if one is present;
otherwise, this is an empty string (""), in which case a custom label may need to be generated by your code using other attributes of the track, if the track's label needs to be exposed to the user. TextTrack.language Read only A DOMString which specifies the text language in which the text track's contents is written. The value must adhere to the format specified in the Tags for Identifying Languages (...
TextTrackList: change event - Web APIs
The change event is fired when a text track is made active or inactive, or a textTrackList is
otherwise changed. Bubbles No Cancelable No Interface Event Event handler property onchange Examples Using addEventListener(): const mediaElement = document.querySelectorAll('video, audio')[0]; mediaElement.textTracks.addEventListener('change', (event) => { console.log(`'${event.type}' event fired`); }); Using the onchange event handler property: const mediaElement = document.querySelector('video, audio'); mediaElement.textTracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; Specifications Specification Status HTML Living StandardThe definition of 'change' in that specification. Living ...
TouchEvent.altKey - Web APIs
This property is Read only . Syntax var altEnabled = touchEvent.altKey; Return value altEnabled true if the alt key is enabled for this event; and false if the alt is not enabled. Example This example illustrates how to access the TouchEvent key modifier properties: TouchEvent.altKey, TouchEvent.ctrlKey, TouchEvent.metaKey and TouchEvent.shiftKey. ...
TouchEvent.ctrlKey - Web APIs
This property is Read only . Syntax var ctrlEnabled = touchEvent.ctrlKey; Return value ctrlEnabled true if the control key is enabled for this event; and false if the control is not enabled. Example The TouchEvent.altKey example includes an example of this property's usage. ...
TouchEvent.metaKey - Web APIs
This property is Read only . Note: On Macintosh keyboards, this is the ? Command key. On Windows keyboards, this is the Windows key (?). Syntax var metaEnabled = touchEvent.metaKey; Return value metaEnabled true if the Meta key is enabled for this event; and false if the Meta is not enabled. Example The TouchEvent.altKey example includes an example of this property's usage. ...
TouchEvent.shiftKey - Web APIs
This property is Read only . Syntax var shiftEnabled = touchEvent.shiftKey; Return value shiftEnabled true if the shift key is enabled for this event; and false if the shift key is not enabled. Example The TouchEvent.altKey example includes an example of this property's usage. ...
TouchEvent.targetTouches - Web APIs
object that includes those TPs that are currently touching the surface and started on the element that is the target of the current event. As such, the targetTouches list is a strict subset of the touches list. In following code snippet, the function compares the length of the touches list to the the length of the targetTouches list and returns true if the lengths are the same and returns false
otherwise. function touches_in_target(ev) { // Return true if all of the touches are within the target element; //
otherwise return false. return (ev.touches.length == ev.targetTouches.length ? true : false); } Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. Touch Events Recommendation Initial definition. ...
TouchList.item() - Web APIs
rns null if the index is not less than the length of the list. Example This code example illustrates the use of the TouchList interface's item method and the length property. target = document.getElementById("target"); target.addEventListener('touchstart', function(ev) { // If this touchstart event started on element target, // set touch to the first item in the targetTouches list; //
otherwise set touch to the first item in the touches list var touch; if (ev.targetTouches.length >= 1) touch = ev.targetTouches.item(0); else touch = ev.touches.item(0); }, false); Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. Touch Events Recommendation Initial definition. ...
TouchList.length - Web APIs
value numTouches The number of touch points in touchList. Example This code example illustrates the use of the TouchList interface's item method and the length property. target = document.getElementById("target"); target.addEventListener('touchstart', function(ev) { // If this touchstart event started on element target, // set touch to the first item in the targetTouches list; //
otherwise set touch to the first item in the touches list var touch; if (ev.targetTouches.length >= 1) touch = ev.targetTouches.item(0); else touch = ev.touches.item(0); }, false); Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. Touch Events Recommendation Initial definition. ...
Touch events - Web APIs
is is very similar to the previous function; the only real differences are that we draw a small square to mark the end and that when we call Array.splice(), we simply remove the old entry from the ongoing touch list, without adding in the updated information. The result is that we stop tracking that touchpoint. Handling canceled touches If the user's finger wanders into browser UI, or the touch
otherwise needs to be canceled, the touchcancel event is sent, and we call the handleCancel() function below. function handleCancel(evt) { evt.preventDefault(); console.log("touchcancel."); var touches = evt.changedTouches; for (var i = 0; i < touches.length; i++) { var idx = ongoingTouchIndexById(touches[i].identifier); ongoingTouches.splice(idx, 1); // remove it; we're done } } Sin...
UIEvent.isChar - Web APIs
Some keystroke combinations may raise events but not produce any character (example: ctrl-alt-?). When this is the case, isChar returns false. It is used when event handlers need to do something like echo the input on the screen. ...
URLSearchParams.get() - Web APIs
The get() method of the URLSearchParams interface returns the first value associated to the given search parameter. Note: This feature is available in Web Workers. Syntax URLSearchParams.get(name) Parameters name The name of the parameter to return. Return value A USVString if the given search parameter is found;
otherwise, null. Examples If the URL of your page is https://example.com/?name=Jonathan&age=18 you could parse out the 'name' and 'age' parameters using: let params = new URLSearchParams(document.location.search.substring(1)); let name = params.get("name"); // is the string "Jonathan" let age = parseInt(params.get("age"), 10); // is the number 18 Requesting a parameter that isn't present in the query string will return null: let address = params.get("address"); // null S...
ValidityState - Web APIs
equired syntax (when type is email or url), or false if the syntax is correct. If true, the element matches the :invalid CSS pseudo-class. valid Read only A Boolean that is true if the element meets all its validation constraints, and is therefore considered to be valid, or false if it fails any constraint. If true, the element matches the :valid CSS pseudo-class; the :invalid CSS pseudo-class
otherwise. valueMissing Read only A Boolean that is true if the element has a required attribute, but no value, or false
otherwise. If true, the element matches the :invalid CSS pseudo-class. Specifications Specification Status Comment HTML Living StandardThe definition of 'ValidityState' in that specification. Living Standard Living Standard HTML 5.1The definit...
VideoTrack.label - Web APIs
Syntax var videoTrackLabel = VideoTrack.label; Value A DOMString specifying the track's human-readable label, if one is available in the track metadata.
Otherwise, an empty string ("") is returned. For example, a track whose kind is "sign" might have a label such as "A sign-language interpretation.". Example This example returns an array of track kinds and labels for potential use in a user interface to select video tracks for a specified media element. ...
VideoTrackList.selectedIndex - Web APIs
The read-only VideoTrackList property selectedIndex returns the index of the currently selected track, if any, or -1
otherwise. Syntax var index = VideoTrackList.selectedIndex; Value A number indicating the index of the currently selected track, if any, or -1
otherwise. Specifications Specification Status Comment HTML Living StandardThe definition of 'VideoTrackList: selectedIndex' in that specification. Living Standard ...
VideoTrackList - Web APIs
eve an instance of this object with HTMLMediaElement.videoTracks. The individual tracks can be accessed using array syntax or functions such as forEach() for example. Properties This interface also inherits properties from its parent interface, EventTarget. length Read only The number of tracks in the list. selectedIndex Read only The index of the currently selected track, if any, or -1
otherwise. Event handlers onaddtrack An event handler to be called when the addtrack event is fired, indicating that a new video track has been added to the media element. onchange An event handler to be called when the change event occurs -- that is, when the value of the selected property for a track has changed, due to the track being made active or inactive. onremovetrack An event handler to ...
WebGL2RenderingContext.getFragDataLocation() - Web APIs
nderingContext.getFragDataLocation() method of the WebGL 2 API returns the binding of color numbers to user-defined varying out variables. Syntax GLint gl.getFragDataLocation(program, name); Parameters program A WebGLProgram to query. name A DOMString specifying the name of the user-defined varying out variable. Return value A GLint indicating the assigned color number binding, or -1
otherwise. Examples // program is a linked WebGLProgram gl.getFragDataLocation(program, 'fragColor'); Specifications Specification Status Comment WebGL 2.0The definition of 'getFragDataLocation' in that specification. Editor's Draft Initial definition. OpenGL ES 3.0The definition of 'glGetFragDataLocation' in that specification. Standard Man page of the (si...
WebGLRenderingContext.getActiveUniform() - Web APIs
d[0].foo d[0].bar d[1].foo d[1].bar Uniform blocks: one entry for each member. If the uniform block has an instance name, the block name is prefixed. E.g. uniform Block { float foo; }; will result in foo, and uniform Block { float bar; } e; will result in Block.bar. The size attribute of the return value corresponds to the length of the array for uniforms declared as arrays.
Otherwise, it is 1 (this includes interface blocks instanced with arrays). Exceptions gl.INVALID_VALUE is generated if the program WebGLProgram is invalid (not linked, deleted, etc.). gl.INVALID_VALUE is generated if index is not in the range [0, gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS) - 1]. Examples const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); for (let i = 0...
WebGLRenderingContext.getAttribLocation() - Web APIs
of the WebGL API returns the location of an attribute variable in a given WebGLProgram. Syntax GLint gl.getAttribLocation(program, name); Parameters program A WebGLProgram containing the attribute variable. name A DOMString specifying the name of the attribute variable whose location to get. Return value A GLint number indicating the location of the variable name if found. Returns -1
otherwise. Examples gl.getAttribLocation(program, 'vColor'); Specifications Specification Status Comment WebGL 1.0The definition of 'getAttribLocation' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGetAttribLocation' in that specification. Standard Main page of the OpenGL API. ...
WebGLRenderingContext.getVertexAttrib() - Web APIs
n. Syntax any gl.getVertexAttrib(index, pname); Parameters index A GLuint specifying the index of the vertex attribute. pname A GLenum specifying the information to query. Possible values: gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: Returns the currently bound WebGLBuffer. gl.VERTEX_ATTRIB_ARRAY_ENABLED: Returns a GLboolean that is true if the vertex attribute is enabled at this index.
Otherwise false. gl.VERTEX_ATTRIB_ARRAY_SIZE: Returns a GLint indicating the size of an element of the vertex array. gl.VERTEX_ATTRIB_ARRAY_STRIDE: Returns a GLint indicating the number of bytes between successive elements in the array. 0 means that the elements are sequential. gl.VERTEX_ATTRIB_ARRAY_TYPE: Returns a GLenum representing the array type. One of gl.BYTE, gl.UNSIGNED_BYTE, ...
WebGLRenderingContext.isBuffer() - Web APIs
Syntax GLboolean gl.isBuffer(buffer); Parameters buffer A WebGLBuffer to check. Return value A GLboolean indicating whether or not the buffer is valid. Examples Creating a buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.isBuffer(buffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isBuffer' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.isFramebuffer() - Web APIs
Syntax GLboolean gl.isFramebuffer(framebuffer); Parameters framebuffer A WebGLFramebuffer to check. Return value A GLboolean indicating whether or not the frame buffer is valid. Examples Checking a frame buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); gl.isFramebuffer(framebuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isFramebuffer' in that specification. ...
WebGLRenderingContext.isProgram() - Web APIs
Syntax GLboolean gl.isProgram(program); Parameters program A WebGLProgram to check. Return value A GLboolean indicating whether or not the program is valid. Examples Checking a program var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var program = gl.createProgram(); // ... gl.isProgram(program); Specifications Specification Status Comment WebGL 1.0The definition of 'isProgram' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.isRenderbuffer() - Web APIs
Syntax GLboolean gl.isRenderbuffer(renderbuffer); Parameters renderbuffer A WebGLRenderbuffer to check. Return value A GLboolean indicating whether or not the renderbuffer is valid. Examples Checking a renderbuffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderbuffer = gl.createRenderbuffer(); gl.isRenderbuffer(renderbuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isRenderbuffer' in that specification. ...
WebGLRenderingContext.isShader() - Web APIs
Syntax GLboolean gl.isShader(shader); Parameters shader A WebGLShader to check. Return value A GLboolean indicating whether or not the shader is valid. Examples Checking a shader var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var shader = gl.createShader(gl.VERTEX_SHADER); // ... gl.isShader(shader); Specifications Specification Status Comment WebGL 1.0The definition of 'isShader' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.isTexture() - Web APIs
Syntax GLboolean gl.isTexture(texture); Parameters texture A WebGLTexture to check. Return value A GLboolean indicating whether or not the texture is valid. Examples Checking a texture var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); gl.isTexture(texture); Specifications Specification Status Comment WebGL 1.0The definition of 'isTexture' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext - Web APIs
rawingBufferHeight The read-only height of the current drawing buffer. Should match the height of the canvas element associated with this context. WebGLRenderingContext.getContextAttributes() Returns a WebGLContextAttributes object that contains the actual context parameters. Might return null, if the context is lost. WebGLRenderingContext.isContextLost() Returns true if the context is lost,
otherwise returns false. WebGLRenderingContext.makeXRCompatible() Ensures the context is compatible with the user's XR hardware, re-creating the context if necessary with a new configuration to do so. This can be used to start an application using standard 2D presentation, then transition to using a VR or AR mode later. Viewing and clipping WebGLRenderingContext.scissor() Defines the scissor box. ...
Clearing by clicking - Web APIs
canvas.addEventListener("click", switchColor, false); button.addEventListener("click", switchColor, false); // A variable to hold the WebGLRenderingContext. var gl; // The click event handler. function switchColor () { // Referring to the externally defined gl variable. // If undefined, try to obtain the WebGLRenderingContext. // If failed, alert user of failure. //
Otherwise, initialize the drawing buffer (the viewport). if (!gl) { gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { alert("Failed to get WebGL context.\n" + "Your browser or device may not support WebGL."); return; } gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); } // Get ...
Clearing with colors - Web APIs
ecause it only needs to run once. window.removeEventListener(evt.type, setupWebGL, false); // References to the document elements. var paragraph = document.querySelector("p"), canvas = document.querySelector("canvas"); // Getting the WebGL rendering context. var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); // If failed, inform user of failure.
Otherwise, initialize // the drawing buffer (the viewport) and clear the context // with a solid color. if (!gl) { paragraph.innerHTML = "Failed to get WebGL context. " + "Your browser or device may not support WebGL."; return; } paragraph.innerHTML = "Congratulations! Your browser supports WebGL. "; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); // Se...
Raining rectangles - Web APIs
gRect.position[1], rainingRect.size[0] , rainingRect.size[1]); gl.clear(gl.COLOR_BUFFER_BIT); rainingRect.position[1] -= rainingRect.velocity; if (rainingRect.position[1] < 0) { misses += 1; missesDisplay.innerHTML = misses; rainingRect = new Rectangle(); } // We are using setTimeout for animation. So we reschedule // the timeout to call drawAnimation again in 17ms. //
Otherwise we won't get any animation. timer = setTimeout(drawAnimation, 17); } function playerClick (evt) { // We need to transform the position of the click event from // window coordinates to relative position inside the canvas. // In addition we need to remember that vertical position in // WebGL increases from bottom to top, unlike in the browser // window. var position = [ evt.pageX...
WebGL constants - Web APIs
to createShader to define a vertex shader COMPILE_STATUS 0x8B81 Passed to getShaderParamter to get the status of the compilation. Returns false if the shader was not compiled. You can then query getShaderInfoLog to find the exact error DELETE_STATUS 0x8B80 Passed to getShaderParamter to determine if a shader was deleted via deleteShader. Returns true if it was, false
otherwise. LINK_STATUS 0x8B82 Passed to getProgramParameter after calling linkProgram to determine if a program was linked correctly. Returns false if there were errors. Use getProgramInfoLog to find the exact error. VALIDATE_STATUS 0x8B83 Passed to getProgramParameter after calling validateProgram to determine if it is valid. Returns false if errors were found. ATTAC...
Using WebGL extensions - Web APIs
Extension objects If an extension defines specific symbols or functions that are not available in the core specification of WebGL, they will be available on the extension object returned by the call to gl.getExtension(). ...
Signaling and video calling - Web APIs
) { 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. If that property is present, it specifies the username of the client to which the message is to be sent, and we call sendToOneUser() to send the message to them.
Otherwise, the message is broadcast to all users by iterating over the connection list, sending the message to each user. As the existing code allows the sending of arbitrary message types, no additional changes are required. Our clients can now send messages of unknown types to any specific user, letting them send signaling messages back and forth as desired. That's all we need to change on the server s...
WebRTC API - Web APIs
sed to send tone dialing sounds--or packets representing those tones--across the network to the remote peer. Interfaces RTCDTMFSender Manages the encoding and transmission of Dual-Tone Multi-Frequency (DTMF) signaling for an RTCPeerConnection. RTCDTMFToneChangeEvent Used by the tonechange event to indicate that a DTMF tone has either begun or ended. This event does not bubble (except where
otherwise stated) and is not cancelable (except where
otherwise stated). Events tonechange Either a new DTMF tone has begun to play over the connection, or the last tone in the RTCDTMFSender's toneBuffer has been sent and the buffer is now empty. The event's type is RTCDTMFToneChangeEvent. Guides Introduction to WebRTC protocols This article introduces the protocols on top of which the WebRTC A...
Using bounded reference spaces - Web APIs
nd safely. Basics The XRReferenceSpaceType of all bounded reference spaces is bounded-floor. This is the only type of bounded reference space currently available; in all others, if you need boundaries, you will have to manage them yourself. Because bounded-floor is a floor-bound reference space, the user starts out on the floor of the space, which is sensible given the real-world implications
otherwise. Therefore, the bounded reference space's origin always places the Y=0 plane at floor level. The boundary is then defined using an array of 2D coordinates, specifying only the X and Z components since Y is always 0. These points go around the room in a clockwise direction. Note that if the underlying platform defines a fixed room-scale origin and boundary, it may initialize any uninitialized val...
Fundamentals of WebXR - Web APIs
arent, and if not displaying anything is essentially identical to wearing regular eyeglasses. When objects are drawn, they are drawn onto the goggles' lenses, either partially or completely blocking the physical environment from being seen through the obscured portion of the lens. CAVEs A Cave Automated Virtual Environment (CAVE) is an immersive VR environment in which the scene is projected or
otherwise displayed on the walls (as well as possibly the ceiling and/or floor), thus completely surrounding the user with the simulation and allowing them to be immersed in the scene. The user wears 3D glasses that both add the 3D effect to the projected image, but provide a means for the system to render foreground objects into the world. The user's activity may be monitored using motion sensors that ar...
WebXR application life cycle - Web APIs
rovided about the objects located in the 3D world to render the frame using WebGL. Each time the callback is invoked, it should call requestAnimationFrame() again in order to let the browser know that the callback needs to be run again when it's time to render the next frame. When the time comes (such as when the user exits your app or navigates away from your site), end the XR session;
otherwise, continue the loop until the user chooses to exit XR mode. To end the XR session yourself, call XRSession.end(). Include a handler for the XRSession event end event to be informed when the session is ending, regardless of whether your code, the user, or the browser initiated the termination of the session. ...
WebXR permissions and security - Web APIs
e for a user-launched web application. The document is considered trustworthy, in that it is responsible and is both currently active and has focus. The user's intent to enter immersive VR mode is well understood; see User intent below for details. If all of that is true, the promise returned by requestSession() is resolved, and the new XRSession object is passed into the fulfillment handler.
Otherwise, an appropriate exception is thrown, such as SecurityError if the document doesn't have permission to enter immersive mode. Inline presentation When you request an XRSession with the mode set to inline, and any features are required or requested, the browser will only allow the session to be created if the call to requestSession() was made by code which is executing expressly due to user intent...
Using the Web Animations API - Web APIs
m the original CSS. However, unlike CSS, the Web Animations API doesn't need to explicitly be told the percentages along the animation for each key to appear at. It will automatically divide the animation into equal parts based on the number of keys you give it. This means that a Keyframe object with three keys will play the middle key 50% of the way through each loop of the animation unless told
otherwise. When we want to explicitly set a key's offset from the other keys, we can specify an offset directly in the object, separated from the declaration with a comma. In the above example, to make sure that Alice's color changes at 30% (not 50%) for the color change, we are giving it offset: 0.3. Currently, there should be at least two keyframes specified (representing the starting and ending states...
Basic concepts behind Web Audio API - Web APIs
.1 kHz) is a common sampling frequency. Why 44.1kHz? Firstly, because the hearing range of human ears is roughly 20 Hz to 20,000 Hz. Via the Nyquist-Shannon sampling theorem, the sampling frequency must be greater than twice the maximum frequency one wishes to reproduce. Therefore, the sampling rate has to be greater than 40 kHz. Secondly, signals must be low-pass filtered before sampling,
otherwise aliasing occurs. While an ideal low-pass filter would perfectly pass frequencies below 20 kHz (without attenuating them) and perfectly cut off frequencies above 20 kHz, in practice a transition band is necessary, where frequencies are partly attenuated. The wider this transition band is, the easier and more economical it is to make an anti-aliasing filter. The 44.1 kHz sampling frequency allows f...
Web Audio API best practices - Web APIs
check if context is in suspended state (autoplay policy) if (audioCtx.state === 'suspended') { audioCtx.resume(); } }, false); You might instead be working with an OfflineAudioContext, in which case you can resume the suspended audio context with the startRendering() method. User control If your website or application contains sound, you should allow the user control over it,
otherwise again, it will become annoying. This can be achieved by play/stop and volume/mute controls. The Using the Web Audio API tutorial goes over how to do this. If you have buttons that switch audio on and off, using the ARIA role="switch" attribute on them is a good option for signalling to assistive technology what the button's exact purpose is, and therefore making the app more accessible. There's ...
Web Audio API - Web APIs
, OscillatorNode, PeriodicWave, and GainNode.Migrating from webkitAudioContextIn 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. Tools for analyzing Web Audio usageWhile 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. This article discusses tools available to help you do that.Using IIR filtersThat's it for our IIRFilter demo. This should have shown you how to use the basics, and helped you to understand what it's useful for and how it works.Using the Web Audio APIGreat! We have a boombox that plays our 'tape', and we can adjust the volume and stereo panning, giving us a fairly basic working au...
Window: beforeunload event - Web APIs
aded. The document is still visible and the event is still cancelable at this point. Bubbles No Cancelable Yes Interface Event Event handler property onbeforeunload This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser navigates to the new page,
otherwise it cancels the navigation. According to the specification, to show the confirmation dialog an event handler should call preventDefault() on the event. However note that not all browsers support this method, and some instead require the event handler to implement one of two legacy methods: assigning a string to the event's returnValue property returning a string from the event handler. Som...
Window: error event - Web APIs
The error event is fired on a Window object when a resource failed to load or couldn't be used -- for example if a script has an execution error. Bubbles No Cancelable No Interface Event or UIEvent Event handler property onerror The event object is a UIEvent instance if it was generated from a user interface element, or an Event instance
otherwise. Examples Live example HTML <div class="controls"> <button id="script-error" type="button">Generate script error</button> <img class="bad-img" /> </div> <div class="event-log"> <label>Event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea> </div> CSS body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: cont...
Window.find() - Web APIs
Boolean. If true, specifies a case-sensitive search. aBackwards Boolean. If true, specifies a backward search. aWrapAround Boolean. If true, specifies a wrap around search. aWholeWord Unimplemented Boolean. If true, specifies a whole word search. This is not implemented; see bug 481513. aSearchInFrames Boolean. If true, specifies a search in frames. Returns true if the string is found;
otherwise, false. Example JavaScript findString = function findText(text) { alert("String \x22" + text + "\x22 found? " + window.find(text)); } HTML <p>Apples, Bananas, and Oranges.</p> <button type="button" onClick='findString("Apples")'>Search for Apples</button> <button type="button" onClick='findString("Banana")'>Search for Banana</button> <button type="button" onClick='findString("Orange")'>Sea...
Window.fullScreen - Web APIs
Bear in mind that if you try to set this property without chrome privileges, it will not throw an exception and instead just silently fail. This is to prevent scripts designed to set this property in Internet Explorer from breaking. Return value isInFullScreen A boolean. ...
Privileged features - Web APIs
is not minimized. alwaysLowered windows are often referred as pop-under windows. The alwaysLowered window can not be on top of the parent but the parent window can be minimized. In NS 6.x, the alwaysLowered window has no minimize system command icon and no restore/maximize system command. alwaysOnTop If on, the new window will always be displayed on top of all other windows (browser windows and
otherwise), regardless of whether it is active or not. This was added in Firefox 66 (see bug 1519893). z-lock Same as alwaysLowered. close When set to no or 0, this feature removes the system close command icon and system close menu item. It will only work for dialog windows (dialog feature set). close=no will override minimizable=yes. Mozilla and Firefox users can force new windows to always have a c...
window.postMessage() - Web APIs
messages from other sites, always verify the sender's identity using the origin and possibly source properties. Any window (including, for example, http://evil.example.com) can send a message to any other window, and you have no guarantees that an unknown sender will not send malicious messages. Having verified identity, however, you still should always verify the syntax of the received message.
Otherwise, a security hole in the site you trusted to send only trusted messages could then open a cross-site scripting hole in your site. Always specify an exact target origin, not *, when you use postMessage to send data to other windows. A malicious site can change the location of the window without your knowledge, and therefore it can intercept the data sent using postMessage. Secure shared memory me...
Window.requestAnimationFrame() - Web APIs
in a single frame, each receives the same timestamp even though time has passed during the computation of every previous callback's workload. This timestamp is a decimal number, in milliseconds, but with a minimal precision of 1ms (1000 us). Be sure to always use the first argument (or some other method for getting the current time) to calculate how much the animation will progress in a frame,
otherwise the animation will run faster on high refresh rate screens. Check the example below for a way to do this. Syntax window.requestAnimationFrame(callback); Parameters callback The function to call when it's time to update your animation for the next repaint. The callback function is passed one single argument, a DOMHighResTimeStamp similar to the one returned by performance.now(), indicatin...
window.requestIdleCallback() - Web APIs
ed in first-in-first-out order; however, callbacks which have a timeout specified may be called out-of-order if necessary in order to run them before the timeout elapses. You can call requestIdleCallback() within an idle callback function to schedule another callback to take place no sooner than the next pass through the event loop. A timeout option is strongly recommended for required work, as
otherwise it's possible multiple seconds will elapse before the callback is fired. Syntax var handle = window.requestIdleCallback(callback[, options]) Return value An ID which can be used to cancel the callback by passing it into the window.cancelIdleCallback() method. Parameters callback A reference to a function that should be called in the near future, when the event loop is idle. The callback ...
Window.window - Web APIs
al === window.global); // displays "true" you can access built-in properties of the window object without having to type window. prefix: setTimeout("alert('Hi!')", 50); // equivalent to using window.setTimeout. alert(window === window.window); // displays "true" The point of having the window property refer to the object itself, was likely to make it easy to refer to the global object.
Otherwise, you'd have to do a manual var window = this; assignment at the top of your script. Another reason, is that without this property you wouldn't be able to write, for example, "window.open('http://google.com/')". You'd have to use "open('http://google.com/')" instead. Yet another reason to use this property, is for libraries which wish to offer OOP-versions, and non-OOP versions (especially JavaS...
WindowOrWorkerGlobalScope.atob() - Web APIs
For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. For use with Unicode or UTF-8 strings, see the note on "Unicode strings" in the page for btoa(). ...
WindowOrWorkerGlobalScope.btoa() - Web APIs
For example, you can encode control characters such as ASCII values 0 through 31. Syntax var encodedData = scope.btoa(stringToEncode); Parameters stringToEncode The binary string to encode. ...
WritableStreamDefaultWriter - Web APIs
, with any queued writes discarded. WritableStreamDefaultWriter.close() Closes the associated writable stream. WritableStreamDefaultWriter.releaseLock() Releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on;
otherwise, the writer will appear closed. WritableStreamDefaultWriter.write() Writes a passed chunk of data to a WritableStream and its underlying sink, then returns a Promise that resolves to indicate the success or failure of the write operation. Examples The following example shows the creation of a WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a functio...
HTML in XMLHttpRequest - Web APIs
sing is not supported. View on JSFiddle Character encoding If the character encoding is declared in the HTTP Content-Type header, that character encoding is used. Failing that, if there is a byte order mark, the encoding indicated by the byte order mark is used. Failing that, if there is a <meta> element that declares the encoding within the first 1024 bytes of the file, that encoding is used.
Otherwise, the file is decoded as UTF-8. Handling HTML on older browsers XMLHttpRequest originally supported only XML parsing. HTML parsing support is a recent addition. 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) { ...
XPathException - Web APIs
In the DOM XPath API the XPathException interface represents exception conditions that can be encountered while performing XPath operations. Properties XPathException.code Read only Returns a short that contains one of the error code constants. Constants Constant Value Description INVALID_EXPRESSION_ERR 51 If the expression has a syntax error or
otherwise is not a legal expression according to the rules of the specific XPathEvaluator or contains specialized extension functions or variables not supported by this implementation. TYPE_ERR 52 If the expression cannot be converted to return the specified type. Specifications Specification Status Comment Document Object Model (DOM) Level 3 XPath SpecificationThe de...
XREye - Web APIs
The XREye enumerated type is used to identify which eye a particular XRView represents: left or right; or, if the view doesn't represent a single eye, the value may be none. Values left The XRView represents the point-of-view of the viewer's left eye. right The view represents the viewer's right eye. none The XRView describes a monoscopic view, or the view
otherwise doesn't represent a particular eye's point-of-view. Usage notes These values are used by the XRView property eye. Specifications Specification Status Comment WebXR Device APIThe definition of 'XREye' in that specification. Working Draft Initial definition. ...
XRPermissionDescriptor.mode - Web APIs
on on specifying features during a WebXR permission check. let xrPermissionDesc = { name: "xr", mode: "immersive-vr" }; if (navigator.permissions) { navigator.permissions.query(xrPermissionDesc).then(({state}) => { switch(state) { case "granted": setupXR(); break; case "prompt": promptAndSetupXR(); break; default: /* do nothing
otherwise */ break; } .catch(err) { console.log(err); } } else { setupXR(); } Specifications Specification Status Comment WebXR Device APIThe definition of 'XRPermissionDescriptor.mode' in that specification. Working Draft Initial definition. ...
XRPermissionDescriptor - Web APIs
y the granted case. let xrPermissionDesc = { name: "xr", mode: "immersive-vr", requiredFeatures: [ "local-floor" ] }; if (navigator.permissions) { navigator.permissions.query(xrPermissionDesc).then(({state}) => { switch(state) { case "granted": setupXR(); break; case "prompt": promptAndSetupXR(); break; default: /* do nothing
otherwise */ break; } .catch(err) { console.log(err); } } else { setupXR(); } Specifications Specification Status Comment WebXR Device APIThe definition of 'XRPermissionDescriptor' in that specification. Working Draft Initial definition. ...
XRPermissionStatus.granted - Web APIs
racking space whose native origin tracks the viewer's position and orientation. This is used for environments in which the user can physically move around, and is supported by all instances of XRSession, both immersive and inline, though it's most useful for inline sessions. It's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces.
Otherwise, typically, one of the other reference space types will be used more often. XRReferenceSpace Usage notes Examples Specifications Specification Status Comment WebXR Device APIThe definition of 'XRPermissionStatus.granted' in that specification. Working Draft Initial definition. ...
XRPose.transform - Web APIs
by passing the event frame's pose into a function called findTargetUsingRay(), then dispatches the event differently depending on the user's handedness; this is done by comparing the value of the XRInputSource property handedness to a value in the variable user.handedness. If the source is a controller in the user's primary hand, a function is called on the targeted object called primaryAction();
otherwise, it calls the targeted object's offHandAction() function. xrSession.addEventListener("select", event => { let source = event.inputSource; let frame = event.frame; let targetRayPose = frame.getPose(source.targetRaySpace, myRefSpace); let targetObject = findTargetUsingRay(targetRay.transform.matrix); if (source.targetRayMode == "tracked-pointer") { if (source.handedness == user.hand...
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
is adjusted to a position given by startPosition and whose orientation is looking directly along the Z azis. Then the first animation frame is requested using XRSession's requestAnimationFrame(). Implementing rotation based on non-XR inputs The input controls supported directly by WebXR are all dedicated VR or AR input devices. In order to use mouse, keyboard, or other input devices to move or
otherwise transform objects in the 3D space--or to allow the user to move through the space--you'll need to write some code to read the inputs and move perform the movements. This is another good use case for getOffsetReferenceSpace(). In this example, we'll show code that lets the user look around by right-clicking and moving the mouse to change the viewing angle. First, we add an event handler for mous...
XRReferenceSpace - Web APIs
racking space whose native origin tracks the viewer's position and orientation. This is used for environments in which the user can physically move around, and is supported by all instances of XRSession, both immersive and inline, though it's most useful for inline sessions. It's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces.
Otherwise, typically, one of the other reference space types will be used more often. XRReferenceSpace Usage notes Creating an XRReferenceSpace There are two situations in which you need to obtain an XRReferenceSpace. The first is when you set up your scene and need to obtain a reference space to represent the user's viewpoint on the world for the duration of the XRSession. To do that, call th...
XRReferenceSpaceType - Web APIs
racking space whose native origin tracks the viewer's position and orientation. This is used for environments in which the user can physically move around, and is supported by all instances of XRSession, both immersive and inline, though it's most useful for inline sessions. It's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces.
Otherwise, typically, one of the other reference space types will be used more often. XRReferenceSpace Specifications Specification Status Comment WebXR Device APIThe definition of 'XRReferenceSpaceType' in that specification. Working Draft Initial definition. ...
XRRenderStateInit - Web APIs
calFieldOfView Optional A floating-point value indicating the default field of view, in radians, to be used when computing the projection matrix for an inline XRSession. The projection matrix calculation also takes into account the output canvas's aspect ratio. This property must not be specified for immersive sessions, so the value is null by default for immersive sessions. The default value is
otherwise ? * 0.5 (half of the value of pi). Usage notes Any properties not specified in the XRRenderStateInit compliant object passed into updateRenderState() are left at their current values. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRRenderStateInit' in that specification. Working Draft Initial definition. ...
XRSession.requestReferenceSpace() - Web APIs
racking space whose native origin tracks the viewer's position and orientation. This is used for environments in which the user can physically move around, and is supported by all instances of XRSession, both immersive and inline, though it's most useful for inline sessions. It's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces.
Otherwise, typically, one of the other reference space types will be used more often. XRReferenceSpace Return value A Promise that resolves with an XRReferenceSpace object. Exceptions Rather than throwing true exceptions, requestReferenceSpace() rejects the returned promise with a DOMException whose name is found in the list below: NotSupportedError The requested reference space is not su...
XRSession.updateRenderState() - Web APIs
calFieldOfView Optional A floating-point value indicating the default field of view, in radians, to be used when computing the projection matrix for an inline XRSession. The projection matrix calculation also takes into account the output canvas's aspect ratio. This property must not be specified for immersive sessions, so the value is null by default for immersive sessions. The default value is
otherwise ? * 0.5 (half of the value of pi). Return value None. Exceptions This method may throw any of the following exceptions. These are true exceptions, since this method does not return a promise. InvalidStateError This may occur for one of the following reasons: The XRSession has already ended, so you cannot change its render state. The baseLayer specified in newState was created by...
XRSystem: devicechange event - Web APIs
OK) => { if (immersiveOK) { enableXRButton.disabled = false; } else { enableXRButton.disabled = true; } }); }); } When devicechange is received, the handler set up in this code calls the XR method isSessionSupported() to find out if there's a device available that can handle immersive VR presentations. If there is, the button to enter XR mode is enabled;
otherwise it's disabled. You can also use the ondevicechange event handler property to set a single handler for devicechange events: if (navigator.xr) { navigator.xr.ondevicechange = event => { /* ... etc ... */ }; } Specifications Specification Status Comment WebXR Device APIThe definition of 'devicechange event' in that specification. Working Draft Initial de...
XRView - Web APIs
verseOrientation, inverseOrientation, -mousePitch); quat.rotateY(inverseOrientation, inverseOrientation, -mouseYaw); // Compute the true "up" vector for our object. vec3.cross(vecX, vecY, cubeOrientation); vec3.cross(vecY, cubeOrientation, vecX); // Now compute the transform that teleports the object to the // specified point and save a copy of it to display to the user // later;
otherwise we probably wouldn't need to save mouseMatrix // at all. let newTransform = new XRRigidTransform({x: transverseDistance, y: verticalDistance, z: axialDistance}, {x: inverseOrientation[0], y: inverseOrientation[1], z: inverseOrientation[2], w: inverseOrienta...
XRWebGLLayer.antialias - Web APIs
The read-only XRWebGLLayer property antialias is a Boolean value which is true if the rendering layer's frame buffer supports antialiasing.
Otherwise, this property's value is false. The specific antialiasing technique used is left to the user agent's discretion and cannot be specified by the web site or web app. Syntax let antialiasingSupported = xrWebGLLayer.antialias; Value A Boolean value which is true if the WebGL rendering layer's frame buffer is configured to support antialiasing.
Otherwise, this property is false. When the WebXR compositor is enabled, this value corresponds to the value of the antialias property on the object returned by the WebGL context's getContentAttributes() method. Usage notes Since this is a read-only property, you can set the antialiasing mode only when in...
XRWebGLLayer.framebuffer - Web APIs
The opaque framebuffer is functionally nearly the same as a standard WebGL framebuffer, except for the differences covered in the section How opaque framebuffers are special below. Syntax let framebuffer = xrWebGLLayer.framebuffer; Value A WebGLFramebuffer object representing the framebuffer into which the 3D scene is being rendered, or null if the XR compositor is disabled for the session. ...
XRWebGLLayer.ignoreDepthValues - Web APIs
bject specified as the constructor's layerInit parameter. As a parameter you're likely to set yourself, it is unlikely you'll need to read it later, but it's available if the need arises. Syntax let ignoringDepthBuffer = xrWebGLLayer.ignoreDepthValues; Value A Boolean value which is true if the WebGL context's depth buffer is being used while computing the locations of points in the 3D world.
Otherwise, if this is true, the depth buffer's values are being used to assist in placing objects in the scene. Since the XR compositor uses the depth buffer by default, this value is false unless explicitly set
otherwise when creating the XRWebGLLayer using its constructor, XRWebGLLayer(). Usage notes When the ignoreDepthValues property is false, the XR compositor uses the values found in the depth buff...
XSLTProcessor - Web APIs
load the XSLT stylesheet, to manipulate <xsl:param> parameter values, and to apply the transformation to documents. Syntax The constructor has no parameters. new XSLTProcessor() Methods [Throws] void XSLTProcessor.importStylesheet(Node styleSheet) Imports the XSLT stylesheet. If the given node is a document node, you can pass in a full XSL Transform or a literal result element transform;
otherwise, it must be an <xsl:stylesheet> or <xsl:transform> element. [Throws] DocumentFragment XSLTProcessor.transformToFragment(Node source, Document owner) Transforms the node source by applying the stylesheet imported using the XSLTProcessor.importStylesheet() function. The owner document of the resulting document fragment is the owner node. [Throws] Document XSLTProcessor.transformToDocument(Node s...
msPutPropertyEnabled - Web APIs
roperty in the style object is enabled or disabled. This proprietary method is specific to Internet Explorer and Microsoft Edge. Syntax var retval = style.msPutPropertyEnabled(propertyName, true); Parameters name[in]: Name of the property. (String) boolean[in]: True = Enable the property. False = Disable the property. Return value Type = HRESULT: If this method succeeds, it returns S_OK.
Otherwise, it returns an HRESULT error code. See also CSS Style Declaration Microsoft API extensions ...
msWriteProfilerMark - Web APIs
ior may change in the future. The msWriteProfilerMark method writes a profiling event. This proprietary method is specific to Internet Explorer and Microsoft Edge. Syntax window.msWriteProfilerMark("start-render"); Parameters bstrProfilerMarkName[in] An event name. Type = String. This parameter may be null. Return value Type: HRESULT. If this method succeeds, it returns S_OK.
Otherwise, it returns an HRESULT error code. Notes msWriteProfilerMark enables you to inject DOM based performance markers in addition to existing Javascript API to learn exactly when parts of the page are being rendered, building a waterfall view for every one of our impressions showing latency per object, which can be useful for more accurately debugging real users perf issues. Internet Explorer 10. T...
Using the aria-valuenow attribute - Accessibility
aria-valuenow is a required attribute of role slider, scrollbar and spinbutton. Value String representation of a number Possible effects on user agents and assistive technology For elements with role progressbar and scrollbar, assistive technologies SHOULD render the actual value as a percentage, calculated as a position on the range from aria-valuemin to aria-valuemax if both are defined,
otherwise the actual value with a percent indicator. For elements with role slider and spinbutton, assistive technologies SHOULD render the actual value to users. Note: Opinions may differ on how assistive technology should handle this technique. The information provided above is one of those opinions and therefore not normative. Examples Example 1: The snippet below shows a simple slider with a curr...
ARIA: row role - Accessibility
tus. This is not the case for an ordinary table or grid, in which the aria-expanded attribute is not present. To create an interactive widget that has a tabular structure, use the grid pattern instead. If the interaction provides for the selection state of individual cells, if left to right and top to botton navigation is provided, or if the user interface allows the rearranging of cell order or
otherwise changing individual cell order such as through drag and drop, use grid or treegrid instead. Note: Using the native HTML table element (<table>) along with the table row element (<tr>) whenever possible is strongly encouraged. Associated WAI-ARIA roles, states, and properties Context roles role="rowgroup" An optional contextual row parent, it establishes a relationship between descendant ...
ARIA: switch role - Accessibility
ibility API if one is available and it supports the switch role. All elements that are descendants of an element with the switch role applied to it are automatically assigned role presentation. This prevents elements that are used to construct the switch from being interacted with individually by assistive technologies. Text in these elements remains visible to the user agent and may be read or
otherwise delivered to the user, unless it's expressly hidden using display: none or aria-hidden="true". The assistive technology, if it supports the switch role, responds by doing the following: Screen readers should announce the element as a switch, optionally providing instructions as to how to activate the switch. There are varying opinions on how assistive technologies should handle this role;...
ARIA: tab role - Accessibility
should contain the aria-controls property identifying an element with the tabpanel role. When an element with the tabpanel role has focus, or a child of it has focus, that indicates that the connected element with the tab role is the active tab in a tablist. When working with elements with the tab role, when they are selected or active, they should have their aria-selected attribute set to true,
otherwise it should be set to false. When a tab is selected or active, its controlled tabpanel should have its aria-expanded and hidden attributes set to true,
otherwise they should be set to false. Associated Roles and Attributes aria-selected boolean aria-controls id of element with tabpanel role id content Keyboard interaction Key Action Tab When focus is outside ...
ARIA: table role - Accessibility
g with all the related semantic elements and attributes that are all supported by all assistive technologies. To create an interactive widget that has a tabular structure, use the grid pattern instead. If the interaction provides for the selection state of individual cells, if left to right and top to bottom navigation is provided, or if the user interface allows the rearranging of cell order or
otherwise changing individual cell order such as through drag and drop, use grid or treegrid instead. Note: Using a native HTML table element whenever possible is strongly encouraged. Associated WAI-ARIA roles, states, and properties role="rowgroup" An optional child of the table, the row group encapsulates a group of rows, similar to thead, tbody, and tfoot. role="row" A row within the table, an...
ARIA: dialog role - Accessibility
een, keyboard focus (whose control depends upon the dialogs purpose) should be moved to the default focusable control inside the dialog. For dialogs that only provide a basic message, it could be an "OK" button. For dialogs containing a form it could be the first field in the form. After the dialog is dismissed, keyboard focus should be moved back to where it was before it moved into the dialog.
Otherwise the focus can be dropped to the beginning of the page. For most dialogs, the expected behavior is that the dialog's tab order wraps, which means that when the user tabs through the focusable elements in the dialog, the first focusable element will be focused after the last one has been reached. In other words, the tab order should be contained within and by the dialog. If the dialog can be move...
ARIA - Accessibility
Accessible Rich Internet Applications (ARIA) is a set of attributes that define ways to make web content and web applications (especially those developed with JavaScript) more accessible to people with disabilities. It supplements HTML so that interactions and widgets commonly used in applications can be passed to assistive technologies when there is not
otherwise a mechanism. For example, ARIA enables accessible navigation landmarks in HTML4, JavaScript widgets, form hints and error messages, live content updates, and more. Many of these widgets were later incorporated into HTML5, and developers should prefer using the correct semantic HTML element over using ARIA, if such an element exists. For instance, native elements have built-in keyboard accessibility, roles and states. However,...
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
cessible methods which can be overridden are GetAccFirstChild/GetAccLastChild/GetAccChildCount, which allows for objects to define their own decendant subtrees. The default behavior for nsIAccessible::getAccFirstChild is to instantiate a nsDOMTreeWalker, and ask it for the first child. However, nsImageAccessible overrides getAccFirstChild, returning the first area of an image map if there is one,
otherwise nsnull. This is necessary because the image map areas can be in a completely different area of the DOM from the image they apply to. Generating MSAA Events First, keep in mind that most MSAA events aren't utilized by accessibility aids. Therefore we implement only the handful that matter. See the Events cheat sheet above for the list of events we implement. By far the most important one is EVEN...
Understandable - Accessibility
ation. When an error is detected, an intuitive error message should be shown next to the form input that is at fault to help the user correct their inputs. For screenreader users, you can use aria live regions to alert the user to a change on the page. Note: Server-side validation should *always* be used alongside client-side validation. Client-side validation is too easy to turn off or
otherwise get around, so it can't be relied on alone. See Form data validation for comprehensive validation information, and WAI-ARIA: Dynamic content updates for information on live regions. 3.3.2 Labels or Instructions (A) Clear instructions should be provided when data input is required. When a simple instruction or prompt is required, you can use <label> elements for single...
-webkit-line-clamp - CSS: Cascading Style Sheets
The -webkit-line-clamp CSS property allows limiting of the contents of a block container to the specified number of lines. It only works in combination with the display property set to -webkit-box or -webkit-inline-box and the -webkit-box-orient property set to vertical. In most cases you will also want to set overflow to hidden,
otherwise the contents won't be clipped but an ellipsis will still be shown after the specified number of lines. When applied to anchor elements, the truncating can happen in the middle of the text, not necessarily at the end. Note: This property was originally implemented in WebKit and has some issues. It got standardized for legacy support. The CSS Overflow Module Level 3 specification also defines a line-clamp property, which is meant to replace this property and ...
-webkit-mask-repeat-y - CSS: Cascading Style Sheets
e next image is added, all of the current ones compress to allow room. Example: An image with an original height of 260px, repeated three times, might stretch until each repetition is 300px high, and then another image will be added. They will then compress to a height of 225px. ...
::-webkit-scrollbar - CSS: Cascading Style Sheets
the draggable resizing handle that appears at the bottom corner of some elements. Syntax Syntax not found in DB! Examples .visible-scrollbar, .invisible-scrollbar, .mostly-customized-scrollbar { display: block; width: 10em; overflow: auto; height: 2em; } .invisible-scrollbar::-webkit-scrollbar { display: none; } /* Demonstrate a "mostly customized" scrollbar * (won't be visible
otherwise if width/height is specified) */ .mostly-customized-scrollbar::-webkit-scrollbar { width: 5px; height: 8px; background-color: #aaa; /* or add it to the track */ } /* Add a thumb */ .mostly-customized-scrollbar::-webkit-scrollbar-thumb { background: #000; } <div class="visible-scrollbar"> Etiam sagittis sem sed lacus laoreet, eu fermentum eros auctor. Proin at nulla elementum, con...
:visited - CSS: Cascading Style Sheets
he style set in :visited will be ignored entirely. Although these styles can be change the appearance of colors to the end user, the window.getComputedStyle method will lie and always return the value of the non-:visited color. Note: For more information on these limitations and the reasons behind them, see Privacy and the :visited selector. Syntax :visited Examples Properties that would
otherwise have no color or be transparent cannot be modified with :visited. Of the properties that can be set with this pseudo-class, your browser probably has a default value for color and column-rule-color only. Thus, if you want to modify the other properties, you'll need to give them a base value outside the :visited selector. HTML <a href="#test-visited-link">Have you visited this link yet?</a><br> ...
@font-face - CSS: Cascading Style Sheets
, url(basic-sans-serif.ttf) format("truetype"); The available types are: "woff", "woff2", "truetype", "opentype", "embedded-opentype", and "svg". unicode-range The range of Unicode code points to be used from the font. Description If the local() function is provided, specifying a font name to look for on the user's computer, and the user agent finds a match, that local font is used.
Otherwise, the font resource specified using the url() function is downloaded and used. By allowing authors to provide their own fonts, @font-face makes it possible to design content without being limited to the so-called "web-safe" fonts (that is, the fonts which are so common that they're considered to be universally available). The ability to specify the name of a locally-installed font to look for and...
bleed - CSS: Cascading Style Sheets
The bleed CSS at-rule descriptor, used with the @page at-rule, specifies the extent of the page bleed area outside the page box. This property only has effect if crop marks are enabled using the marks property. Syntax /* Keyword values */ bleed: auto; /* <length> values */ bleed: 8pt; bleed: 1cm; Values auto Computes to 6pt if the value of marks is crop.
Otherwise it computes to zero. <length> Specifies by how far outward, in each direction, the bleed area extends past the page box. Values may be negative, but there may be implementation-specific limits. Formal definition Related at-rule@pageInitial valueautoComputed valueas specified Formal syntax auto | <length> Examples Setting a page bleed of 1cm @page { bleed: 1cm; } Specifications Specification S...
max-height - CSS: Cascading Style Sheets
ative length. <percentage> A percentage value relative to the height of the initial viewport at zoom factor 1.0 for vertical lengths. Must be non-negative. Formal definition Related at-rule@viewportInitial valueautoPercentagesrefer to the height of the initial viewportComputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value;
otherwise, auto Formal syntax <viewport-length>where <viewport-length> = auto | <length-percentage>where <length-percentage> = <length> | <percentage> Examples Setting viewport max height in pixels @viewport { max-height: 600px; } Specifications Specification Status Comment CSS Device AdaptationThe definition of '"max-height" descriptor' in that specification. Workin...
max-width - CSS: Cascading Style Sheets
ative length. <percentage> A percentage value relative to the width of the initial viewport at zoom factor 1.0 for horizontal lengths. Must be non-negative. Formal definition Related at-rule@viewportInitial valueautoPercentagesrefer to the width of the initial viewportComputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value;
otherwise, auto Formal syntax <viewport-length>where <viewport-length> = auto | <length-percentage>where <length-percentage> = <length> | <percentage> Examples Setting viewport max width in pixels @viewport { max-width: 600px; } Specifications Specification Status Comment CSS Device AdaptationThe definition of '"max-width" descriptor' in that specification. Working...
min-height - CSS: Cascading Style Sheets
ative length. <percentage> A percentage value relative to the height of the initial viewport at zoom factor 1.0 for vertical lengths. Must be non-negative. Formal definition Related at-rule@viewportInitial valueautoPercentagesrefer to the height of the initial viewportComputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value;
otherwise, auto Formal syntax <viewport-length>where <viewport-length> = auto | <length-percentage>where <length-percentage> = <length> | <percentage> Examples Setting viewport min height in pixels @viewport { min-height: 200px; } Specifications Specification Status Comment CSS Device AdaptationThe definition of '"min-height" descriptor' in that specification. Workin...
min-width - CSS: Cascading Style Sheets
tage value relative to the width or height of the initial viewport at zoom factor 1.0, for horizontal and vertical lengths respectively. Must be non-negative. Formal definition Related at-rule@viewportInitial valueautoPercentagesrefer to the width of the initial viewportComputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value;
otherwise, auto Formal syntax <viewport-length>where <viewport-length> = auto | <length-percentage>where <length-percentage> = <length> | <percentage> Examples Setting viewport min width in pixels @viewport { min-width: 200px; } Specifications Specification Status Comment CSS Device AdaptationThe definition of '"min-width" descriptor' in that specification. Working D...
Detecting CSS animation support - CSS: Cascading Style Sheets
ets && 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.
Otherwise, we can use JavaScript to create the desired CSS animation effects. Setting the animation property is easy; simply update its value in the style collection. However, adding keyframes is trickier, since they're not defined using traditional CSS syntax (which makes them more flexible, but harder to define from script). To define our keyframes using JavaScript, we need to write them out as a CSS s...
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
, and while working in a language written top to bottom. This means that the main axis runs along the row horizontally, and our cross axis alignment moves the items up and down. If we change our flex-direction to column, align-items and align-self will align the items to the left and right. You can try this out in the example below, which has a flex container with flex-direction: column yet
otherwise is exactly the same as the previous example. Aligning content on the cross axis -- the align-content property So far we have been aligning the items, or an individual item inside the area defined by the flex-container. If you have a wrapped multiple-line flex container then you might also want to use the align-content property to control the distribution of space between the rows. In the spe...
Ordering Flex Items - CSS: Cascading Style Sheets
the visual presentation while leaving the source order intact for non-CSS UAs and for linear models such as speech and sequential navigation." - Ordering and Orientation If your items were links or some other element that the user could tab to, then the tabbing order would be the order that these items appear in the document source -- not your visual order. If you are using a reverse value, or
otherwise reordering your items, you should consider whether you actually need to change the logical order in the source. The specification continues with a warning not to use reordering to fix issues in your source: "Authors must not use order or the *-reverse values of flex-flow/flex-direction as a substitute for correct source ordering, as that can ruin the accessibility of the document." Note: For...
Variable fonts guide - CSS: Cascading Style Sheets
ly implementations of variable font support, and is necessary to utilize new or custom axes beyond the five registered ones. However, the W3C's intent was for this syntax not to be used when other attributes are available. Therefore wherever possible, the appropriate property should be used, with the lower-level syntax of font-variation-settings only being used to set values or axes not available
otherwise. Notes When using font-variation-settings it is important to note that axis names are case-sensitive. The registered axis names must be in lower case, and custom axes must be in upper case. For example: font-variation-settings: 'wght' 375, 'GRAD' 88; wght (weight) is a registered axis, and GRAD (grade) is a custom one. If you have set values using font-variation-settings and wa...
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
d item placement algorithm, however for most of us we just need to remember a few simple rules for our items. Order modified document order Grid places items that have not been given a grid position in what is described in the specification as "order modified document order". This means that if you have used the order property at all, the items will be placed by that order, not their DOM order.
Otherwise they will stay by default in the order that they are entered in the document source. Items with placement properties The first thing grid will do is place any items that have a position. In the example below I have 12 grid items. Item 2 and item 5 have been placed using line based placement on the grid. You can see how those items are placed and the other items then auto-place in the spaces. Th...
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
o for margins and padding. Once you realize that grid-area sees the world as "block and inline", you can remember that we are setting the two starts, then the two ends. It becomes much more logical once you know! Mixed writing modes and grid layout In addition to displaying documents, using the correct writing mode for the language, writing modes can be used creatively within documents that are
otherwise ltr. In this next example I have a grid layout with a set of links down one side. I've used writing modes to turn these on their side in the column track: .wrapper { display: grid; grid-gap: 20px; grid-template-columns: 1fr auto; font: 1em Helvetica, Arial, sans-serif; } .wrapper nav { writing-mode: vertical-lr; } .wrapper ul { list-style: none; margin: 0; paddin...
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
t. CSS Grid Layout is very different, in terms of the amount of time it has been in development, and the work of the various browser vendors to ensure that what ships works in the same way for everyone. Starting to use Grid in production It is worth noting that you do not have to use grid in an all or nothing way. You could start by simply enhancing elements in your design with grid, that could
otherwise display using an older method. Overwriting of legacy methods with grid layout works surprisingly well, due to the way grid interacts with these other methods. Floats We have typically used floats to create multiple column layouts. If you have floated an item, which is also a grid item in a supporting browser, the float will no longer apply to the item. The fact is that a grid item takes precede...
Grid template areas - CSS: Cascading Style Sheets
This means that you must have the same number of cells for each row, if empty with a full stop character demonstrating that the cell is to be left empty. You will also create an invalid grid if your areas are not rectangular. Redefining the grid using media queries As our layout is now contained in one part of the CSS, this makes it very easy to make...
Using CSS gradients - CSS: Cascading Style Sheets
percentage or absolute length. <div class="radial-gradient"></div> div { width: 120px; height: 120px; } .radial-gradient { background: radial-gradient(red 10px, yellow 30%, #1e90ff 50%); } Positioning the center of the gradient You can position the center of the gradient with keyterms, percentage, or absolute lengths, length and percentage values repeating if only one is present,
otherwise in the order of position from the left and position from the top. <div class="radial-gradient"></div> div { width: 120px; height: 240px; } .radial-gradient { background: radial-gradient(at 0% 30%, red 10px, yellow 30%, #1e90ff 50%); } Sizing radial gradients Unlike linear gradients, you can specify the size of radial gradients. Possible values include closest-corner, closest-side...
Consistent list indentation - CSS: Cascading Style Sheets
er, but sit stubbornly in place in Gecko-based browsers.This article will help you understand the problems that can occur and how to avoid them. In order to understand why this is the case, and more importantly how to avoid the problem altogether, it's necessary to examine the details of list construction. Making a List First, we consider a single, pure list item. This list item has no marker (
otherwise known as a "bullet") and is not yet part of a list itself. It hangs alone in the void, simple and unadorned, as shown in Figure 1. That dotted red border represents outer edges of the content-area of the list item. Remember that, at this point, the list item has no padding or borders. If we add two more list items, we get a result like that shown in Figure 2. Now we wrap these in a parent e...
Using CSS counters - CSS: Cascading Style Sheets
e used. Using counters Manipulating a counter's value To use a CSS counter, it must first be initialized to a value with the counter-reset property (0 by default). The same property can also be used to change its value to any specific number. Once initialized, a counter's value can be increased or decreased with counter-increment. The counter's name must not be "none", "inherit", or "initial";
otherwise the declaration is ignored. Displaying a counter The value of a counter can be displayed using either the counter() or counters() function in a content property. The counter() function has two forms: 'counter(name)' or 'counter(name, style)'. The generated text is the value of the innermost counter of the given name in scope at the given pseudo-element.The counter is rendered in the specified ...
CSS Overflow - CSS: Cascading Style Sheets
le contains the features of CSS relating to scrollable overflow handling in visual media. In CSS overflow happens when the content of a box extends past one or more of the box's edges. Ink overflow and scrollable overflow There are two types of overflow that you might encounter in CSS. The first is described as ink overflow. This is the overflow of painting effects which do not affect layout or
otherwise extend the scrollable overflow region, such as box shadows, border images, text decoration, overhanging glyphs, outlines, etc. The overflow that we sometimes need to manage in CSS is described as scrollable overflow. This is the content appearing outside of the box for which scrolling mechanisms need to be provided. The overflow properties are how we can control what happens when content overflo...
CSS values and units - CSS: Cascading Style Sheets
1cm = 96px/2.54 mm Millimeters 1mm = 1/10th of 1cm Q Quarter-millimeters 1Q = 1/40th of 1cm in Inches 1in = 2.54cm = 96px pc Picas 1pc = 1/16th of 1in pt Points 1pt = 1/72th of 1in px Pixels 1px = 1/96th of 1in When including a length value, if the length is 0, the unit identifier is not required.
Otherwise, the unit identifier is required, is case insensitive, and must come immediately after the numeric part of the value, with no space in-between. Angle units Angle values are represented by the type <angle> and accept the following values: Unit Name Description deg Degrees There are 360 degrees in a full circle. grad Gradians There are 400 gradian...
Testing media queries programmatically - CSS: Cascading Style Sheets
ndleOrientationChange(mediaQueryList); // Add the callback function as a listener to the query list. mediaQueryList.addListener(handleOrientationChange); This code creates the orientation-testing media query list, then adds an event listener to it. After adding the listener, we also call the listener directly. This makes our listener perform adjustments based on the current device orientation;
otherwise, our code might assume the device is in portrait mode at startup, even if it's actually in landscape mode. The handleOrientationChange() function would look at the result of the query and handle whatever we need to do on an orientation change: function handleOrientationChange(evt) { if (evt.matches) { /* The viewport is currently in portrait orientation */ } else { /* The viewport i...
Using media queries - CSS: Cascading Style Sheets
dia queries into a single rule by separating them with commas. and The and operator is used for combining multiple media features together into a single media query, requiring each chained feature to return true in order for the query to be true. It is also used for joining media features with media types. not The not operator is used to negate a media query, returning true if the query would
otherwise return false. If present in a comma-separated list of queries, it will only negate the specific query to which it is applied. If you use the not operator, you must also specify a media type. Note: In Level 3, the not keyword can't be used to negate an individual media feature expression, only an entire media query. only The only operator is used to apply a style only if an entire query match...
Shorthand properties - CSS: Cascading Style Sheets
these values. inherit Sets the property value applied to a selected element to be the same as that of its parent element. Effectively, this "turns on inheritance". initial Sets the property value applied to a selected element to the initial value of that property. unset Resets the property to its natural value, which means that if the property is naturally inherited it acts like inherit,
otherwise it acts like initial. Note: There is also a newer value, revert, which has limited browser support. Note: See Origin of CSS declarations in Introducing the CSS Cascade for more information on each of these and how they work. We can look at a list of links and explore how the universal values work. The live example below allows you to play with the CSS and see what happens when you make ch...
Value definition syntax - CSS: Cascading Style Sheets
ar at least one time. bold smaller smaller smaller, as the different occurrence of smaller must be separated by commas. smaller, as bold is juxtaposed and must appear before any smaller keyword. Exclamation point (!) The exclamation point multiplier after a group indicates that the group is required, and must produce at least one value; even if the grammar of the items within the group would
otherwise allow the entire contents to be omitted, at least one component value must not be omitted. [ bold? smaller? ]! This example matches the following values: bold smaller bold smaller But not: neither bold nor smaller, as one of them must appear. smaller bold, as bold is juxtaposed and must appear before the smaller keyword. bold smaller bold, as bold and smaller may only appear once. ...
Visual formatting model - CSS: Cascading Style Sheets
xes cannot be styled independently in the way the <em> can; they just inherit the styles of their container. Other formatting contexts also create anonymous boxes. Grid Layout behaves in the same way as the flexbox example above, turning strings of text into a grid item with an anonymous box. Multiple-column layout creates anonymous column boxes around the columns; these also cannot be styled or
otherwise targetted. Table layout will add anonymous boxes to create a proper table structure -- for example adding an anonymous table row -- if there was no box with display: table-row. Line boxes Line boxes are the boxes that wrap each line of text. You can see the difference between line boxes and their containing block if you float an item and then follow it by a block that has a background color. I...
align-self - CSS: Cascading Style Sheets
. Formal definition Initial valueautoApplies toflex items, grid items, and absolutely-positioned boxesInheritednoComputed valueauto computes to itself on absolutely-positioned elements, and to the computed value of align-items on the parent (minus any legacy keywords) on all other boxes, or start if the box has no parent. Its behavior depends on the layout model, as described for justify-self. ...
aspect-ratio - CSS: Cascading Style Sheets
r layout functions. This property is not yet implemented in browsers, however some browsers are implementing this internally in order to provide the aspect ratio mapping described below. Syntax aspect-ratio: 1 / 1; /* Global values */ aspect-ratio: inherit; aspect-ratio: initial; aspect-ratio: unset; Values <auto> Replaced elements with an intrinsic aspect ratio use that aspect ratio,
otherwise the box has no preferred aspect ratio. Size calculations involving intrinsic aspect ratio always work with the content box dimensions. <ratio> The box's preferred aspect ratio is the specified ratio of width / height. Size calculations involving preferred aspect ratio work with the dimensions of the box specified by box-sizing. Formal definition Initial valueautoApplies toall elements except...
background-clip - CSS: Cascading Style Sheets
le is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. If the element has no background-image or background-color, this property will only have a visual effect when the border has transparent regions or partially opaque regions (due to border-style or border-image);
otherwise, the border masks the difference. Note: Because the root element has a different background painting area, the background-clip property has no effect when specified on it. See "The backgrounds of special elements." Note: For documents whose root element is an HTML element: if the computed value of background-image on the root element is none and its background-color is transparent, user agen...
background - CSS: Cascading Style Sheets
d to the height for vertical offsetsbackground-size: relative to the background positioning areaComputed valueas each of the properties of the shorthand:background-image: as specified, but with <url> values made absolutebackground-position: a list, each item consisting of two keywords representing the origin and two offsets from that origin, each given as an absolute length (if given a <length>),
otherwise as a percentagebackground-size: as specified, but with relative lengths converted into absolute lengthsbackground-repeat: a list, each item consisting of two keywords, one per dimensionbackground-origin: as specifiedbackground-clip: as specifiedbackground-attachment: as specifiedbackground-color: computed colorAnimation typeas each of the properties of the shorthand:background-color: a colorbackg...
block-size - CSS: Cascading Style Sheets
A related property is inline-size, which defines the other dimension of the element. Initial valueautoApplies tosame as width and heightInheritednoPercentagesblock-size of containing blockComputed valuesame as width and heightAnimation typea length, percentage or calc(); Syntax Values The block-size property takes the same values as the width and heig...
border-image-slice - CSS: Cascading Style Sheets
regions in total: four corners, four edges, and a middle region. Four slice lines, set a given distance from their respective sides, control the size of the regions. The above diagram illustrates the location of each region. Zones 1-4 are corner regions. Each one is used a single time to form the corners of the final border image. Zones 5-8 are edge regions. These are repeated, scaled, or
otherwise modified in the final border image to match the dimensions of the element. Zone 9 is the middle region. It is discarded by default, but is used like a background image if the keyword fill is set. The border-image-repeat, border-image-width, and border-image-outset properties determine how these regions are used to form the final border image. Syntax /* All sides */ border-image-slice: 30%; ...
bottom - CSS: Cascading Style Sheets
t (which might not be its containing block). This computed value is then handled as if it were a <length>, <percentage>, or the auto keyword. Formal definition Initial valueautoApplies topositioned elementsInheritednoPercentagesrefer to the height of the containing blockComputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value;
otherwise, autoAnimation typea length, percentage or calc(); Formal syntax <length> | <percentage> | auto Examples Absolute and fixed positioning This example demonstrates the difference in behavior of the bottom property, when position is absolute versus fixed. HTML <p>This<br>is<br>some<br>tall,<br>tall,<br>tall,<br>tall,<br>tall<br>content.</p> <div class="fixed"><p>Fixed</p></div> <div class="ab...
box-shadow - CSS: Cascading Style Sheets
ist is uninterpolable. If the lists of shadows have different lengths, then the shorter list is padded at the end with shadows whose color is transparent, all lengths are 0, and whose inset (or not) matches the longer list. Formal definition Initial valuenoneApplies toall elements. ...
box-sizing - CSS: Cascading Style Sheets
the content, and height = border + padding + height of the content. Formal definition Initial valuecontent-boxApplies toall elements that accept width or heightInheritednoComputed valueas specifiedAnimation typediscrete Formal syntax content-box | border-box Examples Box sizes with content-box and border-box This example shows how different box-sizing values alter the rendered size of two
otherwise identical elements. HTML <div class="content-box">Content box</div> <br> <div class="border-box">Border box</div> CSS div { width: 160px; height: 80px; padding: 20px; border: 8px solid red; background: yellow; } .content-box { box-sizing: content-box; /* Total width: 160px + (2 * 20px) + (2 * 8px) = 216px Total height: 80px + (2 * 20px) + (2 * 8px) = 136px Content box...
content - CSS: Cascading Style Sheets
ain document. Accessibility support for CSS generated content - Tink Explanation of WCAG, Guideline 1.3 - MDN Understanding Success Criterion 1.3.1 | W3C Understanding WCAG 2.0 Formal definition Initial valuenormalApplies to::before and ::after pseudo-elementsInheritednoComputed valueOn elements, always computes to normal. On ::before and ::after, if normal is specified, computes to none. ...
<display-inside> - CSS: Cascading Style Sheets
oses as a single keyword, or as defined in the Level 3 specification alongside a value from the <display-outside> keywords. Syntax Valid <display-inside> values: flow The element lays out its contents using flow layout (block-and-inline layout). If its outer display type is inline or run-in, and it is participating in a block or inline formatting context, then it generates an inline box.
Otherwise it generates a block container box. Depending on the value of other properties (such as position, float, or overflow) and whether it is itself participating in a block or inline formatting context, it either establishes a new block formatting context (BFC) for its contents or integrates its contents into its parent formatting context. flow-root The element generates a block element box that...
display - CSS: Cascading Style Sheets
play type, which defines the type of formatting context that its contents are laid out in (assuming it is a non-replaced element). Valid <display-inside> values: flow The element lays out its contents using flow layout (block-and-inline layout). If its outer display type is inline or run-in, and it is participating in a block or inline formatting context, then it generates an inline box.
Otherwise it generates a block container box. Depending on the value of other properties (such as position, float, or overflow) and whether it is itself participating in a block or inline formatting context, it either establishes a new block formatting context (BFC) for its contents or integrates its contents into its parent formatting context. flow-root The element generates a block element box that...
filter - CSS: Cascading Style Sheets
quivalent filter functions from the longer list are added to the end of the shorter list using their lacuna values, then all filter functions are interpolated according to their specific rules. If one filter is none, it is replaced with the filter functions list of the other one using the filter function default values, then all filter functions are interpolated according to their specific rules.
Otherwise, discrete interpolation is used. Functions The filter property is specified as none or one or more of the functions listed below. If the parameter for any function is invalid, the function returns none. Except where noted, the functions that take a value expressed with a percent sign (as in 34%) also accept the value expressed as decimal (as in 0.34). When a single filter property has two or m...
fit-content() - CSS: Cascading Style Sheets
values */ fit-content(200px) fit-content(5cm) fit-content(30vw) fit-content(100ch) /* <percentage> value */ fit-content(40%) Values <length> An absolute length. <percentage> A percentage relative to the available space in the given axis. In grid properties it is relative to the inline size of the grid container in column tracks and to the block size of the grid container for row tracks.
Otherwise it is relative to the available inline size or block size of the laid out box depending on the writing mode. Examples Sizing grid columns with fit-content HTML <div id="container"> <div>Item as wide as the content.</div> <div> Item with more text in it. Because the contents of it are wider than the maximum width, it is clamped at 300 pixels. </div> <div>Flexible item</div> </...
flex-basis - CSS: Cascading Style Sheets
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Note: in case both flex-basis (other than auto) and width (or height in case of flex-direction: column) are set for an element, flex-basis has priority. ...
flex-grow - CSS: Cascading Style Sheets
in the flex container should be assigned to the item (the flex grow factor). The main size is either width or height of the item which is dependent on the flex-direction value. The remaining space is the size of the flex container minus the size of all flex items' sizes together. If all sibling items have the same flex grow factor, then all items will receive the same share of remaining space,
otherwise it is distributed according to the ratio defined by the different flex grow factors. flex-grow is used alongside the other flex properties flex-shrink and flex-basis, and normally defined using the flex shorthand to ensure all values are set. Formal definition Initial value0Applies toflex items, including in-flow pseudo-elementsInheritednoComputed valueas specifiedAnimation typea number Forma...
font-kerning - CSS: Cascading Style Sheets
mation stored in a font. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Kerning defines how letters are spaced. In well-kerned fonts, this feature makes character spacing more uniform and pleasant to read than it would
otherwise be. In the image below, for instance, the examples on the left do not use kerning, while the ones on the right do: Syntax The font-kerning property is specified as one of the keyword values listed below. Values auto The browser determines whether font kerning should be used or not. For example, some browsers will disable kerning on small fonts, since applying it could harm the readabili...
font-style - CSS: Cascading Style Sheets
lique version of the font by slanting a normal face by the specified amount. Valid values are degree values of -90deg to 90deg inclusive. If an angle is not specified, an angle of 14 degrees is used. Positive values are slanted to the end of the line, while negative values are slanted towards the beginning. In general, for a requested angle of 14 degrees or greater, larger angles are prefered;
otherwise, smaller angles are preferred (see the spec's font matching section for the precise algorithm). Variable fonts Variable fonts can offer a fine control over the degree to which an oblique face is slanted. You can select this using the <angle> modifier for the oblique keyword. For TrueType or OpenType variable fonts, the "slnt" variation is used to implement varying slant angles for oblique, an...
grid-column-end - CSS: Cascading Style Sheets
ault span of 1. <custom-ident> If there is a named line with the name '<custom-ident>-end', it contributes the first such line to the grid item's placement. Note: Named grid areas automatically generate implicit named lines of this form, so specifying grid-column-end: foo; will choose the end edge of that named grid area (unless another line named foo-end was explicitly specified before it).
Otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. <integer> && <custom-ident>? Contributes the nth grid line to the grid item's placement. If a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. If a name is given as a <custom-ident>, only lines with that name are counted. If not enough lines with tha...
grid-column-start - CSS: Cascading Style Sheets
pan of 1. <custom-ident> If there is a named line with the name <custom-ident>-start, it contributes the first such line to the grid item's placement. Note: Named grid areas automatically generate implicit named lines of this form, so specifying grid-column-start: foo; will choose the start edge of that named grid area (unless another line named foo-start was explicitly specified before it).
Otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. <integer> && <custom-ident>? Contributes the nth grid line to the grid item's placement. If a negative integer is given, it counts in reverse, starting from the end edge of the explicit grid. If a name is given as a <custom-ident>, only lines with that name are counted. If not enough lines with that name e...
grid-column - CSS: Cascading Style Sheets
there is a named line with the name '<custom-ident>-start'/'<custom-ident>-end', it contributes the first such line to the grid item's placement. Note: Named grid areas automatically generate implicit named lines of this form, so specifying grid-column: foo; will choose the start/end edge of that named grid area (unless another line named foo-start/foo-end was explicitly specified before it).
Otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. <integer> && <custom-ident>? Contributes the nth grid line to the grid item's placement. If a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. If a name is given as a <custom-ident>, only lines with that name are counted. If not enough lines with tha...
grid-row-end - CSS: Cascading Style Sheets
default span of 1. <custom-ident> If there is a named line with the name '<custom-ident>-end', it contributes the first such line to the grid item's placement. Note: Named grid areas automatically generate implicit named lines of this form, so specifying grid-row-end: foo; will choose the end edge of that named grid area (unless another line named foo-end was explicitly specified before it).
Otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. The <custom-ident> cannot take the span value. <integer> && <custom-ident>? Contributes the nth grid line to the grid item's placement. If a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. If a name is given as a <custom-ident>, only lines with th...
grid-row-start - CSS: Cascading Style Sheets
an of 1. <custom-ident> If there is a named line with the name '<custom-ident>-start', it contributes the first such line to the grid item's placement. Note: Named grid areas automatically generate implicit named lines of this form, so specifying grid-row-start: foo; will choose the start edge of that named grid area (unless another line named foo-start was explicitly specified before it).
Otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. <integer> && <custom-ident>? Contributes the nth grid line to the grid item's placement. If a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. If a name is given as a <custom-ident>, only lines with that name are counted. If not enough lines with tha...
grid-row - CSS: Cascading Style Sheets
If there is a named line with the name '<custom-ident>-start'/'<custom-ident>-end', it contributes the first such line to the grid item's placement. Note: Named grid areas automatically generate implicit named lines of this form, so specifying grid-row: foo; will choose the start/end edge of that named grid area (unless another line named foo-start/foo-end was explicitly specified before it).
Otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. <integer> && <custom-ident>? Contributes the nth grid line to the grid item's placement. If a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. If a name is given as a <custom-ident>, only lines with that name are counted. If not enough lines with tha...
hanging-punctuation - CSS: Cascading Style Sheets
and last first, force-end, and last Values none No character hangs. first An opening bracket or quote at the start of the first formatted line of an element hangs. last A closing bracket or quote at the end of the last formatted line of an element hangs. force-end A stop or comma at the end of a line hangs. allow-end A stop or comma at the end of a line hangs if it does not
otherwise fit prior to justification. Formal definition Initial valuenoneApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Formal syntax none | [ first | [ force-end | allow-end ] | last ] Examples Setting opening and closing quotes to hang HTML <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur dignissim nunc mauris, et sollicitudin est sceleri...
<image> - CSS: Cascading Style Sheets
If language is rtl, the image will be horizontally flipped. */ cross-fade(20% url(twenty.png), url(eighty.png)) /* cross faded images, with twenty being 20% opaque and eighty being 80% opaque. */ image-set('test.jpg' 1x, 'test-2x.jpg' 2x) /* a selection of imag...
offset-distance - CSS: Cascading Style Sheets
ance: 40px; <length-percentage> A length that specifies how far the element is along the path (defined with offset-path). 100% represents the total length of the path (when the offset-path is defined as a basic shape or path()). Formal definition Initial value0Applies totransformable elementsInheritednoPercentagesrefer to the total path lengthComputed valuefor <length> the absolute value,
otherwise a percentageAnimation typea length, percentage or calc(); Formal syntax <length-percentage>where <length-percentage> = <length> | <percentage> Examples Using offset-distance in an animation The motion aspect in CSS Motion Path typically comes from animating the offset-distance property. If you want to animate an element along its full path, you would define its offset-path and then set up an...
offset-position - CSS: Cascading Style Sheets
specified, the second value is assumed to be center. If three or four values are used, the length-percentage values are offsets for the preceding keyword value(s). For more explanation of these value types, see background-position. ...
offset - CSS: Cascading Style Sheets
ath: noneoffset-distance: 0offset-anchor: autooffset-rotate: autoApplies totransformable elementsInheritednoPercentagesas each of the properties of the shorthand:offset-position: referToSizeOfContainingBlockoffset-distance: refer to the total path lengthoffset-anchor: relativeToWidthAndHeightComputed valueas each of the properties of the shorthand:offset-position: for <length> the absolute value,
otherwise a percentageoffset-path: as specifiedoffset-distance: for <length> the absolute value,
otherwise a percentageoffset-anchor: for <length> the absolute value,
otherwise a percentageoffset-rotate: as specifiedAnimation typeas each of the properties of the shorthand:offset-position: a positionoffset-path: as <angle>, <basic-shape> or <path()>offset-distance: a length, percentage or calc();offset-anch...
overflow - CSS: Cascading Style Sheets
* Keyword values */ overflow: visible; overflow: hidden; overflow: clip; overflow: scroll; overflow: auto; overflow: hidden visible; /* Global values */ overflow: inherit; overflow: initial; overflow: unset; The overflow property is specified as one or two keywords chosen from the list of values below. If two keywords are specified, the first applies to overflow-x and the second to overflow-y.
Otherwise, both overflow-x and overflow-y are set to the same value. Values visible Content is not clipped and may be rendered outside the padding box. hidden Content is clipped if necessary to fit the padding box. No scrollbars are provided, and no support for allowing the user to scroll (such as by dragging or using a scroll wheel) is allowed. The content can be scrolled programmatically (for exam...
perspective-origin - CSS: Cascading Style Sheets
The value may be negative. top, a keyword being a shortcut for the 0 length value. center, a keyword being a shortcut for the 50% percentage value. bottom, a keyword being a shortcut for the 100% percentage value. ...
place-self - CSS: Cascading Style Sheets
boxes, absolutely-positioned boxes, and grid itemsInheritednoComputed valueas each of the properties of the shorthand:align-self: auto computes to itself on absolutely-positioned elements, and to the computed value of align-items on the parent (minus any legacy keywords) on all other boxes, or start if the box has no parent. Its behavior depends on the layout model, as described for justify-self.
Otherwise the specified value.justify-self: as specifiedAnimation typediscrete Formal syntax <'align-self'> <'justify-self'>? Examples Simple demonstration In the following example we have a simple 2 x 2 grid layout. Initially the grid container has justify-items and align-items values of stretch -- the defaults -- which causes the grid items to stretch across the entire width of their cells. The sec...
quotes - CSS: Cascading Style Sheets
valueas specifiedAnimation typediscrete Formal syntax none | auto | [ <string> <string> ]+ Examples Basic quote marks HTML <q>To be or not to be. That's the question!</q> CSS q { quotes: '"' '"' "'" "'"; } q::before { content: open-quote; } q::after { content: close-quote; } Result Auto quotes For most browsers, the default value of quotes is auto (Firefox 70+), or the browser
otherwise had this default behavior (Chromiums, Safari, Edge), so this example works without it being explicitly being set. HTML <div lang="fr"> <q>Ceci est une citation francaise.</q> <div> <hr> <div lang="ru"> <q>??? ??????? ??????</q> <div> <hr> <div lang="de"> <q>Dies ist ein deutsches Zitat</q> <div> <hr> <div lang="en"> <q>This is an English quote.</q> <div> CSS /*q { quotes: auto; }...
repeat() - CSS: Cascading Style Sheets
the grid track. auto-fill If the grid container has a definite or maximal size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container. Treating each track as its maximal track sizing function (each independant value used to define grid-template-rows or grid-template-columns), if that is definite.
Otherwise, as its minimum track sizing function, and taking grid-gap into account. If any number of repetitions would overflow, then the repetition is 1.
Otherwise, if the grid container has a definite minimal size in the relevant axis, the number of repetitions is the smallest possible positive integer that fulfills that minimum requirement.
Otherwise, the specified track list repeats only once. auto-fit...
revert - CSS: Cascading Style Sheets
ser agent's stylesheet (or by user styles, if any exist). It can be applied to any CSS property, including the CSS shorthand all. This removes from the cascade all of the styles that have been overridden until the style being rolled back to is reached. If used by a site's own styles (the author origin), revert rolls back the property's cascaded value to the user's custom style, if one exists;
otherwise, it rolls the style back to the user agent's default style. If used in a user's custom stylesheet, or if the style was applied by the user (the user origin), revert rolls back the cascaded value to the user agent's default style. If used within the user agent's default styles, this keyword is functionally equivalent to unset. The revert keyword works exactly the same as unset in many cases. T...
right - CSS: Cascading Style Sheets
he case, the left value has precedence when the container is left-to-right; the right value has precedence when the container is right-to-left. ...
<string> - CSS: Cascading Style Sheets
surrounded by either double (") or single (') quotes. Most characters can be represented literally. All characters can also be represented with their respective Unicode code points in hexadecimal, in which case they are preceded by a backslash (\). For example, \22 represents a double quote, \27 a single quote ('), and \A9 the copyright symbol ((C)). Importantly, certain characters which would
otherwise be invalid can be escaped with a backslash. These include double quotes when used inside a double-quoted string, single quotes when used inside a single-quoted string, and the backslash itself. For example, \\ will create a single backslash. To output new lines, you must escape them with a line feed character such as \A or \00000A. In your code, however, strings can span multiple lines, in which...
table-layout - CSS: Cascading Style Sheets
ths. Under the "fixed" layout method, the entire table can be rendered once the first table row has been downloaded and analyzed. This can speed up rendering time over the "automatic" layout method, but subsequent cell content might not fit in the column widths provided. Cells use the overflow property to determine whether to clip any overflowing content, but only if the table has a known width;
otherwise, they won't overflow the cells. Formal definition Initial valueautoApplies totable and inline-table elementsInheritednoComputed valueas specifiedAnimation typediscrete Formal syntax auto | fixed Examples Fixed-width tables with text-overflow This example uses a fixed table layout, combined with the width property, to restrict the table's width. The text-overflow property is used to apply ...
text-decoration-skip-ink - CSS: Cascading Style Sheets
it; text-decoration-skip: initial; text-decoration-skip: unset; Values none Underlines and overlines are drawn across the full length of the text content, including parts that cross over glyph descenders and ascenders. auto The default -- the browser may interrupt underlines and overlines so that they do not touch or closely approach a glyph. That is, they are interrupted where they would
otherwise cross over a glyph. all The browser must interrupt underlines and overlines so that they do not touch or closely approach a glyph. This can be helpful with certain Chinese, Japanese, or Korean (CJK) fonts, where the auto behavior might not create interruptions. Formal definition Initial valueautoApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Formal synt...
top - CSS: Cascading Style Sheets
t (which might not be its containing block). This computed value is then handled as if it were a <length>, <percentage>, or the auto keyword. ...
transform-origin - CSS: Cascading Style Sheets
words are convenience shorthands and match the following <percentage> values: Keyword Value left 0% center 50% right 100% top 0% bottom 100% Formal definition Initial value50% 50% 0Applies totransformable elementsInheritednoPercentagesrefer to the size of bounding 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; <...
user-select - CSS: Cascading Style Sheets
issues, make the final behavior meets the specifications. Syntax none The text of the element and its sub-elements is not selectable. Note that the Selection object can contain these elements. auto The used value of auto is determined as follows: On the ::before and ::after pseudo elements, the used value is none If the element is an editable element, the used value is contain
Otherwise, if the used value of user-select on the parent of this element is all, the used value is all
Otherwise, if the used value of user-select on the parent of this element is none, the used value is none
Otherwise, the used value is text text The text can be selected by the user. all The content of the element shall be selected atomically: If a selection would contain part of the element,...
vertical-align - CSS: Cascading Style Sheets
in the row. bottom Aligns the bottom padding edge of the cell with the bottom of the row. Negative values are allowed. Formal definition Initial valuebaselineApplies toinline-level and table-cell elements. ...
will-change - CSS: Cascading Style Sheets
or consume a lot of resources. Use sparingly. The normal behavior for optimizations that the browser make is to remove the optimizations as soon as it can and revert back to normal. But adding will-change directly in a stylesheet implies that the targeted elements are always a few moments away from changing and the browser will keep the optimizations for much longer time than it would have
otherwise. So it is a good practice to switch will-change on and off using script code before and after the change occurs. Don't apply will-change to elements to perform premature optimization. If your page is performing well, don't add the will-change property to elements just to wring out a little more speed. will-change is intended to be used as something of a last resort, in order to try to deal ...
regexp:replace() - EXSLT
m a search-and-replace operation upon. regExpString The JavaScript style regular expression to evaluate. flagsString The string containing character flags. replaceString The string with which the matched substrings are to be replaced. The character flags are: g - Global replace If this flag is specified, all occurrences of the regular expression within the originalString are replaced.
Otherwise only the first occurrence is replaced. i - Case insensitive match If this flag is specified, the match is performed in a case insensitive fashion. Returns The revised version of the string. Specifications EXSLT - REGEXP:REPLACE ...
Getting Started - Developer guides
, you need to actually make the request, by calling the open() and send() methods of the HTTP request object, like this: httpRequest.open('GET', 'http://www.example.org/some.file', true); httpRequest.send(); The first parameter of the call to open() is the HTTP request method - GET, POST, HEAD, or another method supported by your server. Keep the method all-capitals as per the HTTP standard,
otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods, check the W3C specs. The second parameter is the URL you're sending the request to. As a security feature, you cannot call URLs on 3rd-party domains by default. Be sure to use the exact domain name on all of your pages or you will get a "permission denied" error when you call op...
Video player styling basics - Developer guides
r set. There are some browser-specific properties that need to be set to ensure that Firefox and Chrome use the required colour for the progress bar: .controls progress::-moz-progress-bar { background-color:#0095dd; } .controls progress::-webkit-progress-value { background-color:#0095dd; } Although the same properties are set to the same value, these rules need to be defined separately,
otherwise Chrome ignores it. JavaScript That's really it for the immediate styling; the next task is making a number of JavaScript changes to ensure that everything works as expected. Control visibility The first change is simple: the data-state for showing the video controls when JavaScript is available to the browser now needs to be set: // Display the user defined video controls videoControls.setAt...
Event developer guide - Developer guides
nts, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or
otherwise changes it. The process loading of a web page can trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user. The user interaction with the web page contents can trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
% is the same as 1.0. For example, a bright red that's 50% opaque can be represented as rgb(255, 0, 0, 0.5) or rgb(100%, 0, 0, 50%). HSL functional notation Designers and artists often prefer to work using the HSL (Hue/Saturation/Luminosity) color method. On the web, HSL colors are represented using HSL functional notation. The hsl() CSS function is very similar to the rgb() function in usage
otherwise. Figure 1. An HSL color cylinder. Hue defines the actual color based on the position along a circular color wheel representing the colors of the visible spectrum. Saturation is a percentage of how much of the way between being a shade of gray and having the maximum possible amount of the given hue. As the value of luminance (or lightness) increases, the color transitions from the darkest possi...
disabled - HTML: Hypertext Markup Language
cannot interact with the control or it's descendant controls. If this attribute is not specified, the control inherits its setting from the containing element, for example fieldset; if there is no containing element with the disabled attribute set, and the control itself does not have the attribute, then the control is enabled. If declared on an <optgroup>, the select is still interactive (unless
otherwise disabled), but none of the items in the option group are selectable. Note: If a <fieldset> is disabled, the descendant form controls are all disabled, with the exception of form controls within the <legend>. When a supporting element has the disabled attribute applied, the :disabled pseudo-class also applies to it. Conversely, elements that support the disabled attribute but don't have the at...
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>. This must be an integer value 0 or higher. If no minlength is specified, or an invalid value is specified, the input has no minimum length. This value must be less than or equal to the value of maxlength,
otherwise the value will never be valid, as it is impossible to meet both criteria. The input will fail constraint validation if the length of the text value of the field is less than minlength UTF-16 code units long, with validityState.tooShort returning true. Constraint validation is only applied when the value is changed by the user. Once submission fails, some browsers will display an error message indicating the minimum length required and the curr...
Date and time formats used in HTML - HTML: Hypertext Markup Language
es through the Royal Observatory at Greenwich, England). For dates prior to UTC, the time base is instead expressed in terms of UT1, which is the contemporary Earth solar time at the prime meridian. The time zone string is appended immediately following the time in the date and time string. You can specify simply "Z" as the time zone offset string to indicate that the time is specified in UTC.
Otherwise, the time zone string is constructed as follows: A character indicating the sign of the offset: the plus character ("+", or U+002B) for time zones to the east of the prime meridian or the minus character ("-", or U+002D) for time zones to the west of the prime meridian. A two-digit number of hours that the time zone is offset from the prime meridian. This value must be between 00 and 23. An ...
<b>: The Bring Attention To element - HTML: Hypertext Markup Language
This was formerly known as the Boldface element, and most browsers still draw the text in boldface. However, you should not use <b> for styling text; instead, you should use the CSS font-weight property to create boldface text, or the <strong> element to indicate that text is of special importance. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
<button>: The Button element - HTML: Hypertext Markup Language
owner, either by wrapping it in a <form> or set the attribute form to the id of the form. <button> elements are much easier to style than <input> elements. You can add inner HTML content (think <i>, <br>, or even <img>), and use ::after and ::before pseudo-elements for complex rendering. If your buttons are not for submitting form data to a server, be sure to set their type attribute to button.
Otherwise they will try to submit form data and to load the (nonexistent) response, possibly destroying the current state of the document. Example <button name="button">Press me</button> Accessibility concerns Icon buttons Buttons that only show an icon to represent do not have an accessible name. Accessible names provide information for assistive technology, such as screen readers, to access when ...
<dfn>: The Definition element - HTML: Hypertext Markup Language
term being defined. The element must still have text within it, but that text may be an abbreviation (perhaps using <abbr>) or another form of the term. If the <dfn> contains a single child element and does not have any text content of its own, and the child element is an <abbr> element with a title attribute itself, then the exact value of the <abbr> element's title is the term being defined.
Otherwise, the text content of the <dfn> element is the term being defined. This is shown in the first example below. If the <dfn> element has a title attribute, it must contain the term being defined and no other text. Links to <dfn> elements If you include an id attribute on the <dfn> element, you can then link to it using <a> elements. Such links should be uses of the term, with the intent being t...
<figure>: The Figure with Optional Caption element - HTML: Hypertext Markup Language
Permitted content A <figcaption> element, followed by flow content; or flow content followed by a <figcaption> element; or flow content. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts Flow content. Implicit ARIA role figure Permitted ARIA roles With no figcaption descendant: any,
otherwise no permitted roles DOM interface HTMLElement Attributes This element only includes the global attributes. Usage notes Usually a <figure> is an image, illustration, diagram, code snippet, etc., that is referenced in the main flow of a document, but that can be moved to another part of the document or to an appendix without affecting the main flow. Being a sectioning root, ...
<form> - HTML: Hypertext Markup Language
he elements inside the form are valid. Content categories Flow content, palpable content Permitted content Flow content, but not containing <form> elements Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts flow content Implicit ARIA role form if the form has an accessible name,
otherwise no corresponding role Permitted ARIA roles search, none or presentation DOM interface HTMLFormElement Attributes This element includes the global attributes. accept Comma-separated content types the server accepts. This attribute was removed in HTML5 and should not be used. Instead, use the accept attribute on <input type=file> elements. accept-charset S...
<head>: The Document Metadata (Header) element - HTML: Hypertext Markup Language
not human-readability. For human-visible information, like top-level headings and listed authors, see the <header> element. Content categories None. Permitted content If the document is an <iframe> srcdoc document, or if title information is available from a higher level protocol (like the subject line in HTML email), zero or more elements of metadata content.
Otherwise, one or more elements of metadata content where exactly one is a <title> element. Tag omission The start tag may be omitted if the first thing inside the <head> element is an element. The end tag may be omitted if the first thing following the <head> element is not a space character or a comment. Permitted parents An <html> element, as its first child. Imp...
<hgroup> - HTML: Hypertext Markup Language
taglines without using <hgroup>. The <hgroup> element allows the primary heading for a document section to be grouped with any secondary headings--such as subheadings or alternative titles--to form a multi-level heading. In other words, the <hgroup> element prevents any of its secondary <h1>-<h6> children from creating separate sections of their own in the outline--as those <h1>-<h6> elements
otherwise normally would if they were not children of any <hgroup>. So in the abstract outline produced by the HTML outline algorithm defined in the HTML specification, the <hgroup> as a whole forms a single logical heading, with the entire set of <h1>-<h6> children of the <hgroup> going into the outline as one multi-level unit, to comprise that single logical heading in the abstract outline. To produce ...
<input type="checkbox"> - HTML: Hypertext Markup Language
sers on macOS may draw the checkbox with a hyphen "-" inside to indicate an unexpected state. value The value attribute is one which all <input>s share; however, it serves a special purpose for inputs of type checkbox: when a form is submitted, only checkboxes which are currently checked are submitted to the server, and the reported value is the value of the value attribute. If the value is not
otherwise specified, it is the string on by default. This is demonstrated in the section Value above. Using checkbox inputs We already covered the most basic use of checkboxes above. Let's now look at the other common checkbox-related features and techniques you'll need. Handling multiple checkboxes The example we saw above only contained one checkbox; in real-world situations you'll be likely to encou...
<input type="date"> - HTML: Hypertext Markup Language
element has no minimum date value. If both the max and min attributes are set, this value must be a date string earlier than or equal to the one in the max attribute. step The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal to the basis for stepping (min if specified, value
otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max). Note: When the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction wh...
<input type="datetime-local"> - HTML: Hypertext Markup Language
format yyyy-MM-ddThh:mm, then the element has no minimum value. This value must specify a date string earlier than or equal to the one specified by the max attribute. step The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal to the basis for stepping (min if specified, value
otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max). Note: When the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction wh...
<input type="email"> - HTML: Hypertext Markup Language
low browsers latitude on this. For example, the element could be integrated with the user's device's built-in address book to allow picking e-mail addresses from that list. In its most basic form, an email input can be implemented like this: <input id="emailAddress" type="email"> Notice that it's considered valid when empty and when a single validly-formatted e-mail address is entered, but is
otherwise not considered valid. By adding the required attribute, only validly-formed e-mail addresses are allowed; the input is no longer considered valid when empty. Allowing multiple e-mail addresses By adding the multiple Boolean attribute, the input can be configured to accept multiple e-mail addresses. <input id="emailAddress" type="email" multiple> The input is now considered valid when a sing...
<input type="month"> - HTML: Hypertext Markup Language
tElement.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal to the basis for stepping (min if specified, value
otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max). Note: When the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction wh...
<input type="radio"> - HTML: Hypertext Markup Language
tate of an <input> across page loads. Use the autocomplete attribute to control this feature. value The value attribute is one which all <input>s share; however, it serves a special purpose for inputs of type radio: when a form is submitted, only radio buttons which are currently checked are submitted to the server, and the reported value is the value of the value attribute. If the value is not
otherwise specified, it is the string on by default. This is demonstrated in the section Value above. Using radio inputs We already covered the fundamentals of radio buttons above. Let's now look at the other common radio-button-related features and techniques you may need to know about. Selecting a radio button by default To make a radio button selected by default, you simply include checked attribute...
<input type="range"> - HTML: Hypertext Markup Language
for min that isn't a valid number, the input has no minimum value. This value must be less than or equal to the value of the max attribute. See the HTML min attribute. step The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal to the basis for stepping (min if specified, value
otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max). Note: When the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction wh...
<input type="reset"> - HTML: Hypertext Markup Language
hile trying to click the submit button). Value A DOMString used as the button's label Events click Supported common attributes type and value IDL attributes value Methods None Value An <input type="reset"> element's value attribute contains a DOMString that is used as the button's label. Buttons such as reset don't have a value
otherwise. <input type="reset" value="Reset the form"> If you don't specify a value, you get an button with the default label (typically "Reset," but this will vary depending on the user agent): <input type="reset"> Using reset buttons <input type="reset"> buttons are used to reset forms. If you want to create a custom button and then customize the behaviour using JavaScript, you need to use <...
<input type="search"> - HTML: Hypertext Markup Language
eets to apply custom styles to them). Basic example <form> <div> <input type="search" id="mySearch" name="q"> <button>Search</button> </div> </form> This renders like so: q is the most common name given to search inputs, although it's not mandatory. When submitted, the data name/value pair sent to the server will be q=searchterm. You must remember to set a name for your input,
otherwise nothing will be submitted. Differences between search and text types The main basic differences come in the way browsers handle them. The first thing to note is that some browsers show a cross icon that can be clicked on to remove the search term instantly if desired. The following screenshot comes from Chrome: In addition, modern browsers also tend to automatically store search terms previ...
<input type="submit"> - HTML: Hypertext Markup Language
put type="submit" value="Send Request"> Value A DOMString used as the button's label Events click Supported common attributes type and value IDL attributes value Methods None Value An <input type="submit"> element's value attribute contains a DOMString which is displayed as the button's label. Buttons do not have a true value
otherwise. <input type="submit" value="Send Request"> If you don't specify a value, the button will have a default label, chosen by the user agent. This label is likely to be something along the lines of "Submit" or "Submit Query." Here's an example of a submit button with a default label in your browser: <input type="submit"> Additional attributes In addition to the attributes shared by all <...
<input type="text"> - HTML: Hypertext Markup Language
v> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name"> </div> <div> <button>Submit</button> </div> </form> This renders like so: When submitted, the data name/value pair sent to the server will be uname=Chris (if "Chris" was entered as the input value before submission). You must remember to include name attribute on the <input> element,
otherwise the text field's value won't be included with the submitted data. Setting placeholders You can provide a useful placeholder inside your text input that can provide a hint as to what to enter by including using the placeholder attribute. Look at the following example: <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" place...
<input type="url"> - HTML: Hypertext Markup Language
plications of any kind. A simple URL input Currently, all browsers which implement this element implement it as a standard text input field with basic validation features. In its most basic form, a URL input can be implemented like this: <input id="myURL" name="myURL" type="url"> Notice that it's considered valid when empty and when a single validly-formatted URL address is entered, but is
otherwise not considered valid. By adding the required attribute, only properly-formed URLs are allowed; the input is no longer considered valid when empty. There is nothing magical going on here. Submitting this form would cause the following data to be sent to the server: myURL=http%3A%2F%2Fwww.example.com. Note how characters are escaped as necessary. Placeholders Sometimes it's helpful to offer an i...
<input type="week"> - HTML: Hypertext Markup Language
tElement.value property. Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal to the basis for stepping (min if specified, value
otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max). Note: When the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction wh...
<link>: The External Resource Link element - HTML: Hypertext Markup Language
links, the restricted set of media queries defined in HTML 4. referrerpolicy A string indicating which referrer to use when fetching the resource: no-referrer means that the Referer header will not be sent. no-referrer-when-downgrade means that no Referer header will be sent when navigating to an origin without TLS (HTTPS). This is a user agent's default behavior, if no policy is
otherwise specified. origin means that the referrer will be the origin of the page, which is roughly the scheme, the host, and the port. origin-when-cross-origin means that navigating to other origins will be limited to the scheme, the host, and the port, while navigating on the same origin will include the referrer's path. unsafe-url means that the referrer will include the origin and the path (but ...
<mark>: The Mark Text element - HTML: Hypertext Markup Language
include: When used in a quotation (<q>) or block quote (<blockquote>), it generally indicates text which is of special interest but is not marked in the original source material, or material which needs special scrutiny even though the original author didn't think it was of particular importance. Think of this like using a highlighter pen in a book to mark passages that you find of interest.
Otherwise, <mark> indicates a portion of the document's content which is likely to be relevant to the user's current activity. This might be used, for example, to indicate the words that matched a search operation. Don't use <mark> for syntax highlighting purposes; instead, use the <span> element with appropriate CSS applied to it. Don't confuse <mark> with the <strong> element; <mark> is used to denot...
<noscript> - HTML: Hypertext Markup Language
ng content. Permitted content When scripting is disabled and when it is a descendant of the <head> element: in any order, zero or more <link> elements, zero or more <style> elements, and zero or more <meta> elements. When scripting is disabled and when it isn't a descendant of the <head> element: any transparent content, but no <noscript> element must be among its descendants.
Otherwise: flow content or phrasing content. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts phrasing content, if there are no ancestor <noscript> element, or in a <head> element (but only for an HTML document), here again if there are no ancestor <noscript> element. Implicit ARIA role No corresponding role ...
<ol>: The Ordered List element - HTML: Hypertext Markup Language
ou like. The <ol> and <ul> elements both represent a list of items. The difference is with the <ol> element, the order is meaningful. For example: Steps in a recipe Turn-by-turn directions The list of ingredients in decreasing proportion on nutrition information labels To determine which list to use, try changing the order of the list items; if the meaning changes, use the <ol> element --
otherwise you can use <ul>. Examples Simple example <ol> <li>Fee</li> <li>Fi</li> <li>Fo</li> <li>Fum</li> </ol> The above HTML will output: Using Roman Numeral type <ol type="i"> <li>Introduction</li> <li>List of Greivances</li> <li>Conclusion</li> </ol> The above HTML will output: Using the start attribute <p>Finishing places of contestants not in the winners' circle:</p> <o...
<output>: The Output element - HTML: Hypertext Markup Language
ending tag are mandatory. Permitted parents Any element that accepts phrasing content. Implicit ARIA role status Permitted ARIA roles Any DOM interface HTMLOutputElement Attributes This element includes the global attributes. for A space-separated list of other elements' ids, indicating that those elements contributed input values to (or
otherwise affected) the calculation. form The <form> element to associate the output with (its form owner). The value of this attribute must be the id of a <form> in the same document. (If this attribute is not set, the <output> is associated with its ancestor <form> element, if any.) This attribute lets you associate <output> elements to <form>s anywhere in the document, not just inside a <form>. It ca...
<script>: The Script element - HTML: Hypertext Markup Language
in effect, this can be used to serve fallback scripts to older browsers that do not support modular JavaScript code. nonce A cryptographic nonce (number used once) to whitelist scripts in a script-src Content-Security-Policy. The server must generate a unique nonce value each time it transmits a policy. It is critical to provide a nonce that cannot be guessed as bypassing a resource's policy is
otherwise trivial. referrerpolicy Indicates which referrer to send when fetching the script, or resources fetched by the script: no-referrer: The Referer header will not be sent. no-referrer-when-downgrade (default): The Referer header will not be sent to origins without TLS (HTTPS). origin: The sent referrer will be limited to the origin of the referring page: its scheme, host, and port. origi...
<section>: The Generic Section element - HTML: Hypertext Markup Language
low content, Sectioning content, palpable content. Permitted content Flow content. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts flow content. Note that a <section> element must not be a descendant of an <address> element. Implicit ARIA role region if the element has an accessible name,
otherwise no corresponding role Permitted ARIA roles alert, alertdialog, application, banner, complementary, contentinfo, dialog, document, feed, log, main, marquee, navigation, none, note, presentation, search, status, tabpanel DOM interface HTMLElement Attributes This element only includes the global attributes. Usage notes Each <section> should be identified, typicall...
<select>: The HTML Select element - HTML: Hypertext Markup Language
ed, labelable, resettable, and submittable form-associated element Permitted content Zero or more <option> or <optgroup> elements. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts phrasing content. Implicit ARIA role combobox with no multiple attribute and no size attribute greater than 1,
otherwise listbox Permitted ARIA roles menu with no multiple attribute and no size attribute greater than 1,
otherwise no role permitted DOM interface HTMLSelectElement Specifications Specification Status Comments HTML Living StandardThe definition of '<select>' in that specification. Living Standard HTML5The definition of '<select...
<style>: The Style Information element - HTML: Hypertext Markup Language
style should be applied to. Its value is a media query, which defaults to all if the attribute is missing. nonce A cryptographic nonce (number used once) used to whitelist inline styles in a style-src Content-Security-Policy. The server must generate a unique nonce value each time it transmits a policy. It is critical to provide a nonce that cannot be guessed as bypassing a resource's policy is
otherwise trivial. title This attribute specifies alternative style sheet sets. Deprecated attributes scoped This attribute specifies that the styles only apply to the elements of its parent(s) and children. This attribute may be re-introduced in the future per https://github.com/w3c/csswg-drafts/issues/3547. If you want to use the attribute now, you can use a polyfill. Examples A ...
<sub>: The Subscript element - HTML: Hypertext Markup Language
for <sub> include (but aren't necessarily limited to): Marking up footnote numbers. See Footnote numbers for an example. Marking up the subscript in mathematical variable numbers (although you may also consider using a MathML formula for this). See Variable subscripts. Denoting the number of atoms of a given element within a chemical formula (such as every developer's best friend, C8H10N4O2,
otherwise known as "caffeine"). See Chemical formulas. Examples Footnote numbers Traditional footnotes are denoted using numbers which are rendered in subscript. This is a common use case for <sub>: <p>According to the computations by Nakamura, Johnson, and Mason<sub>1</sub> this will result in the complete annihilation of both particles.</p> The resulting output looks like this: Variable subscrip...
<tr>: The Table Row element - HTML: Hypertext Markup Language
owed Tag omission Start tag is mandatory. End tag may be omitted if the <tr> element is immediately followed by a <tr> element, or if the row is the last element in its parent table group (<thead>, <tbody> or <tfoot>) element Permitted parents <table> (only if the table has no child <tbody> element, and even then only after any <caption>, <colgroup>, and <thead> elements);
otherwise, the parent must be <thead>, <tbody> or <tfoot> Implicit ARIA role row Permitted ARIA roles Any DOM interface HTMLTableRowElement Specifications Specification Status Comment HTML Living StandardThe definition of 'tr element' in that specification. Living Standard The WHATWG Living Standard HTML5The definition o...
<ul>: The Unordered List element - HTML: Hypertext Markup Language
ay be nested as deeply as desired. Moreover, the nested lists may alternate between <ol> and <ul> without restriction. The <ol> and <ul> elements both represent a list of items. They differ in that, with the <ol> element, the order is meaningful. As a rule of thumb to determine which one to use, try changing the order of the list items; if the meaning is changed, the <ol> element should be used,
otherwise you can use <ul>. Examples Simple example <ul> <li>first item</li> <li>second item</li> <li>third item</li> </ul> The above HTML will output: Nesting a list <ul> <li>first item</li> <li>second item <!-- Look, the closing </li> tag is not placed here! --> <ul> <li>second item first subitem</li> <li>second item second subitem <!-- Same for the second nest...
<var>: The Variable element - HTML: Hypertext Markup Language
ier New", monospace; } Examples Basic example Here's a simple example, using <var> to denote variable names in a mathematical equation. <p>A simple equation: <var>x</var> = <var>y</var> + 2 </p> The output: Overriding the default style Using CSS, you can override the default style for the <var> element. In this example, variable names are rendered using bold Courier if it's available,
otherwise it falls back to the default monospace font. CSS var { font: bold 15px "Courier", "Courier New", monospace; } HTML <p>The variables <var>minSpeed</var> and <var>maxSpeed</var> control the minimum and maximum speed of the apparatus in revolutions per minute (RPM).</p> This HTML uses <var> to enclose the names of two variables. Result Specifications Specification Statu...
<wbr> - HTML: Hypertext Markup Language
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Content categories Flow content, phrasing content. ...
tabindex - HTML: Hypertext Markup Language
elements are not be listed in the accessibility tree. This prevents assistive technology from being able to navigate to and manipulate those components. The content should be semantically described using interactive elements (<a>, <button>, <details>, <input>, <select>, <textarea>, etc.) instead. These elements have built-in roles and states that communicate status to the accessibility that would
otherwise have to be managed by ARIA. Using the tabindex attribute | The Paciello Group Specifications Specification Status Comment HTML Living StandardThe definition of 'tabindex' in that specification. Living Standard No change from latest snapshot, HTML 5.1. HTML 5.1The definition of 'tabindex' in that specification. Recommendation Snapshot of HTML ...
Link types - HTML: Hypertext Markup Language
alternate If the element is <link> and the rel attribute also contains the stylesheet type, the link defines an alternative style sheet; in that case the title attribute must be present and not be the empty string. If the type is set to application/rss+xml or application/atom+xml, the link defines a syndication feed. The first one defined on the page is the default. ...
Using the application cache - HTML: Hypertext Markup Language
e a cached resource (for example, you update the header.png image with new content), you must also change the content of the manifest file in order to let browsers know that they need to refresh the cache. You can make any change you want to the manifest file, but revising a version number is the recommended best practice. Important: Do not specify the manifest itself in the cache manifest file,
otherwise it will be nearly impossible to inform the browser a new manifest is available. Sections in a cache manifest file: CACHE, NETWORK, and FALLBACK A manifest can have three distinct sections: CACHE, NETWORK, and FALLBACK. CACHE: This is the default section for entries in a cache manifest file. Files listed under the CACHE: section header (or immediately after the CACHE MANIFEST line) are expli...
Data URLs - HTTP
ndicating the type of data, an optional base64 token if non-textual, and the data itself: data:[<mediatype>][;base64],<data> The mediatype is a MIME type string, such as 'image/jpeg' for a JPEG image file. If omitted, defaults to text/plain;charset=US-ASCII If the data is textual, you can simply embed the text (using the appropriate entities or escapes based on the enclosing document's type).
Otherwise, you can specify base64 to embed base64-encoded binary data. You can find more info on MIME types here and here. A few examples: data:,Hello%2C%20World! Simple text/plain data. Note the use of percent-encoding (URL-encoding) for the quote and space characters. Also, for CSV data (MIME type "text/csv"), percent-encoding is needed to preserve the line endings that delimit rows of the spreadshe...
Identifying resources on the Web - HTTP
ively, it is possible to directly use an IP address, but because it is less convenient, it is not often used on the Web. Port :80 is the port in this instance. It indicates the technical "gate" used to access the resources on the web server. It is usually omitted if the web server uses the standard ports of the HTTP protocol (80 for HTTP and 443 for HTTPS) to grant access to its resources.
Otherwise it is mandatory. Path /path/to/myfile.html is the path to the resource on the Web server. In the early days of the Web, a path like this represented a physical file location on the Web server. Nowadays, it is mostly an abstraction handled by Web servers without any physical reality. Query ?key1=value1&key2=value2 are extra parameters provided to the Web server. Those parameters are ...
Configuring servers for Ogg media - HTTP
requests to retrieve the media from the seek target position. In addition, Gecko uses byte-range requests to seek to the end of the media (assuming you serve the Content-Length header) in order to determine the duration of the media. Your server should accept the Accept-Ranges: bytes HTTP header if it can accept byte-range requests. It must return 206: Partial content to all byte range requests;
otherwise, browsers can't be sure you actually support byte range requests. Your server must also return 206: Partial Content for the request Range: bytes=0- as well. Include regular key frames When the browser seeks through Ogg media to a specified time, it has to seek to the nearest key frame before the seek target, then download and decode the video from there until the requested target time. The far...
Content negotiation - HTTP
sharing the amount of device memory with the server. The value is given in miliseconds and it's use is optional. The Accept-Encoding header The Accept-Encoding header defines the acceptable content-encoding (supported compressions). The value is a q-factor list (e.g.: br, gzip;q=0.8) that indicates the priority of the encoding values. The default value identity is at the lowest priority (unless
otherwise declared). Compressing HTTP messages is one of the most important ways to improve the performance of a Web site, it shrinks the size of the data transmitted and makes better use of the available bandwidth; browsers always send this header and the server should be configured to abide to it and to use compression. The Accept-Language header The Accept-Language header is used to indicate the lang...
Age - HTTP
The Age header contains the time in seconds the object has been in a proxy cache. The Age header is usually close to zero. If it is Age: 0, it was probably just fetched from the origin server;
otherwise It is usually calculated as a difference between the proxy's current date and the Date general header included in the HTTP response. Header type Response header Forbidden header name no Syntax Age: <delta-seconds> Directives <delta-seconds> A non-negative integer, representing time in seconds the object has been in a proxy cache. Examples Age: 24 Specifications Specification Title RFC 7234, section 5.1: Age Hypertext Transfer Protocol (HTTP/1.1): Caching ...
CSP: base-uri - HTTP
The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: child-src - HTTP
u must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: connect-src - HTTP
The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: default-src - HTTP
The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: font-src - HTTP
u must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: form-action - HTTP
The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: frame-src - HTTP
u must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: img-src - HTTP
The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: manifest-src - HTTP
u must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: media-src - HTTP
u must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: navigate-to - HTTP
The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: object-src - HTTP
u must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: prefetch-src - HTTP
The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: script-src-attr - HTTP
The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: script-src-elem - HTTP
The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: script-src - HTTP
The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: style-src-attr - HTTP
The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: style-src-elem - HTTP
The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: style-src - HTTP
The single quotes are required. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' An allow-list for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
CSP: worker-src - HTTP
u must include the single quotes. 'none' Refers to the empty set; that is, no URLs match. The single quotes are required. 'nonce-<base64-value>' A whitelist for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource's policy is
otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' A sha256, sha384 or sha512 hash of scripts or styles. The use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the bas...
Content-Security-Policy-Report-Only - HTTP
Response header Forbidden header name no This header is not supported inside a <meta> element. Syntax Content-Security-Policy-Report-Only: <policy-directive>; <policy-directive> Directives The directives of the Content-Security-Policy header can also be applied to Content-Security-Policy-Report-Only. The CSP report-uri directive should be used with this header,
otherwise this header will be an expensive no-op machine. Examples This header reports violations that would have occurred. You can use this to iteratively work on your content security policy. You observe how your site behaves, watching for violation reports, or malware redirects, then choose the desired policy enforced by the Content-Security-Policy header. Content-Security-Policy-Report-Only: default...
Expect - HTTP
indicates expectations that need to be fulfilled by the server in order to properly handle the request. The only expectation defined in the specification is Expect: 100-continue, to which the server shall respond with: 100 if the information contained in the header is sufficient to cause an immediate success, 417 (Expectation Failed) if it cannot meet the expectation; or any other 4xx status
otherwise. For example, the server may reject a request if its Content-Length is too large. No common browsers send the Expect header, but some other clients such as cURL do so by default. Header type Request header Forbidden header name yes Syntax No other expectations except "100-continue" are specified currently. Expect: 100-continue Directives 100-continue Inf...
Index - HTTP
er encodings the user agent is willing to accept. (you could informally call it Accept-Transfer-Encoding, which would be more intuitive). 105 Timing-Allow-Origin CORS, HTTP, Reference, Timing-Allow-Origin, header The Timing-Allow-Origin response header specifies origins that are allowed to see values of attributes retrieved via features of the Resource Timing API, which would
otherwise be reported as zero due to cross-origin restrictions. 106 Tk DNT, HTTP, Reference, Response, header, tracking The Tk response header indicates the tracking status that applied to the corresponding request. 107 Trailer HTTP, Reference, header The Trailer response header allows the sender to include additional fields at the end of chunked messages in order ...
Public-Key-Pins-Report-Only - HTTP
e> This directive is meaningless for the Public-Key-Pins-Report-Only header, it will be ignored by user agents and the header will not be cached. includeSubDomains Optional If this optional parameter is specified, this rule applies to all of the site's subdomains as well. report-uri="<uri>" Pin validation failures are reported to the given URL. This directive should be used with this header,
otherwise this header will be a no-op. Example Public-Key-Pins-Report-Only: pin-sha256="cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs="; pin-sha256="M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE="; includeSubDomains; report-uri="https://www.example.org/hpkp-report" In this example, pin-sha256="cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs=" pins the server's public key used in production. The second ...
Timing-Allow-Origin - HTTP
Header type Response header Forbidden header name no Syntax Timing-Allow-Origin: * Timing-Allow-Origin: <origin>[, <origin>]* Directives * The server may specify "*" as a wildcard, thereby allowing any origin to see timing resources. <origin> Specifies a URI that may see the timing resources. You can specify multiple origins, separated by commas. ...
HTTP Index - HTTP
er encodings the user agent is willing to accept. (you could informally call it Accept-Transfer-Encoding, which would be more intuitive). 186 Timing-Allow-Origin CORS, HTTP, Reference, Timing-Allow-Origin, header The Timing-Allow-Origin response header specifies origins that are allowed to see values of attributes retrieved via features of the Resource Timing API, which would
otherwise be reported as zero due to cross-origin restrictions. 187 Tk DNT, HTTP, Reference, Response, header, tracking The Tk response header indicates the tracking status that applied to the corresponding request. 188 Trailer HTTP, Reference, header The Trailer response header allows the sender to include additional fields at the end of chunked messages in order ...
Proxy Auto-Configuration (PAC) file - HTTP
gs: "SUN"|"MON"|"TUE"|"WED"|"THU"|"FRI"|"SAT" gmt Is either the string "GMT" or is left out. Only the first parameter is mandatory. Either the second, the third, or both may be left out. If only one parameter is present, the function returns a value of true on the weekday that the parameter represents. If the string "GMT" is specified as a second parameter, times are taken to be in GMT.
Otherwise, they are assumed to be in the local timezone. If both wd1 and wd1 are defined, the condition is true if the current weekday is in between those two ordered weekdays. Bounds are inclusive, but the bounds are ordered. If the "GMT" parameter is specified, times are taken to be in GMT.
Otherwise, the local timezone is used. The order of the days matters; Before Firefox 49, weekdayRange("SUN", "SA...
501 Not Implemented - HTTP
uired to support (and therefore that must not return 501) are GET and HEAD. If the server does recognize the method, but intentionally does not support it, the appropriate response is 405 Method Not Allowed. A 501 error is not something you can fix, but requires a fix by the web server you are trying to access. A 501 response is cacheable by default; that is, unless caching headers instruct
otherwise. Status 501 Not Implemented Specifications Specification Title RFC 7231, section 6.6.2: 501 Not Implemented Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
A re-introduction to JavaScript (JS tutorial) - JavaScript
ent that it was created with. What's happening here is pretty much the same as was happening with the inner functions earlier on: a function defined inside another function has access to the outer function's variables. The only difference here is that the outer function has returned, and hence common sense would seem to dictate that its local variables no longer exist. But they do still exist --
otherwise, the adder functions would be unable to work. What's more, there are two different "copies" of makeAdder()'s local variables -- one in which a is 5 and the other one where a is 20. So the result of that function calls is as follows: add5(6); // returns 11 add20(7); // returns 27 Here's what's actually happening. Whenever JavaScript executes a function, a 'scope' object is created to hold the l...
About JavaScript - JavaScript
C++ to reduce the number of new concepts required to learn the language. Language constructs, such as if statements, for and while loops, and switch and try ... catch blocks function the same as in these languages (or nearly so). JavaScript can function as both a procedural and an object oriented language. Objects are created programmatically in JavaScript, by attaching methods and properties to
otherwise empty objects at run time, as opposed to the syntactic class definitions common in compiled languages like C++ and Java. Once an object has been constructed it can be used as a blueprint (or prototype) for creating similar objects. JavaScript's dynamic capabilities include runtime object construction, variable parameter lists, function variables, dynamic script creation (via eval), object intros...
Details of the object model - JavaScript
blic Engineer () { dept = "engineering"; machine = ""; } public Engineer (String mach) { dept = "engineering"; machine = mach; } } These JavaScript definitions use a special idiom for setting default values: this.name = name || ''; The JavaScript logical OR operator (||) evaluates its first argument. If that argument converts to true, the operator returns it.
Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see if name has a useful value for the name property. If it does, it sets this.name to that value.
Otherwise, it sets this.name to the empty string. This chapter uses this idiom for brevity; however, it can be puzzling at first glance. Note: This may not work as expected if the constructor function is ...
Indexed collections - JavaScript
rally preferred. See Array literals for details. To create an array with non-zero length, but without any items, either of the following can be used: // This... let arr = new Array(arrayLength) // ...results in the same array as this let arr = Array(arrayLength) // This has exactly the same effect let arr = [] arr.length = arrayLength Note: In the above code, arrayLength must be a Number.
Otherwise, an array with a single element (the provided value) will be created. Calling arr.length will return arrayLength, but the array doesn't contain any elements. A for...in loop will not find any property on the array. In addition to a newly defined variable as shown above, arrays can also be assigned as a property of a new or an existing object: let obj = {} // ... obj.prop = [element0, element1,...
Loops and iteration - JavaScript
increments n and adds that value to x. Therefore, x and n take on the following values: After the first pass: n = 1 and x = 1 After the second pass: n = 2 and x = 3 After the third pass: n = 3 and x = 6 After completing the third pass, the condition n < 3 is no longer true, so the loop terminates. Example 2 Avoid infinite loops. Make sure the condition in a loop eventually becomes false--
otherwise, the loop will never terminate! The statements in the following while loop execute forever because the condition never becomes false: // Infinite loops are bad! while (true) { console.log('Hello, world!'); } labeled statement A label provides a statement with an identifier that lets you refer to it elsewhere in your program. For example, you can use a label to identify a loop, and then use t...
Meta programming - JavaScript
Because Reflect.defineProperty returns a Boolean success status, you can just use an if...else block here: if (Reflect.defineProperty(target, property, attributes)) { // success } else { // failure } << PreviousNext >> ...
JavaScript modules - JavaScript
prepended to it, e.g. Module.Square( ... ). Troubleshooting Here are a few tips that may help you if you are having trouble getting your modules to work. Feel free to add to the list if you discover more! We mentioned this before, but to reiterate: .js files need to be loaded with a MIME-type of text/javascript (or another JavaScript-compatible MIME-type, but text/javascript is recommended),
otherwise you'll get a strict MIME type checking error like "The server responded with a non-JavaScript MIME type". If you try to load the HTML file locally (i.e. with a file:// URL), you'll run into CORS errors due to JavaScript module security requirements. You need to do your testing through a server. GitHub pages is ideal as it also serves .js files with the correct MIME type. Because .mjs is a non-s...
Regular expressions - JavaScript
l characters literally (actually searching for a "*", for instance), you must escape it by putting a backslash in front of it. For instance, to search for "a" followed by "*" followed by "b", you'd use /a\*b/ -- the backslash "escapes" the "*", making it literal instead of special. Similarly, if you're writing a regular expression literal and need to match a slash ("/"), you need to escape that (
otherwise, it terminates the pattern). For instance, to search for the string "/example/" followed by one or more alphabetic characters, you'd use /\/example\/[a-z]+/i--the backslashes before each slash make them literal. To match a literal backslash, you need to escape the backslash. For instance, to match the string "C:\" where "C" can be any letter, you'd use /[A-Z]:\\/ -- the first backslash escapes t...
Using Promises - JavaScript
guments to then are optional, and catch(failureCallback) is short for then(null, failureCallback). You might see this expressed with arrow functions instead: doSomething() .then(result => doSomethingElse(result)) .then(newResult => doThirdThing(newResult)) .then(finalResult => { console.log(`Got the final result: ${finalResult}`); }) .catch(failureCallback); Important: Always return results,
otherwise callbacks won't catch the result of a previous promise (with arrow functions () => x is short for () => { return x; }). Chaining after a catch It's possible to chain after a failure, i.e. a catch, which is useful to accomplish new actions even after an action failed in the chain. Read the following example: new Promise((resolve, reject) => { console.log('Initial'); resolve(); }) .then...
Working with objects - JavaScript
number o.b -- a getter that returns o.a plus 1 o.c -- a setter that sets the value of o.a to half of the value o.c is being set to Please note that function names of getters and setters defined in an object literal using "[gs]et property()" (as opposed to __define[GS]etter__ ) are not the names of the getters themselves, even though the [gs]et propertyName(){ } syntax may mislead you to think
otherwise. Getters and setters can also be added to an object at any time after creation using the Object.defineProperties method. This method's first parameter is the object on which you want to define the getter or setter. The second parameter is an object whose property names are the getter or setter names, and whose property values are objects for defining the getter or setter functions. Here's an exa...
Inheritance and the prototype chain - JavaScript
s a property of doSomeInstancing, the browser first looks to see if doSomeInstancing has that property. If doSomeInstancing does not have the property, then the browser looks for the property in the __proto__ of doSomeInstancing (a.k.a. doSomething.prototype). If the __proto__ of doSomeInstancing has the property being looked for, then that property on the __proto__ of doSomeInstancing is used.
Otherwise, if the __proto__ of doSomeInstancing does not have the property, then the __proto__ of the __proto__ of doSomeInstancing is checked for the property. By default, the __proto__ of any function's prototype property is window.Object.prototype. So, the __proto__ of the __proto__ of doSomeInstancing (a.k.a. the __proto__ of doSomething.prototype (a.k.a. Object.prototype)) is then looked through for t...
RangeError: invalid array length - JavaScript
ual to 232. Why are Array and ArrayBuffer length limited? The length property of an Array or an ArrayBuffer is represented with an unsigned 32-bit integer, that can only store values which are in the range from 0 to 232-1. If you are creating an Array, using the constructor, you probably want to use the literal notation instead, as the first argument is interpreted as the length of the Array.
Otherwise, you might want to clamp the length before setting the length property, or using it as argument of the constructor. Examples Invalid cases new Array(Math.pow(2, 40)) new Array(-1) new ArrayBuffer(Math.pow(2, 32)) new ArrayBuffer(-1) let a = []; a.length = a.length - 1; // set -1 to the length property let b = new Array(Math.pow(2, 32) - 1); b.length = b.length + 1; // set 2^3...
SyntaxError: missing : after property id - JavaScript
obj = { }; obj['propertyKey'] = 'value'; Empty properties You can't create empty properties like this: var obj = { propertyKey; }; // SyntaxError: missing : after property id If you need to define a property without a value, you might use null as a value. var obj = { propertyKey: null }; Computed properties If you create a property key from an expression, you need to use square brackets.
Otherwise the property name can't be computed: var obj = { 'b'+'ar': 'foo' }; // SyntaxError: missing : after property id Put the expression in brackets []: var obj = { ['b'+'ar']: 'foo' }; ...
Functions - JavaScript
r result; result = padZeros(42,4); // returns "0042" result = padZeros(42,2); // returns "42" result = padZeros(5,4); // returns "0005" Determining whether a function exists You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used;
otherwise, some other action is taken. if ('function' === typeof window.noFunc) { // use noFunc() } else { // do something else } Note that in the if test, a reference to noFunc is used--there are no brackets "()" after the function name so the actual function is not called. Specifications Specification ECMAScript (ECMA-262)The definition of 'Function definitions' in that sp...
Array.prototype.reduce() - JavaScript
lator The accumulator accumulates callback's return values. It is the accumulated value previously returned in the last invocation of the callback--or initialValue, if it was supplied (see below). currentValue The current element being processed in the array. index Optional The index of the current element being processed in the array. Starts from index 0 if an initialValue is provided.
Otherwise, it starts from index 1. array Optional The array reduce() was called upon. initialValue Optional A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used as the initial accumulator value and skipped as currentValue. Calling reduce() on an empty array without an initialValue will throw a TypeError...
Array.prototype.find() - JavaScript
cute on each value in the array, taking 3 arguments: element The current element in the array. index Optional The index (position) of the current element in the array. array Optional The array that find was called on. thisArg Optional Object to use as this inside callback. Return value The value of the first element in the array that satisfies the provided testing function.
Otherwise, undefined is returned. Description The find method executes the callback function once for each index of the array until the callback returns a truthy value. If so, find immediately returns the value of that element.
Otherwise, find returns undefined. callback is invoked for every index of the array, not just those with assigned values. This means it may be less efficient for sparse arrays, c...
Array.isArray() - JavaScript
The Array.isArray() method determines whether the passed value is an Array. Array.isArray([1, 2, 3]); // true Array.isArray({foo: 123}); // false Array.isArray('foobar'); // false Array.isArray(undefined); // false Syntax Array.isArray(value) Parameters value The value to be checked. Return value true if the value is an Array;
otherwise, false. Description If the value is an Array, true is returned;
otherwise, false is. See the article "Determining with absolute accuracy whether or not a JavaScript object is an array" for more details. Given a TypedArray instance, false is always returned. Polyfill Running the following code before any other code will create Array.isArray() if it's not natively available. if (!Array.isArray) { Array.isArray = function(arg) { return Ob...
Array.prototype.map() - JavaScript
ttern; use forEach or for-of instead. You shouldn't be using map if: you're not using the array it returns; and/or you're not returning a value from the callback. Parameters in Detail callback is invoked with three arguments: the value of the element, the index of the element, and the array object being mapped. If a thisArg parameter is provided, it will be used as callback's this value.
Otherwise, the value undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. map does not mutate the array on which it is called (although callback, if invoked, may do so). The range of elements processed by map is set before the first invocation of callback. Elements which are appen...
Array - JavaScript
parenthesized substrings is unlimited. [1]: "bB" [2]: "d" Constructor Array() Creates a new Array object. Static properties get Array[@@species] The constructor function is used to create derived objects. Static methods Array.from() Creates a new Array instance from an array-like or iterable object. Array.isArray() Returns true if the argument is an array, or false
otherwise. Array.of() Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments. Instance properties Array.prototype.length Reflects the number of elements in an array. Array.prototype[@@unscopables] A symbol containing property names to exclude from a with binding scope. Instance methods Array.prototype.concat() Returns a new array that...
ArrayBuffer.isView() - JavaScript
or a DataView. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax ArrayBuffer.isView(value) Parameters value The value to be checked. Return value true if the given argument is one of the ArrayBuffer views;
otherwise, false. Examples Using isView ArrayBuffer.isView(); // false ArrayBuffer.isView([]); // false ArrayBuffer.isView({}); // false ArrayBuffer.isView(null); // false ArrayBuffer.isView(undefined); // false ArrayBuffer.isView(new ArrayBuffer(10)); // false ArrayBuffer.isView(new Uint8Array()); // true ArrayBuffer.isVi...
ArrayBuffer - JavaScript
ng data, for example from a Base64 string or from a local file. Constructor ArrayBuffer() Creates a new ArrayBuffer object. Static properties get ArrayBuffer[@@species] The constructor function that is used to create derived objects. Static methods ArrayBuffer.isView(arg) Returns true if arg is one of the ArrayBuffer views, such as typed array objects or a DataView. Returns false
otherwise. Instance properties ArrayBuffer.prototype.byteLength The read-only size, in bytes, of the ArrayBuffer. This is established when the array is constructed and cannot be changed. Instance methods ArrayBuffer.prototype.slice() Returns a new ArrayBuffer whose contents are a copy of this ArrayBuffer's bytes from begin (inclusive) up to end (exclusive). If either begin or end is negative, i...
Date.prototype.setYear() - JavaScript
years ("year 2000 problem"), it is no longer used and has been replaced by the setFullYear() method. Syntax dateObj.setYear(yearValue) Parameters yearValue An integer. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. Description If yearValue is a number between 0 and 99 (inclusive), then the year for dateObj is set to 1900 + yearValue.
Otherwise, the year for dateObj is set to yearValue. Examples Using setYear() The first two lines set the year to 1996. The third sets the year to 2000. var theBigDay = new Date(); theBigDay.setYear(96); theBigDay.setYear(1996); theBigDay.setYear(2000); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.setYear' in that specification. ...
Error - JavaScript
use instanceof MyError to check the kind of error in the exception handler. This results in cleaner and more consistent error handling code. See "What's a good way to extend Error in JavaScript?" on StackOverflow for an in-depth discussion. ES6 Custom Error Class Versions of Babel prior to 7 can handle CustomError class methods, but only when they are declared with Object.defineProperty().
Otherwise, old versions of Babel and other transpilers will not correctly handle the following code without additional configuration. Some browsers include the CustomError constructor in the stack trace when using ES2015 classes. class CustomError extends Error { constructor(foo = 'bar', ...params) { // Pass remaining arguments (including vendor specific ones) to parent constructor super(...
FinalizationRegistry - JavaScript
ms across versions. Complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs. Notes on cleanup callbacks Some notes on cleanup callbacks: Developers shouldn't rely on cleanup callbacks for essential program logic. Cleanup callbacks may be useful for reducing memory usage across the course of a program, but are unlikely to be useful
otherwise. A conforming JavaScript implementation, even one that does garbage collection, is not required to call cleanup callbacks. When and whether it does so is entirely down to the implementation of the JavaScript engine. When a registered object is reclaimed, any cleanup callbacks for it may be called then, or some time later, or not at all. It's likely that major implementations will call cleanup c...
Function.prototype.apply() - JavaScript
rns a new array. But you wanted to append to the existing array... So what now? Write a loop? Surely not? apply to the rescue! const array = ['a', 'b']; const elements = [0, 1, 2]; array.push.apply(array, elements); console.info(array); // ["a", "b", 0, 1, 2] Using apply and built-in functions Clever usage of apply allows you to use built-in functions for some tasks that would probably have
otherwise been written by looping over the array values. As an example, here are Math.max/Math.min, used to find out the maximum/minimum value in an array. // min/max number in an array const numbers = [5, 6, 2, 3, 7]; // using Math.min/Math.max apply let max = Math.max.apply(null, numbers); // This about equal to Math.max(numbers[0], ...) // or Math.max(5, 6, ...) let min = Math.min.apply(null, number...
Function.caller - JavaScript
It's also null for strict, async function and generator function callers. This property replaces the obsolete arguments.caller property of the arguments object. ...
JSON.parse() - JavaScript
to the original value itself) are individually run through the reviver. Then it is called, with the object containing the property being processed as this, and with the property name as a string, and the property value as arguments. If the reviver function returns undefined (or returns no value, for example, if execution falls off the end of the function), the property is deleted from the object.
Otherwise, the property is redefined to be the return value. If the reviver only transforms some values and not others, be certain to return all untransformed values as-is,
otherwise, they will be deleted from the resulting object. JSON.parse('{"p": 5}', (key, value) => typeof value === 'number' ? value * 2 // return value * 2 for numbers : value // return everything else unchanged ); // {...
Map.prototype.forEach() - JavaScript
the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value undefined. callback is invoked with three arguments: the entry's value the entry's key the Map object being traversed If a thisArg parameter is provided to forEach, it will be passed to callback when invoked, for use as its this value.
Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. Each value is visited once, except in the case when it was deleted and re-added before forEach has finished. callback is not invoked for values deleted before being visited. New values added before...
Map.prototype.has() - JavaScript
this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax myMap.has(key) Parameters key The key of the element to test for presence in the Map object. Return value true if an element with the specified key exists in the Map object;
otherwise false. Examples Using has() let myMap = new Map() myMap.set('bar', "foo") myMap.has('bar') // returns true myMap.has('baz') // returns false Specifications Specification ECMAScript (ECMA-262)The definition of 'Map.prototype.has' in that specification. ...
Math.acos() - JavaScript
interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.acos(x) Parameters x A number representing a cosine, where x is between -1 and 1. Return value The arccosine (angle in radians) of the given number if it's between -1 and 1;
otherwise, NaN. Description The Math.acos() method returns a numeric value between 0 and ? radians for x between -1 and 1. If the value of x is outside this range, it returns NaN. Because acos() is a static method of Math, you always use it as Math.acos(), rather than as a method of a Math object you created (Math is not a constructor). Examples Using Math.acos() Math.acos(-2); // NaN Math.acos(-1);...
Math.asin() - JavaScript
\, \text{such that} \; \sin(y) = x The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.asin(x) Parameters x A number. Return value The arcsine (in radians) of the given number if it's between -1 and 1;
otherwise, NaN. Description The Math.asin() method returns a numeric value between -?2-\frac{\pi}{2} and ?2\frac{\pi}{2} radians for x between -1 and 1. If the value of x is outside this range, it returns NaN. Because asin() is a static method of Math, you always use it as Math.asin(), rather than as a method of a Math object you created (Math is not a constructor). Examples Using Math.asin() Math.as...
Math.sign() - JavaScript
les and send us a pull request. Syntax Math.sign(x) Parameters x A number. If this argument is not a number, it is implicitly converted to one. Return value A number representing the sign of the given argument: If the argument is positive, returns 1. If the argument is negative, returns -1. If the argument is positive zero, returns 0. If the argument is negative zero, returns -0.
Otherwise, NaN is returned. Description Because sign() is a static method of Math, you always use it as Math.sign(), rather than as a method of a Math object you created (Math is not a constructor). Polyfill if (!Math.sign) { Math.sign = function(x) { // If x is NaN, the result is NaN. // If x is -0, the result is -0. // If x is +0, the result is +0. // If x is negative and not -0, ...
Number.MAX_VALUE - JavaScript
approximately 1.79E+308, or 21024. Values larger than MAX_VALUE are represented as Infinity. Because MAX_VALUE is a static property of Number, you always use it as Number.MAX_VALUE, rather than as a property of a Number object you created. Examples Using MAX_VALUE The following code multiplies two numeric values. If the result is less than or equal to MAX_VALUE, the func1 function is called;
otherwise, the func2 function is called. if (num1 * num2 <= Number.MAX_VALUE) { func1(); } else { func2(); } Specifications Specification ECMAScript (ECMA-262)The definition of 'Number.MAX_VALUE' in that specification. ...
Number.MIN_VALUE - JavaScript
approximately 5e-324. Values smaller than MIN_VALUE ("underflow values") are converted to 0. Because MIN_VALUE is a static property of Number, you always use it as Number.MIN_VALUE, rather than as a property of a Number object you created. Examples Using MIN_VALUE The following code divides two numeric values. If the result is greater than or equal to MIN_VALUE, the func1 function is called;
otherwise, the func2 function is called. if (num1 / num2 >= Number.MIN_VALUE) { func1(); } else { func2(); } Specifications Specification ECMAScript (ECMA-262)The definition of 'Number.MIN_VALUE' in that specification. ...
Number.isInteger() - JavaScript
ory. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Number.isInteger(value) Parameters value The value to be tested for being an integer. Return value A Boolean indicating whether or not the given value is an integer. Description If the target value is an integer, return true,
otherwise return false. If the value is NaN or Infinity, return false. The method will also return true for floating point numbers that can be represented as integer. Polyfill Number.isInteger = Number.isInteger || function(value) { return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; }; Examples Using isInteger Number.isInteger(0); // true Number.isI...
Number.isNaN() - JavaScript
l, global isNaN(). The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Number.isNaN(value) Parameters value The value to be tested for NaN. Return value true if the given value is NaN and its type is Number;
otherwise, false. Description Due to both equality operators, == and ===, evaluating to false when checking if NaN is NaN, the function Number.isNaN() has become necessary. This situation is unlike all other possible value comparisons in JavaScript. In comparison to the global isNaN() function, Number.isNaN() doesn't suffer the problem of forcefully converting the parameter to a number. This means it is...
Object() constructor - JavaScript
If the value is an object already, it will return the value. When called in a non-constructor context, Object behaves identically to new Object(). Syntax new Object() new Object(value) Parameters value Any value. ...
Object.freeze() - JavaScript
fails silently in non-strict mode employee.address.city = "Noida"; // attributes of child object can be modified console.log(employee.address.city) // Output: "Noida" To make an object immutable, recursively freeze each property which is of type object (deep freeze). Use the pattern on a case-by-case basis based on your design when you know the object contains no cycles in the reference graph,
otherwise an endless loop will be triggered. An enhancement to deepFreeze() would be to have an internal function that receives a path (e.g. an Array) argument so you can suppress calling deepFreeze() recursively when an object is in the process of being made immutable. You still run a risk of freezing an object that shouldn't be frozen, such as [window]. function deepFreeze(object) { // Retrieve the p...
Object.getOwnPropertyDescriptor() - JavaScript
examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Object.getOwnPropertyDescriptor(obj, prop) Parameters obj The object in which to look for the property. prop The name or Symbol of the property whose description is to be retrieved. Return value A property descriptor of the given property if it exists on the object, undefined
otherwise. Description This method permits examination of the precise description of a property. A property in JavaScript consists of either a string-valued name or a Symbol and a property descriptor. Further information about property descriptor types and their attributes can be found in Object.defineProperty(). A property descriptor is a record with some of the following attributes: value The valu...
Object.isSealed() - JavaScript
stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Object.isSealed(obj) Parameters obj The object which should be checked. Return value A Boolean indicating whether or not the given object is sealed. Description Returns true if the object is sealed,
otherwise false. An object is sealed if it is not extensible and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). Examples Using Object.isSealed // Objects aren't sealed by default. var empty = {}; Object.isSealed(empty); // === false // If you make an empty object non-extensible, // it is vacuously sealed. Object.preventExtensions(empty); Objec...
Object.setPrototypeOf() - JavaScript
bject which is to have its prototype set. prototype The object's new prototype (an object or null). Return value The specified object. Description Throws a TypeError exception if the object whose [[Prototype]] is to be modified is non-extensible according to Object.isExtensible(). Does nothing if the prototype parameter isn't an object or null (i.e., number, string, boolean, or undefined).
Otherwise, this method changes the [[Prototype]] of obj to the new value. Object.setPrototypeOf() is in the ECMAScript 2015 specification. It is generally considered the proper way to set the prototype of an object, vs. the more controversial Object.prototype.__proto__ property. Appending Prototype Chains A combination of Object.getPrototypeOf() and Object.prototype.__proto__ permits appending a whole p...
Object - JavaScript
through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. This provides a very powerful although potentially dangerous mechanism to override or extend object behavior. The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object.
Otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value. When called in a non-constructor context, Object behaves identically to new Object(). See also the object initializer / literal syntax. Deleting a property from an object There isn't any method in an Object itself to delete its own properties (such as Map.pro...
Promise.resolve() - JavaScript
This function flattens nested layers of promise-like objects (e.g. a promise that resolves to a promise that resolves to something) into a single layer. ...
Promise - JavaScript
ejects, it is rejected with the reason from the first promise that was rejected. Promise.reject(reason) Returns a new Promise object that is rejected with the given reason. Promise.resolve(value) Returns a new Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state;
otherwise the returned promise will be fulfilled with the value. Generally, if you don't know if a value is a promise or not, Promise.resolve(value) it instead and work with the return value as a promise. Instance methods Promise.prototype.catch() Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its or...
handler.setPrototypeOf() - JavaScript
l request. Syntax const p = new Proxy(target, { setPrototypeOf: function(target, prototype) { } }); Parameters The following parameters are passed to the setPrototypeOf() method. this is bound to the handler. target The target object. prototype The object's new prototype or null. Return value The setPrototypeOf() method returns true if the [[Prototype]] was successfully changed,
otherwise false. Description The handler.setPrototypeOf() method is a trap for Object.setPrototypeOf(). Interceptions This trap can intercept these operations: Object.setPrototypeOf() Reflect.setPrototypeOf() Invariants If the following invariants are violated, the proxy will throw a TypeError: If target is not extensible, the prototype parameter must be the same value as Object.getPrototypeO...
Reflect.defineProperty() - JavaScript
er, simply returns a Boolean indicating whether or not the property was successfully defined. Examples Using Reflect.defineProperty() let obj = {} Reflect.defineProperty(obj, 'x', {value: 7}) // true obj.x // 7 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 defining a property. ] Because Reflect.defineProperty returns a Boolean success status, you can just use an if...else block here: if (Reflect.defineProperty(target, property, attributes)) { // success } else { // failure } Specifications Specification ECMAScript (ECMA-262)The definition of 'Reflect...
Reflect - JavaScript
ent to calling delete target[propertyKey]. Reflect.get(target, propertyKey[, receiver]) Returns the value of the property. Works like getting a property from an object (target[propertyKey]) as a function. Reflect.getOwnPropertyDescriptor(target, propertyKey) Similar to Object.getOwnPropertyDescriptor(). Returns a property descriptor of the given property if it exists on the object, undefined
otherwise. Reflect.getPrototypeOf(target) Same as Object.getPrototypeOf(). Reflect.has(target, propertyKey) Returns a Boolean indicating whether the target has the property. Either as own or inherited. Works like the in operator as a function. Reflect.isExtensible(target) Same as Object.isExtensible(). Returns a Boolean that is true if the target is extensible. Reflect.ownKeys(target) Returns an ar...
RegExp.prototype[@@search]() - JavaScript
Hub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax regexp[Symbol.search](str) Parameters str A String that is a target of the search. Return value integer If successful, [@@search]() returns the index of the first match of the regular expression inside the string.
Otherwise, it returns -1. Description This method is called internally in String.prototype.search(). For example, the following two examples return the same result. 'abc'.search(/a/); /a/[Symbol.search]('abc'); This method exists for customizing the search behavior in RegExp subclasses. Examples Direct call This method can be used in almost the same way as String.prototype.search(), except the dif...
RegExp.prototype.global - JavaScript
ntribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Property attributes of RegExp.prototype.global Writable no Enumerable no Configurable yes Description The value of global is a Boolean and true if the "g" flag was used;
otherwise, false. The "g" flag indicates that the regular expression should be tested against all possible matches in a string. A regular expression defined as both global ("g") and sticky ("y") will ignore the global flag and perform sticky matches. You cannot change this property directly. Examples Using global var regex = new RegExp('foo', 'g'); console.log(regex.global); // true var str = 'fooex...
RegExp.prototype.ignoreCase - JavaScript
to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Property attributes of RegExp.prototype.ignoreCase Writable no Enumerable no Configurable yes Description The value of ignoreCase is a Boolean and true if the "i" flag was used;
otherwise, false. The "i" flag indicates that case should be ignored while attempting a match in a string. You cannot change this property directly. Examples Using ignoreCase var regex = new RegExp('foo', 'i'); console.log(regex.ignoreCase); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.prototype.ignoreCase' in that specification. ...
RegExpInstance.lastIndex - JavaScript
lastIndex is set to 0. If lastIndex is equal to or less than the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting from lastIndex. If lastIndex is equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, and lastIndex is reset to 0.
Otherwise, lastIndex is set to the next position following the most recent match. Examples Using lastIndex Consider the following sequence of statements: var re = /(hi)?/g; Matches the empty string. console.log(re.exec('hi')); console.log(re.lastIndex); Returns ["hi", "hi"] with lastIndex equal to 2. console.log(re.exec('hi')); console.log(re.lastIndex); Returns ["", undefined], an empty array...
RegExp.prototype.multiline - JavaScript
to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Property attributes of RegExp.prototype.multiline Writable no Enumerable no Configurable yes Description The value of multiline is a Boolean and is true if the "m" flag was used;
otherwise, false. The "m" flag indicates that a multiline input string should be treated as multiple lines. For example, if "m" is used, "^" and "$" change from matching at only the start or end of the entire string to the start or end of any line within the string. You cannot change this property directly. Examples Using multiline var regex = new RegExp('foo', 'm'); console.log(regex.multiline); // t...
RegExp.$1-$9 - JavaScript
the test() method of the RegExp instance to grab a number in a generic string. var str = 'Test 24'; var number = /(\d+)/.test(str) ? RegExp.$1 : '0'; number; // "24" Please note that any operation involving the usage of other regular expressions between a re.test(str) call and the RegExp.$n property, might have side effects, so that accessing these special properties should be done instantly,
otherwise the result might be unexpected. Specifications Specification Legacy RegExp features in JavaScript ...
RegExp.prototype.sticky - JavaScript
ntribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Property attributes of RegExp.prototype.sticky Writable no Enumerable no Configurable yes Description The value of sticky is a Boolean and true if the "y" flag was used;
otherwise, false. The "y" flag indicates that it matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes). A regular expression defined as both sticky and global ignores the global flag. You cannot change this property directly. It is read-only. Examples Using a regular expression with the stick...
RegExp.prototype.test() - JavaScript
is interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax regexObj.test(str) Parameters str The string against which to match the regular expression. Returns true if there is a match between the regular expression and the string str.
Otherwise, false. Description Use test() whenever you want to know whether a pattern is found in a string. test() returns a boolean, unlike the String.prototype.search() method (which returns the index of a match, or -1 if not found). To get more information (but with slower execution), use the exec() method. (This is similar to the String.prototype.match() method.) As with exec() (or in combination wi...
RegExp.prototype.unicode - JavaScript
ribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Property attributes of RegExp.prototype.unicode Writable no Enumerable no Configurable yes Description The value of unicode is a Boolean and true if the "u" flag was used;
otherwise false. The "u" flag enables various Unicode-related features. With the "u" flag, any Unicode code point escapes will be interpreted as such, for example. You cannot change this property directly. It is read-only. Examples Using the unicode property var regex = new RegExp('\u{61}', 'u'); console.log(regex.unicode); // true Specifications Specification ECMAScript (ECMA-262...
Set.prototype.delete() - JavaScript
a Set object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax mySet.delete(value); Parameters value The value to remove from mySet. Return value Returns true if value was successfully removed from mySet;
otherwise false. Examples Using the delete() method const mySet = new Set(); mySet.add('foo'); mySet.delete('bar'); // Returns false. No "bar" element found to be deleted. mySet.delete('foo'); // Returns true. Successfully removed. mySet.has('foo'); // Returns false. The "foo" element is no longer present. Let's checkout below how to delete an Object from a Set. const setObj = new Set(); // C...
Set.prototype.forEach() - JavaScript
th three arguments: the element value the element key the Set object being traversed There are no keys in Set objects, however, so the first two arguments are both values contained in the Set. This is to make it consistent with other forEach() methods for Map and Array. If a thisArg parameter is provided to forEach(), it will be passed to callback when invoked, for use as its this value.
Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. Each value is visited once, except in the case when it was deleted and re-added before forEach() has finished. callback is not invoked for values deleted before being visited. New values added befo...
Set.prototype.has() - JavaScript
is interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax mySet.has(value); Parameters value The value to test for presence in the Set object. Return value Returns true if an element with the specified value exists in the Set object;
otherwise false. Note: Technically speaking, has() uses the sameValueZero algorithm to determine whether the given element is found. Examples Using the has method var mySet = new Set(); mySet.add('foo'); mySet.has('foo'); // returns true mySet.has('bar'); // returns false var set1 = new Set(); var obj1 = {'key1': 1}; set1.add(obj1); set1.has(obj1); // returns true set1.has({'key1': 1}); /...
String.prototype.endsWith() - JavaScript
examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.endsWith(searchString[, length]) Parameters searchString The characters to be searched for at the end of str. length Optional If provided, it is used as the length of str. Defaults to str.length. Return value true if the given characters are found at the end of the string;
otherwise, false. Description This method lets you determine whether or not a string ends with another string. This method is case-sensitive. Polyfill This method has been added to the ECMAScript 6 specification and may not be available in all JavaScript implementations yet. However, you can polyfill String.prototype.endsWith() with the following snippet: if (!String.prototype.endsWith) { String.pro...
String.prototype.includes() - JavaScript
lease clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.includes(searchString[, position]) Parameters searchString A string to be searched for within str. position Optional The position within the string at which to begin searching for searchString. (Defaults to 0.) Return value true if the search string is found anywhere within the given string;
otherwise, false if not. Description This method lets you determine whether or not a string includes another string. Case-sensitivity The includes() method is case sensitive. For example, the following expression returns false: 'Blue Whale'.includes('blue') // returns false Polyfill This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implement...
String.prototype.matchAll() - JavaScript
itHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.matchAll(regexp) Parameters regexp A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). The RegExp object must have the /g flag,
otherwise a TypeError will be thrown. Return value An iterator (which is not a restartable iterable). Examples Regexp.exec() and matchAll() Prior to the addition of matchAll to JavaScript, it was possible to use calls to regexp.exec (and regexes with the /g flag) in a loop to obtain all the matches: const regexp = RegExp('foo[a-z]*','g'); const str = 'table football, foosball'; let match; while (...
String.prototype.replaceAll() - JavaScript
nal string is left unchanged. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax const newStr = str.replaceAll(regexp|substr, newSubstr|function) when using a `regexp` you must have to set the global ("g") flag;
otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp". Parameters regexp (pattern) A RegExp object or literal with the global flag. The matches are replaced with newSubstr or the value returned by the specified function. A RegExp without the global ("g") flag will throw a TypeError: "replaceAll must be called with a global RegExp". substr A String that is to be repl...
String.prototype.startsWith() - JavaScript
thub.com/mdn/interactive-examples and send us a pull request. Syntax str.startsWith(searchString[, position]) Parameters searchString The characters to be searched for at the start of this string. position Optional The position in this string at which to begin searching for searchString. Defaults to 0. Return value true if the given characters are found at the beginning of the string;
otherwise, false. Description This method lets you determine whether or not a string begins with another string. This method is case-sensitive. Polyfill This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can polyfill String.prototype.startsWith() with the following snippet: if (!String.prototype.startsWith) { ...
Symbol.keyFor() - JavaScript
ive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Symbol.keyFor(sym); Parameters sym Symbol, required. The symbol to find a key for. Return value A string representing the key for the given symbol if one is found on the global registry;
otherwise, undefined. Examples Using keyFor var globalSym = Symbol.for('foo'); // create a new global symbol Symbol.keyFor(globalSym); // "foo" var localSym = Symbol(); Symbol.keyFor(localSym); // undefined // well-known symbols are not symbols registered // in the global symbol registry Symbol.keyFor(Symbol.iterator) // undefined Specifications Specification ECMAScript (ECMA-262)...
Symbol - JavaScript
rimitive value. Symbol.toStringTag A string value used for the default description of an object. Used by Object.prototype.toString(). Symbol.unscopables An object value of whose own and inherited property names are excluded from the with environment bindings of the associated object. Static methods Symbol.for(key) Searches for existing symbols with the given key and returns it if found.
Otherwise a new symbol gets created in the global symbol registry with key. Symbol.keyFor(sym) Retrieves a shared symbol key from the global symbol registry for the given symbol. Instance properties Symbol.prototype.description A read-only string containing the description of the symbol. Instance methods Symbol.prototype.toSource() Returns a string containing the source of the Symbol object. ...
TypedArray.prototype.forEach() - JavaScript
nding order. It is not invoked for indexes that have been deleted or elided. However, it is executed for elements that are present and have the value undefined. callback is invoked with three arguments: the element value the element index the typed array being traversed If a thisArg parameter is provided to forEach(), it will be passed to callback when invoked, for use as its this value.
Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. The range of elements processed by forEach() is set before the first invocation of callback. Elements that are appended to the typed array after the call to forEach() begins will not be visited by c...
TypedArray.prototype.map() - JavaScript
hich have assigned values; it is not invoked for indexes that are undefined, those which have been deleted, or which have never been assigned values. mapFn is invoked with three arguments: the value of the element, the index of the element, and the typed array object being traversed. If a thisArg parameter is provided to map(), it will be passed to mapFn when invoked, for use as its this value.
Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by mapFn is determined according to the usual rules for determining the this seen by a function. map() does not mutate the typed array on which it is called (although mapFn, if invoked, may do so). The range of elements processed by map() is set before the first invocation of mapFn. Elements whic...
WeakMap.prototype.has() - JavaScript
in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax wm.has(key); Parameters key Required. The key of the element to test for presence in the WeakMap object. Return value Boolean Returns true if an element with the specified key exists in the WeakMap object;
otherwise false. Examples Using the has method var wm = new WeakMap(); wm.set(window, 'foo'); wm.has(window); // returns true wm.has('baz'); // returns false Specifications Specification ECMAScript (ECMA-262)The definition of 'WeakMap.prototype.has' in that specification. ...
WeakSet.prototype.has() - JavaScript
le is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax ws.has(value); Parameters value Required. The object to test for presence in the WeakSet. Return value Boolean Returns true if an element with the specified value exists in the WeakSet object;
otherwise false. Examples Using the has method var ws = new WeakSet(); var obj = {}; ws.add(window); mySet.has(window); // returns true mySet.has(obj); // returns false Specifications Specification ECMAScript (ECMA-262)The definition of 'WeakSet.prototype.has' in that specification. ...
WebAssembly.compile() - JavaScript
Syntax Promise<WebAssembly.Module> WebAssembly.compile(bufferSource); Parameters bufferSource A typed array or ArrayBuffer containing the binary code of the .wasm module you want to compile. Return value A Promise that resolves to a WebAssembly.Module object representing the compiled module. ...
WebAssembly.compileStreaming() - JavaScript
Syntax Promise<WebAssembly.Module> WebAssembly.compileStreaming(source); Parameters source A Response object or a promise that will fulfill with one, representing the underlying source of a .wasm module you want to stream and compile. ...
isFinite() - JavaScript
for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax isFinite(testValue) Parameters testValue The value to be tested for finiteness. Return value false if the argument is positive or negative Infinity or NaN or undefined;
otherwise, true. Description isFinite is a top-level function and is not associated with any object. You can use this function to determine whether a number is a finite number. The isFinite function examines the number in its argument. If the argument is NaN, positive infinity, or negative infinity, this method returns false;
otherwise, it returns true. Examples Using isFinite isFinite(Infinity); //...
isNaN() - JavaScript
The isNaN() function determines whether a value is NaN or not. Note, coercion inside the isNaN function has interesting rules; you may alternatively want to use Number.isNaN(), as defined in ECMAScript 2015. Syntax isNaN(value) Parameters value The value to be tested. Return value true if the given value is NaN;
otherwise, false. Description The necessity of an isNaN function Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false. Hence, the necessity of an isNaN function. Origin of NaN values NaN values are generated when arithmetic operations result in undefined or unrepresentable values. Such values do not necessarily r...
parseInt() - JavaScript
to truncate numbers will produce unexpected results when used on very large or very small numbers. parseInt should not be used as a substitute for Math.floor(). parseInt understands exactly two signs: + for positive, and - for negative (since ECMAScript 1). It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step;
otherwise, it removes the sign and runs the number-parsing on the rest of the string. If radix is undefined, 0, or unspecified, JavaScript assumes the following: If the input string begins with "0x" or "0X" (a zero, followed by lowercase or uppercase X), radix is assumed to be 16 and the rest of the string is parsed as a hexidecimal number. If the input string begins with "0" (a zero), radix is assume...
Greater than (>) - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x > y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. ...
Greater than or equal (>=) - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x >= y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. ...
Less than or equal (<=) - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x <= y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. ...
Logical NOT (!) - JavaScript
The logical NOT (!) operator (logical complement, negation) takes truth to falsity and vice versa. It is typically used with Boolean (logical) values. When used with non-Boolean values, it returns false if its single operand can be converted to true;
otherwise, returns true. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax !expr Description Returns false if its single operand can be converted to true;
otherwise, returns true. If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy. Examples of expressions that can be converted to f...
Nullish coalescing operator (??) - JavaScript
Contrary to the logical OR (||) operator, the left operand is returned if it is a falsy value which is not null or undefined. In other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you consider some falsy values as usable (eg. '' or 0). See below for more examples. The source for this interactive example is stored in a GitHub repository. ...
Spread syntax (...) - JavaScript
t() is often used to concatenate an array to the end of an existing array. Without spread syntax, this is done as: const arr1 = [0, 1, 2]; const arr2 = [3, 4, 5]; // Append all items from arr2 onto arr1 arr1 = arr1.concat(arr2); With spread syntax this becomes: let arr1 = [0, 1, 2]; let arr2 = [3, 4, 5]; arr1 = [...arr1, ...arr2]; // arr1 is now [0, 1, 2, 3, 4, 5] // Note: Not to use const
otherwise, it will give TypeError (invalid assignment) Array.prototype.unshift() is often used to insert an array of values at the start of an existing array. Without spread syntax, this is done as: const arr1 = [0, 1, 2]; const arr2 = [3, 4, 5]; // Prepend all items from arr2 onto arr1 Array.prototype.unshift.apply(arr1, arr2) // arr1 is now [3, 4, 5, 0, 1, 2] With spread syntax, this becomes: le...
Strict equality (===) - JavaScript
. Syntax x === y Description The strict equality operators (=== and !==) use the Strict Equality Comparison Algorithm to compare two operands. If the operands are of different types, return false. If both operands are objects, return true only if they refer to the same object. If both operands are null or both operands are undefined, return true. If either operand is NaN, return false.
Otherwise, compare the two operand's values: Numbers must have the same numeric values. +0 and -0 are considered to be the same value. Strings must have the same characters in the same order. Booleans must be both true or both false. The most notable difference between this operator and the equality (==) operator is that if the operands are of different types, the == operator attempts to...
new.target - JavaScript
keyword new, a dot, and the identifier target. Normally, the left-hand side of the dot is the object on which property access is performed, but here, new is not an object. The new.target pseudo-property is available in all functions. In class constructors, it refers to the constructed class. In ordinary functions, it refers to the function itself, assuming it was invoked via the new operator;
otherwise new.target is undefined. In arrow functions, new.target is inherited from the surrounding scope. Examples new.target in function calls In normal function calls (as opposed to constructor function calls), new.target is undefined. This lets you detect whether a function was called with new as a constructor. function Foo() { if (!new.target) { throw 'Foo() must be called with new' } console...
this - JavaScript
returned). /* * Constructors work like this: * * function MyConstructor(){ * // Actual function body code goes here. * // Create properties on |this| as * // desired by assigning to them. E.g., * this.fum = "nom"; * // et cetera... * * // If the function has a return statement that * // returns an object, that object will be the * // result of the |new| expression.
Otherwise, * // the result of the expression is the object * // currently bound to |this| * // (i.e., the common case most usually seen). * } */ function C() { this.a = 37; } var o = new C(); console.log(o.a); // 37 function C2() { this.a = 37; return {a: 38}; } o = new C2(); console.log(o.a); // 38 In the last example (C2), because an object was returned during construction, the ne...
var - JavaScript
o be non-configurable because the identifier is to be treated as a variable, rather than a straightforward property of the global object. JavaScript has automatic memory management, and it would make no sense to be able to use the delete operator on a global variable. 'use strict'; var x = 1; globalThis.hasOwnProperty('x'); // true delete globalThis.x; // TypeError in strict mode. Fails silently
otherwise. delete x; // SyntaxError in strict mode. Fails silently
otherwise. Note that in both NodeJS CommonJS modules and native ECMAScript modules, top-level variable declarations are scoped to the module, and are not, therefore added as properties to the global object. Unqualified identifier assignments The global object sits at the top of the scope chain. When attempting to resolve a name to a va...
with - JavaScript
searching a scope chain associated with the execution context of the script or function containing that unqualified name. The 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement body. If an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property.
Otherwise a ReferenceError is thrown. Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable. Performance pro & contra Pro: The with statement can help reduce file size by reducing the need to repeat a lengthy object reference without performance penalty. The scope chain ...
Strict mode - JavaScript
likely, in modern JavaScript). Assignments, which would accidentally create global variables, instead throw an error in strict mode: 'use strict'; // Assuming no global variable mistypedVariable exists mistypeVariable = 17; // this line throws a ReferenceError due to the // misspelling of variable Second, strict mode makes assignments which would
otherwise silently fail to throw an exception. For example, NaN is a non-writable global variable. In normal code assigning to NaN does nothing; the developer receives no failure feedback. In strict mode assigning to NaN throws an exception. Any assignment that silently fails in normal code (assignment to a non-writable global or property, assignment to a getter-only property, assignment to a new property ...
<mfrac> - MathML
This attribute is deprecated and will be removed in the future. ...
<mmultiscripts> - MathML
for both, postscripts and prescripts, attached to a base expression: <mmultiscripts> base (subscript superscript)* [ <mprescripts/> (presubscript presuperscript)* ] </mmultiscripts> After the base expression you can specify a postsubscript and a postsuperscript. Prescripts are optional and are separated by the empty tag <mprescripts/> (only one <mprescripts /> element is allowed,
otherwise you will get an DuplicateMprescripts error in the Error Console and "invalid-markup" in your rendering). In addition you are able to use <none/> as a placeholder for empty scripts (not for the base). See the examples section for a correct usage. Attributes class, id, style Provided for use with stylesheets. href Used to set a hyperlink to a specified URI. mathbackground The background co...
<mo> - MathML
uch as commas). Allowed values are true or false. stretchy Specifies whether the operator stretches to the size of the adjacent element. Allowed values are true or false. symmetric If stretchy is true, this attribute specifies whether the operator should be vertically symmetric around the imaginary math axis (centered fraction line). The default value is true if stretchy is set to true and
otherwise false. Allowed values are true or false. Examples <math> <mrow> <mn>5</mn> <mo>+</mo> <mn>5</mn> </mrow> <mrow> <mo> [ </mo> <!-- default form value: prefix --> <mrow> <mn> 0 </mn> <mo> ; </mo> <!-- default form value: infix --> <mn> 1 </mn> </mrow> <mo> ) </mo> <!-- default form value: postfix --> </mrow> </math> Specifications Specification Status ...
<semantics> - MathML
s understandable to computer algebra systems. The MathML elements <semantics>, <annotation> and <annotation-xml> are used to combine presentation and content markup and to provide both, layout information and semantic meaning of mathematical expressions. The <semantics> element acts as a container element associating annotations and must have child elements (it will raise an invalid markup error
otherwise). The <annotation> element is the container element containing semantic information in a non-XML format, whereas the <annotation-xml> element contains content in an XML format, e.g. Content MathML or OpenMath. The rules of determining the visible child in a <semantics> element are the following: If no rule other rule applies: By default only the first child is rendered, which is supposed to b...
Performance fundamentals - Web Performance
mations.js. Use CSS transforms Instead of tweaking absolute positioning and fiddling with all that math yourself, use the transform CSS property to adjust the position, scale, and so forth of your content. The reason is, once again, hardware acceleration. The browser can do these tasks on your GPU, letting the CPU handle other things. In addition, transforms give you capabilities you might not
otherwise have. Not only can you translate elements in 2D space, but you can transform in three dimensions, skew and rotate, and so forth. Paul Irish has an in-depth analysis of the benefits of translate() from a performance point of view. In general, however, you have the same benefits you get from using CSS animations: you use the right tool for the job and leave the optimization to the browser. You also...
How to make PWAs installable - Progressive web apps (PWAs)
ice's home screen, rather than the user having to open the browser and then navigate to the site by using a bookmark or typing the URL. Your web app can sit next to native applications as first class citizens. This makes the web app easier to access; additionally, you can specify that the app be launched in fullscreen or standalone mode, thus removing the default browser user interface that would
otherwise be present, creating an even more seamless and native-like feel. Requirements To make the web site installable, it needs the following things in place: A web manifest, with the correct fields filled in The web site to be served from a secure (HTTPS) domain An icon to represent the app on the device A service worker registered, to allow the app to work offline (this is required only by Chr...
Mobile first - Progressive web apps (PWAs)
ts with display: table set on them. I have included two links in my markup: <a id="top" href="#bottom">Jump to menu</a> ... <a id="bottom" href="#top">Back to top</a> The first one is to jump down from the top of the article to the navigation menu, and the second one is to jump back up to the top of the article again. ...
bias - SVG: Scalable Vector Graphics
The bias attribute shifts the range of the filter. After applying the kernelMatrix of the <feConvolveMatrix> element to the input image to yield a number and applied the divisor attribute, the bias attribute is added to each component. This allows representation of values that would
otherwise be clamped to 0 or 1. Usage notes Value <number> Default value 0 Animatable Yes One application of bias is when it is desirable to have 0.5 gray value be the zero response of the filter. Specifications Specification Status Comment Filter Effects Module Level 1The definition of 'bias' in that specification. Working Draft No change Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'bias' in that specific...
enable-background - SVG: Scalable Vector Graphics
Value accumulate | new [ <x> <y> <width> <height> ]? Default value accumulate Animatable No accumulate If an ancestor container element has a property value of enable-background: new, then all graphics elements within the current container element are rendered both onto the parent container element's background image canvas and onto the target device.
Otherwise, there is no current background image canvas, so graphics elements are only rendered onto the target device. new [ <x> <y> <width> <height> ]? This value enables the ability of children of the current container element to access the background image. It also indicates that a new (i.e., initially transparent black) background image canvas is established and that in effect all children of t...
fill-rule - SVG: Scalable Vector Graphics
rawing a ray from that point to infinity in any direction, and then examining the places where a segment of the shape crosses the ray. Starting with a count of zero, add one each time a path segment crosses the ray from left to right and subtract one each time a path segment crosses the ray from right to left. After counting the crossings, if the result is zero then the point is outside the path.
Otherwise, it is inside. Example html,body,svg { height:100% } <svg viewBox="-10 -10 320 120" xmlns="http://www.w3.org/2000/svg"> <!-- Effect of nonzero fill rule on crossing path segments --> <polygon fill-rule="nonzero" stroke="red" points="50,0 21,90 98,35 2,35 79,90"/> <!-- Effect of nonzero fill rule on a shape inside a shape with the path segment moving in the same directi...
glyph-orientation-horizontal - SVG: Scalable Vector Graphics
The glyph-orientation-horizontal attribute affects the amount that hte current text position advances as each glyph is rendered. When the reference orientation direction is horizontal and the glyph-orientation-horizontal results in an orientation angle that is a multiple of 180 degrees, then the current text position is incremented according to the horizontal metrics of the glyph.
Otherwise, if the value of this attribute is not a multiple of 180 degrees, then the current text position is incremented according to the vertical metrics of the glyph. This attribute is applied only to text written in a horizontal writing-mode. Note: As a presentation attribute, glyph-orientation-horizontal can be used as a CSS property. As a presentation attribute, it can be applied to any element but it has effe...
glyph-orientation-vertical - SVG: Scalable Vector Graphics
The glyph-orientation-vertical attribute affects the amount that hte current text position advances as each glyph is rendered. When the inline-progression-direction is vertical and the glyph-orientation-vertical results in an orientation angle that is a multiple of 180 degrees, then the current text position is incremented according to the vertical metrics of the glyph.
Otherwise, if the angle is not a multiple of 180 degrees, then the current text position is incremented according to the horizontal metrics of the glyph. This attribute is applied only to text written in a vertical writing-mode. Note: As a presentation attribute, glyph-orientation-vertical can be used as a CSS property. As a presentation attribute, it can be applied to any element but it has effect only on the following five e...
in - SVG: Scalable Vector Graphics
SourceAlpha This keyword represents the graphics elements that were the original input into the <filter> element. SourceAlpha has all of the same rules as SourceGraphic except that only the alpha channel is u...
requiredExtensions - SVG: Scalable Vector Graphics
Animatable No <list-of-extensions> The value is a list of references (IRI references in SVG 1, URL References in SVG 2) which identify the required extensions, with the individual values separated by white space. Determines whether all of the named extensions are supported by the user agent. If all of the given extensions are supported, then the attribute evaluates to true;
otherwise, the current element and its children are skipped and thus will not be rendered. Note: If a given extension reference contains white space within itself, that white space must be escaped. requiredExtensions is often used in conjunction with the <switch> element. If the attribute is used in other situations, then it represents a simple switch on the given element whether to render the element o...
requiredFeatures - SVG: Scalable Vector Graphics
The requiredFeatures attribute takes a list of feature strings, with the individual strings separated by white space. It determines whether or not all of the named features are supported by the browser; if all of them are supported, the attribute evaluates to true end the element is rendered;
otherwise, the attribute evaluates to false and the current element and its children are skipped and thus will not be rendered. This provides a way to design SVG that gracefully falls back when features aren't available. If the attribute is not present, then its implicit evaluated value is true. If a null string or empty string value is given to attribute requiredFeatures, the attribute is evaluate to false. requiredFeatures is often used in conjunction with the <switch> element. If requiredFeatures is use...
systemLanguage - SVG: Scalable Vector Graphics
hes, this may lead to situations where no content is displayed. It is thus recommended to include a "catch-all" choice at the end of such a <switch> which is acceptable in all cases. The attribute evaluates to "true" if one of the language tags indicated by user preferences is a case-insensitive match or prefix (followed by a "-") of one of the language tags given in the value of this parameter.
Otherwise it evaluates to "false". Note: The prefix matching rule does not imply that if a user understands a language with a certain tag, that the user will also understand all languages with the tag as prefix. If the attribute is not present, then it implicitly evaluates to "true". If a null string or empty string value is given, the attribute evaluates to "false". The prefix rule simply allows the us...
Content type - SVG: Scalable Vector Graphics
nt values. The grammar is as follows: icccolor ::= "icc-color(" name (, number)+ ")" The corresponding SVG DOM interface for <icccolor> is SVGICCColor. Integer <integer> An <integer> is specified as an optional sign character (+ or -) followed by one or more digits 0 to 9: integer ::= [+-]? [0-9]+ If the sign character is not present, the number is non-negative. Unless stated
otherwise for a particular attribute or property, the range for an <integer> encompasses (at a minimum) -2147483648 to 2147483647. Within the SVG DOM, an <integer> is represented as a number or an SVGAnimatedInteger. IRI <IRI> An Internationalized Resource Identifier. On the Internet, resources are identified using IRIs (Internationalized Resource Identifiers). For example, an SVG file called...
<cursor> - SVG: Scalable Vector Graphics
ormat is recommended because it supports the ability to define a transparency mask via an alpha channel. If a different image format is used, this format should support the definition of a transparency mask (two options: provide an explicit alpha channel or use a particular pixel color to indicate transparency). If the transparency mask can be determined, the mask defines the shape of the cursor;
otherwise, the cursor is an opaque rectangle. Typically, the other pixel information (e.g., the R, G and B channels) defines the colors for those parts of the cursor which are not masked out. Note that cursors usually contain at least two colors so that the cursor can be visible over most backgrounds. Usage context CategoriesNonePermitted contentAny number of the following elements, in any order:Descript...
<symbol> - SVG: Scalable Vector Graphics
<font-face>, <foreignObject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> Note: A <symbol> element itself is not meant to be rendered. Only instances of a <symbol> element (i.e., a reference to a <symbol> by a <use> element) are rendered. That means that some browsers could refuse to directly display a <symbol> element even if the CSS display property tells
otherwise. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of '<symbol>' in that specification. Candidate Recommendation Allowed geometry properties to be specified on a symbol Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of '<symbol>' in that specification. Recommendation Initial definition ...
How to turn off form autocompletion - Web security
the stored values. Additionally, the browser enables the user to choose a master password that the browser will use to encrypt stored login details. Even without a master password, in-browser password management is generally seen as a net gain for security. Since users do not have to remember passwords that the browser stores for them, they are able to choose stronger passwords than they would
otherwise. For this reason, many modern browsers do not support autocomplete="off" for login fields: If a site sets autocomplete="off" for a <form>, and the form includes username and password input fields, then the browser still offers to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page. If a site sets autocomplete="off" for us...
xml:base - XML: Extensible Markup Language
xml:base is like the HTML <base> element, but can specify the base URI per element as well as the entire document. The base URL of a element can be queried from a script using Node.baseURI. The base URI of an element is: the base URI specified by an xml:base attribute on the element, if one exists,
otherwise the base URI of the element's parent element within the document entity or external entity, if one exists,
otherwise the base URI of the document entity or external entity containing the element. Support was removed from blink (Chrome and Opera) in 2015: Chromium bug 341854 blink-dev mailing list post And from Firefox 66 in bug 903372. Use cases If you have an inline SVG you use as icons that needs to work in a document with a HTML BaseElement , you can reset the URI on your...
boolean - XPath
nctions, XPath axes The boolean function evaluates an expression and returns true or false. Syntax boolean( expression ) Arguments expression The expression to be evaluated. The expression can refer to numbers and node-sets as well as booleans. Returns Boolean true or false after evaluating expression. Notes A number evaluates to false if it is positive or negative zero or NaN.
Otherwise, it evaluates true. A node-set evaluates to true if it is non-empty. A string evaluates to false if it an empty string.
Otherwise, it evaluates to true. An object of a type other than the four basic types is converted to a boolean in a way that is dependent on that type. Defined XPath 1.0 4.3 Gecko support Supported. ...
choose - XPath
This method should be used instead of if(), which has been deprecated. Syntax choose( boolean , object1, object2 ) Arguments boolean The boolean operation to use when determining which object to return. object1 The first object to consider returning. object2 The second object to consider returning. Returns If the boolean parameter is true, the first object is returned;
otherwise, the second object is returned. Note: All parameters are evaluated, even the one that's not returned. Defined XForms 1.1 Gecko support Supported. ...
element-available - XPath
ntax element-available(QName ) Arguments QName Must evaluate to a valid QName. The QName is expanded into an expanded-name using the namespace declarations in scope for the expression. Returns Returns true if and only if the expanded-name is the name of an instruction. If the expanded-name has a namespace URI equal to the XSLT namespace URI, then it refers to an element defined by XSLT.
Otherwise, it refers to an extension element. If the expanded-name has a null namespace URI, the element-available function will return false. Defined XSLT 1.0 15 Gecko support Supported. ...
lang - XPath
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The lang function determines whether the context node matches the given language and returns boolean true or false. Syntax lang(string ) Arguments string The language code or localization (language and country) code to be matched. Returns true if the context node matches the given languages.
Otherwise, false. Notes A node's language is determined by its xml:lang attribute. If the current node does not have an xml:lang attribute, then the value of the xml:lang attribute of the nearest ancestor that has an xml:lang attribute will determine the current node's language. If the language cannot be determined (no ancestor has an xml:lang attribute), this function will return false. If the giv...
unparsed-entity-url - XPath
the unparsed entity with the given name. This is non-XML data referenced in the DTD of the source document. Syntax string unparsed-entity-url(string) Arguments The name of the unparsed entity. If the argument is not a string, it is converted using the rules of the string() function. The name should be an XML Name. Returns The URI of the unparsed entity retrieved from the DTD, if it exists.
Otherwise an empty string. Defined XSLT 1.0 12.4 Gecko support Not supported. ...
XPath snippets - XPath
that case the creation of the XPathNSResolver can be simplified as: var nsResolver = xpe.createNSResolver(xpe.documentElement); Note however that createNSResolver should only be used if you are sure the namespace prefixes in the XPath expression match those in the document you want to query (and that no default namespace is being used (though see document.createNSResolver for a workaround)).
Otherwise, you have to provide your own implementation of XPathNSResolver. If you are using XMLHttpRequest to read a local or remote XML file into a DOM tree (as described in Parsing and serializing XML), the first argument to evaluateXPath() should be req.responseXML. Sample usage Assume we have the following XML document (see also How to Create a DOM tree and Parsing and serializing XML): Example: An...
<xsl:choose> - XSLT: Extensible Stylesheet Language Transformations
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The <xsl:choose> element defines a choice among a number of alternatives. It behaves like a switch statement in procedural languages. Syntax <xsl:choose> <xsl:when test="[whatever to test1]"></xsl:when> <xsl:when test="[whatever to test2]"></xsl:when> <xsl:
otherwise></xsl:
otherwise> [optional] </xsl:choose> Required Attributes None. Optional Attributes None. Type Instruction, appears with a template. It contains one or more <xsl:when> elements, and, optionally, a final <xsl:
otherwise> element. Defined XSLT, section 9.2. Gecko support Supported. ...
<xsl:for-each> - XSLT: Extensible Stylesheet Language Transformations
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The <xsl:for-each> element selects a set of nodes and processes each of them in the same way. It is often used to iterate through a set of nodes or to change the current node. If one or more <xsl:sort> elements appear as the children of this element, sorting occurs before processing.
Otherwise, nodes are processed in document order. Syntax <xsl:for-each select=EXPRESSION> <xsl:sort> [optional] TEMPLATE </xsl:for-each> Required Attributes select Uses an XPath expression to select nodes to be processed. Optional Attributes None. Type Instruction, appears within a template. Defined XSLT, section 8. Gecko support Supported. ...
<xsl:if> - XSLT: Extensible Stylesheet Language Transformations
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The <xsl:if> element contains a test attribute and a template. If the test evaluates to true, the template is processed. In this it is similar to an if statement in other languages. To achieve the functionality of an if-then-else statement, however, use the <xsl:choose> element with one <xsl:when> and one <xsl:
otherwise> children. Syntax <xsl:if test=EXPRESSION> TEMPLATE </xsl:if> Required Attributes test Contains an XPath expression that can be evaluated (using the rules defined for boolean( ) if necessary) to a Boolean value. If the value is true, the template is processed; if it is not, no action is taken. Optional Attributes None. Type Instruction, appears within a template. Defined XSL sectio...
The Netscape XSLT/XPath Reference - XSLT: Extensible Stylesheet Language Transformations
d) xsl:comment (supported) xsl:copy (supported) xsl:copy-of (supported) xsl:decimal-format (supported) xsl:element (supported) xsl:fallback (not supported) xsl:for-each (supported) xsl:if (supported) xsl:import (mostly supported) xsl:include (supported) xsl:key (supported) xsl:message (supported) xsl:namespace-alias (not supported) xsl:number (partially supported) xsl:
otherwise (supported) xsl:output (partially supported) xsl:param (supported) xsl:preserve-space (supported) xsl:processing-instruction xsl:sort (supported) xsl:strip-space (supported) xsl:stylesheet (partially supported) xsl:template (supported) xsl:text (partially supported) xsl:transform (supported) xsl:value-of (partially supported) xsl:variable (supported) xsl:when (supported)...
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
oose (supported) xsl:comment (supported) xsl:copy (supported) xsl:copy-of (supported) xsl:decimal-format (supported) xsl:element (supported) xsl:fallback (not supported) xsl:for-each (supported) xsl:if (supported) xsl:import (mostly supported) xsl:include (supported) xsl:key (supported) xsl:message (supported) xsl:namespace-alias (not supported) xsl:number (partially supported) xsl:
otherwise (supported) xsl:output (partially supported) xsl:param (supported) xsl:preserve-space (supported) xsl:processing-instruction xsl:sort (supported) xsl:strip-space (supported) xsl:stylesheet (partially supported) xsl:template (supported) xsl:text (partially supported) xsl:transform (supported) xsl:value-of (partially supported) xsl:variable (supported) xsl:when (supported) xsl:with-pa...
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
nous, so all processing happens in the // onload handler testTransform.addEventListener("load", onload, false); testTransform.load("test-transform.xml"); function onload() { processor.importStylesheet(testTransform); } XSLTProcessor.importStylesheet() requires one argument, a DOM Node. If that node is a document node, you can pass in a full XSL Transform or a literal result element transform,
otherwise it must be an xsl:stylesheet or xsl:transform element. Transforming the document You can use the XSLTProcessor.transformToDocument() or XSLTProcessor.transformToFragment() methods to transform a document using the imported XSLT stylesheet. transformToDocument XSLTProcessor.transformToDocument() takes one argument, the source node to transform, and returns a new Document with the results of th...